source: opengl-game/new-game.cpp@ 7280257

feature/imgui-sdl points-test
Last change on this file since 7280257 was 7280257, checked in by Dmitry Portnoy <dmitry.portnoy@…>, 7 years ago

Remove uniform buffer code until I figure out how to use it correctly.

  • Property mode set to 100644
File size: 23.4 KB
Line 
1#include "logger.h"
2
3#include "stb_image.h"
4
5#define _USE_MATH_DEFINES
6#define GLM_SWIZZLE
7
8// This is to fix a non-alignment issue when passing vec4 params.
9// Check if it got fixed in a later version of GLM
10#define GLM_FORCE_PURE
11
12#include <glm/mat4x4.hpp>
13#include <glm/gtc/matrix_transform.hpp>
14#include <glm/gtc/type_ptr.hpp>
15
16#include <GL/glew.h>
17#include <GLFW/glfw3.h>
18
19#include <cstdio>
20#include <iostream>
21#include <fstream>
22#include <cmath>
23#include <string>
24#include <array>
25#include <vector>
26
27using namespace std;
28using namespace glm;
29
30#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
31
32/*
33 * If I use one array to store the points for all the object faces in the scene, I'll probably remove the ObjectFace object,
34 * and store the start and end indices of a given object's point coordinates in that array in the SceneObject.
35 *
36 * Should probably do something similar with colors and texture coordinates, once I figure out the best way to store tex coords
37 * for all objects in one array.
38 */
39
40
41// might also want to store the shader to be used for the object
42struct SceneObject {
43 mat4 model_mat;
44 GLuint shader_program;
45};
46
47struct ObjectFace {
48 unsigned int object_id;
49 array<vec3, 3> points;
50};
51
52const bool FULLSCREEN = false;
53int width = 640;
54int height = 480;
55
56vec3 cam_pos;
57
58mat4 view_mat;
59mat4 proj_mat;
60
61vector<SceneObject> objects;
62vector<ObjectFace> faces;
63
64SceneObject* clickedObject = NULL;
65SceneObject* selectedObject;
66
67double fps;
68
69bool faceClicked(ObjectFace* face, vec4 world_ray, vec4 cam, vec4& click_point);
70bool insideTriangle(vec3 p, array<vec3, 3> triangle_points);
71
72GLuint loadShader(GLenum type, string file);
73GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath);
74unsigned char* loadImage(string file_name, int* x, int* y);
75
76void printVector(string label, vec3 v);
77void print4DVector(string label, vec4 v);
78
79float NEAR_CLIP = 0.1f;
80float FAR_CLIP = 100.0f;
81
82void glfw_error_callback(int error, const char* description) {
83 gl_log_err("GLFW ERROR: code %i msg: %s\n", error, description);
84}
85
86void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
87 double mouse_x, mouse_y;
88 glfwGetCursorPos(window, &mouse_x, &mouse_y);
89
90 if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
91 cout << "Mouse clicked (" << mouse_x << "," << mouse_y << ")" << endl;
92 selectedObject = NULL;
93
94 float x = (2.0f*mouse_x) / width - 1.0f;
95 float y = 1.0f - (2.0f*mouse_y) / height;
96
97 cout << "x: " << x << ", y: " << y << endl;
98
99 vec4 ray_clip = vec4(x, y, -1.0f, 1.0f);
100 vec4 ray_eye = inverse(proj_mat) * ray_clip;
101 ray_eye = vec4(ray_eye.xy(), -1.0f, 1.0f);
102 vec4 ray_world = inverse(view_mat) * ray_eye;
103
104 vec4 cam_pos_temp = vec4(cam_pos, 1.0f);
105
106 vec4 click_point;
107 vec3 closest_point = vec3(0.0f, 0.0f, -FAR_CLIP); // Any valid point will be closer than the far clipping plane, so initial value to that
108 int closest_face_id = -1;
109
110 for (int i = 0; i<faces.size(); i++) {
111 if (faceClicked(&faces[i], ray_world, cam_pos_temp, click_point)) {
112 click_point = view_mat * click_point;
113
114 if (-NEAR_CLIP >= click_point.z && click_point.z > -FAR_CLIP && click_point.z > closest_point.z) {
115 closest_point = click_point.xyz();
116 closest_face_id = i;
117 }
118 }
119 }
120
121 if (closest_face_id == -1) {
122 cout << "No object was clicked" << endl;
123 } else {
124 clickedObject = &objects[faces[closest_face_id].object_id];
125 cout << "Clicked object: " << faces[closest_face_id].object_id << endl;
126 }
127 }
128}
129
130int main(int argc, char* argv[]) {
131 cout << "New OpenGL Game" << endl;
132
133 if (!restart_gl_log()) {}
134 gl_log("starting GLFW\n%s\n", glfwGetVersionString());
135
136 glfwSetErrorCallback(glfw_error_callback);
137 if (!glfwInit()) {
138 fprintf(stderr, "ERROR: could not start GLFW3\n");
139 return 1;
140 }
141
142#ifdef __APPLE__
143 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
144 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
145 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
146 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
147#endif
148
149 glfwWindowHint(GLFW_SAMPLES, 4);
150
151 GLFWwindow* window = NULL;
152 GLFWmonitor* mon = NULL;
153
154 if (FULLSCREEN) {
155 mon = glfwGetPrimaryMonitor();
156 const GLFWvidmode* vmode = glfwGetVideoMode(mon);
157
158 width = vmode->width;
159 height = vmode->height;
160 cout << "Fullscreen resolution " << vmode->width << "x" << vmode->height << endl;
161 }
162 window = glfwCreateWindow(width, height, "New OpenGL Game", mon, NULL);
163
164 if (!window) {
165 fprintf(stderr, "ERROR: could not open window with GLFW3\n");
166 glfwTerminate();
167 return 1;
168 }
169
170 glfwSetMouseButtonCallback(window, mouse_button_callback);
171
172 glfwMakeContextCurrent(window);
173 glewExperimental = GL_TRUE;
174 glewInit();
175
176 const GLubyte* renderer = glGetString(GL_RENDERER);
177 const GLubyte* version = glGetString(GL_VERSION);
178 printf("Renderer: %s\n", renderer);
179 printf("OpenGL version supported %s\n", version);
180
181 glEnable(GL_DEPTH_TEST);
182 glDepthFunc(GL_LESS);
183
184 glEnable(GL_CULL_FACE);
185 // glCullFace(GL_BACK);
186 // glFrontFace(GL_CW);
187
188 int x, y;
189 unsigned char* texImage = loadImage("test.png", &x, &y);
190 if (texImage) {
191 cout << "Yay, I loaded an image!" << endl;
192 cout << x << endl;
193 cout << y << endl;
194 printf("first 4 bytes are: %i %i %i %i\n", texImage[0], texImage[1], texImage[2], texImage[3]);
195 }
196
197 GLuint tex = 0;
198 glGenTextures(1, &tex);
199 glActiveTexture(GL_TEXTURE0);
200 glBindTexture(GL_TEXTURE_2D, tex);
201 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage);
202
203 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
204 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
205 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
206 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
207
208 GLfloat points[] = {
209 0.0f, 0.5f, 0.0f,
210 -0.5f, -0.5f, 0.0f,
211 0.5f, -0.5f, 0.0f,
212 0.5f, -0.5f, 0.0f,
213 -0.5f, -0.5f, 0.0f,
214 0.0f, 0.5f, 0.0f,
215 };
216
217 GLfloat colors[] = {
218 1.0, 0.0, 0.0,
219 0.0, 0.0, 1.0,
220 0.0, 1.0, 0.0,
221 0.0, 1.0, 0.0,
222 0.0, 0.0, 1.0,
223 1.0, 0.0, 0.0,
224 };
225
226 GLfloat colors_new[] = {
227 0.0, 1.0, 0.0,
228 0.0, 1.0, 0.0,
229 0.0, 1.0, 0.0,
230 0.0, 1.0, 0.0,
231 0.0, 1.0, 0.0,
232 0.0, 1.0, 0.0,
233 };
234
235 // Each point is made of 3 floats
236 int numPoints = (sizeof(points) / sizeof(float)) / 3;
237
238 GLfloat points2[] = {
239 0.5f, 0.5f, 0.0f,
240 -0.5f, 0.5f, 0.0f,
241 -0.5f, -0.5f, 0.0f,
242 0.5f, 0.5f, 0.0f,
243 -0.5f, -0.5f, 0.0f,
244 0.5f, -0.5f, 0.0f,
245 };
246
247 GLfloat colors2[] = {
248 0.0, 0.9, 0.9,
249 0.0, 0.9, 0.9,
250 0.0, 0.9, 0.9,
251 0.0, 0.9, 0.9,
252 0.0, 0.9, 0.9,
253 0.0, 0.9, 0.9,
254 };
255
256 GLfloat texcoords[] = {
257 1.0f, 1.0f,
258 0.0f, 1.0f,
259 0.0, 0.0,
260 1.0, 1.0,
261 0.0, 0.0,
262 1.0, 0.0
263 };
264
265 // Each point is made of 3 floats
266 int numPoints2 = (sizeof(points2) / sizeof(float)) / 3;
267
268 mat4 T_model, R_model;
269
270 // triangle
271 objects.push_back(SceneObject());
272 objects[0].shader_program = 0;
273
274 T_model = translate(mat4(), vec3(0.45f, 0.0f, 0.0f));
275 R_model = rotate(mat4(), 0.0f, vec3(0.0f, 1.0f, 0.0f));
276 objects[0].model_mat = T_model*R_model;
277
278 faces.push_back(ObjectFace());
279 faces[0].object_id = 0;
280 faces[0].points = {
281 vec3(points[0], points[1], points[2]),
282 vec3(points[3], points[4], points[5]),
283 vec3(points[6], points[7], points[8]),
284 };
285
286 // square
287 objects.push_back(SceneObject());
288 objects[1].shader_program = 0;
289
290 T_model = translate(mat4(), vec3(-0.5f, 0.0f, -1.00f));
291 R_model = rotate(mat4(), 0.5f, vec3(0.0f, 1.0f, 0.0f));
292 objects[1].model_mat = T_model*R_model;
293
294 faces.push_back(ObjectFace());
295 faces[1].object_id = 1;
296 faces[1].points = {
297 vec3(points2[0], points2[1], points2[2]),
298 vec3(points2[3], points2[4], points2[5]),
299 vec3(points2[6], points2[7], points2[8]),
300 };
301
302 faces.push_back(ObjectFace());
303 faces[2].object_id = 1;
304 faces[2].points = {
305 vec3(points2[9], points2[10], points2[11]),
306 vec3(points2[12], points2[13], points2[14]),
307 vec3(points2[15], points2[16], points2[17]),
308 };
309
310 GLuint points_vbo = 0;
311 glGenBuffers(1, &points_vbo);
312 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
313 glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
314
315 GLuint colors_vbo = 0;
316 glGenBuffers(1, &colors_vbo);
317 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
318 glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
319
320 GLuint vao = 0;
321 glGenVertexArrays(1, &vao);
322 glBindVertexArray(vao);
323 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
324 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
325 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
326 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
327
328 glEnableVertexAttribArray(0);
329 glEnableVertexAttribArray(1);
330
331 GLuint points2_vbo = 0;
332 glGenBuffers(1, &points2_vbo);
333 glBindBuffer(GL_ARRAY_BUFFER, points2_vbo);
334 glBufferData(GL_ARRAY_BUFFER, sizeof(points2), points2, GL_STATIC_DRAW);
335
336 GLuint colors2_vbo = 0;
337 glGenBuffers(1, &colors2_vbo);
338 glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo);
339 glBufferData(GL_ARRAY_BUFFER, sizeof(colors2), colors2, GL_STATIC_DRAW);
340
341 GLuint vt_vbo;
342 glGenBuffers(1, &vt_vbo);
343 glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
344 glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW);
345
346 GLuint vao2 = 0;
347 glGenVertexArrays(1, &vao2);
348 glBindVertexArray(vao2);
349 glBindBuffer(GL_ARRAY_BUFFER, points2_vbo);
350 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
351 // glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo);
352 // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
353 glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
354 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
355
356 glEnableVertexAttribArray(0);
357 glEnableVertexAttribArray(1);
358
359 // I can create a vbo to store all points for all models,
360 // and another vbo to store all colors for all models, but how do I allow alternating between
361 // using colors and textures for each model?
362 // Do I create a third vbo for texture coordinates and change which vertex attribute array I have bound
363 // when I want to draw a textured model?
364 // Or do I create one vao with vertices and colors and another with vertices and textures and switch between the two?
365 // Since I would have to switch shader programs to toggle between using colors or textures,
366 // I think I should use one vao for both cases and have a points vbo, a colors vbo, and a textures vbo
367 // One program will use the points and colors, and the other will use the points and texture coords
368 // Review how to bind vbos to vertex attributes in the shader.
369 //
370 // Binding vbos is done using glVertexAttribPointer(...) on a per-vao basis and is not tied to any specific shader.
371 // This means, I could create two vaos, one for each shader and have one use points+colors, while the other
372 // uses points+texxcoords.
373 //
374 // At some point, when I have lots of objects, I want to group them by shader when drawing them.
375 // I'd probably create some sort of set per shader and have each set contain the ids of all objects currently using that shader
376 // Most likely, I'd want to implement each set using a bit field. Makes it constant time for updates and iterating through them
377 // should not be much of an issue either.
378 // Assuming making lots of draw calls instead of one is not innefficient, I should be fine.
379 // I might also want to use one glDrawElements call per shader to draw multiple non-memory-adjacent models
380 //
381 // DECISION: Use a glDrawElements call per shader since I use a regular array to specify the elements to draw
382 // Actually, this will only work once I get UBOs working since each object will have a different model matrix
383 // For now, I could implement this with a glDrawElements call per object and update the model uniform for each object
384
385 GLuint shader_program = loadShaderProgram("./color.vert", "./color.frag");
386 GLuint shader_program2 = loadShaderProgram("./texture.vert", "./texture.frag");
387
388 float speed = 1.0f;
389 float last_position = 0.0f;
390
391 float cam_speed = 1.0f;
392 float cam_yaw_speed = 60.0f*ONE_DEG_IN_RAD;
393
394 // glm::lookAt can create the view matrix
395 // glm::perspective can create the projection matrix
396
397 cam_pos = vec3(0.0f, 0.0f, 2.0f);
398 float cam_yaw = 0.0f * 2.0f * 3.14159f / 360.0f;
399
400 mat4 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
401 mat4 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
402 view_mat = R*T;
403
404 float fov = 67.0f * ONE_DEG_IN_RAD;
405 float aspect = (float)width / (float)height;
406
407 float range = tan(fov * 0.5f) * NEAR_CLIP;
408 float Sx = NEAR_CLIP / (range * aspect);
409 float Sy = NEAR_CLIP / range;
410 float Sz = -(FAR_CLIP + NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP);
411 float Pz = -(2.0f * FAR_CLIP * NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP);
412
413 float proj_arr[] = {
414 Sx, 0.0f, 0.0f, 0.0f,
415 0.0f, Sy, 0.0f, 0.0f,
416 0.0f, 0.0f, Sz, -1.0f,
417 0.0f, 0.0f, Pz, 0.0f,
418 };
419 proj_mat = make_mat4(proj_arr);
420
421 GLint model_test_loc = glGetUniformLocation(shader_program, "model");
422 GLint view_test_loc = glGetUniformLocation(shader_program, "view");
423 GLint proj_test_loc = glGetUniformLocation(shader_program, "proj");
424
425 GLint model_mat_loc = glGetUniformLocation(shader_program2, "model");
426 GLint view_mat_loc = glGetUniformLocation(shader_program2, "view");
427 GLint proj_mat_loc = glGetUniformLocation(shader_program2, "proj");
428
429 glUseProgram(shader_program);
430 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[0].model_mat));
431 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
432 glUniformMatrix4fv(proj_test_loc, 1, GL_FALSE, value_ptr(proj_mat));
433
434 glUseProgram(shader_program2);
435 glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[1].model_mat));
436 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
437 glUniformMatrix4fv(proj_mat_loc, 1, GL_FALSE, value_ptr(proj_mat));
438
439 objects[0].shader_program = shader_program;
440 objects[1].shader_program = shader_program2;
441
442 vector<int> program1_objects, program2_objects;
443 vector<int>::iterator it;
444
445 bool cam_moved = false;
446
447 int frame_count = 0;
448 double elapsed_seconds_fps = 0.0f;
449 double previous_seconds = glfwGetTime();
450
451 while (!glfwWindowShouldClose(window)) {
452 double current_seconds = glfwGetTime();
453 double elapsed_seconds = current_seconds - previous_seconds;
454 previous_seconds = current_seconds;
455
456 elapsed_seconds_fps += elapsed_seconds;
457 if (elapsed_seconds_fps > 0.25f) {
458 fps = (double)frame_count / elapsed_seconds_fps;
459 cout << "FPS: " << fps << endl;
460
461 frame_count = 0;
462 elapsed_seconds_fps = 0.0f;
463 }
464
465 frame_count++;
466
467 if (fabs(last_position) > 1.0f) {
468 speed = -speed;
469 }
470
471 program1_objects.clear();
472 program2_objects.clear();
473
474 // Handle events (Ideally, move all event-handling code
475 // before the render code)
476
477 clickedObject = NULL;
478 glfwPollEvents();
479
480 if (clickedObject == &objects[0]) {
481 selectedObject = &objects[0];
482 }
483 if (clickedObject == &objects[1]) {
484 selectedObject = &objects[1];
485 }
486
487 if (selectedObject == &objects[1] &&
488 objects[1].shader_program == shader_program2) {
489 objects[1].shader_program = shader_program;
490 } else if (selectedObject != &objects[1] &&
491 objects[1].shader_program == shader_program) {
492 objects[1].shader_program = shader_program2;
493 }
494
495 // group scene objects by shader
496 for (int i=0; i < objects.size(); i++) {
497 if (objects[i].shader_program == shader_program) {
498 program1_objects.push_back(i);
499 } else if (objects[i].shader_program == shader_program2) {
500 program2_objects.push_back(i);
501 }
502 }
503
504 /*
505 model[12] = last_position + speed*elapsed_seconds;
506 last_position = model[12];
507 */
508
509 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
510
511 glUseProgram(shader_program);
512 glBindVertexArray(vao);
513
514 for (it=program1_objects.begin(); it != program1_objects.end(); it++) {
515 glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
516
517 if (selectedObject == &objects[*it]) {
518 if (*it == 1) {
519 glBindBuffer(GL_ARRAY_BUFFER, points2_vbo);
520 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
521
522 glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo);
523 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
524
525 glDrawArrays(GL_TRIANGLES, 0, numPoints2);
526 } else {
527 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
528 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
529
530 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
531 glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors_new, GL_STATIC_DRAW);
532 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
533
534 glDrawArrays(GL_TRIANGLES, 0, numPoints);
535 }
536 } else {
537 glBindBuffer(GL_ARRAY_BUFFER, points_vbo);
538 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
539
540 glBindBuffer(GL_ARRAY_BUFFER, colors_vbo);
541 glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
542 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
543
544 glDrawArrays(GL_TRIANGLES, 0, numPoints);
545 }
546 }
547
548 glUseProgram(shader_program2);
549 glBindVertexArray(vao2);
550
551 for (it = program2_objects.begin(); it != program2_objects.end(); it++) {
552 glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat));
553
554 glDrawArrays(GL_TRIANGLES, 0, numPoints2);
555 }
556
557 glfwSwapBuffers(window);
558
559 if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) {
560 glfwSetWindowShouldClose(window, 1);
561 }
562
563 float dist = cam_speed * elapsed_seconds;
564 if (glfwGetKey(window, GLFW_KEY_A)) {
565 cam_pos.x -= cos(cam_yaw)*dist;
566 cam_pos.z += sin(cam_yaw)*dist;
567 cam_moved = true;
568 }
569 if (glfwGetKey(window, GLFW_KEY_D)) {
570 cam_pos.x += cos(cam_yaw)*dist;
571 cam_pos.z -= sin(cam_yaw)*dist;
572 cam_moved = true;
573 }
574 if (glfwGetKey(window, GLFW_KEY_W)) {
575 cam_pos.x -= sin(cam_yaw)*dist;
576 cam_pos.z -= cos(cam_yaw)*dist;
577 cam_moved = true;
578 }
579 if (glfwGetKey(window, GLFW_KEY_S)) {
580 cam_pos.x += sin(cam_yaw)*dist;
581 cam_pos.z += cos(cam_yaw)*dist;
582 cam_moved = true;
583 }
584 if (glfwGetKey(window, GLFW_KEY_LEFT)) {
585 cam_yaw += cam_yaw_speed * elapsed_seconds;
586 cam_moved = true;
587 }
588 if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
589 cam_yaw -= cam_yaw_speed * elapsed_seconds;
590 cam_moved = true;
591 }
592 if (cam_moved) {
593 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z));
594 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f));
595 view_mat = R*T;
596
597 glUseProgram(shader_program);
598 glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat));
599
600 glUseProgram(shader_program2);
601 glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat));
602
603 cam_moved = false;
604 }
605 }
606
607 glfwTerminate();
608 return 0;
609}
610
611GLuint loadShader(GLenum type, string file) {
612 cout << "Loading shader from file " << file << endl;
613
614 ifstream shaderFile(file);
615 GLuint shaderId = 0;
616
617 if (shaderFile.is_open()) {
618 string line, shaderString;
619
620 while(getline(shaderFile, line)) {
621 shaderString += line + "\n";
622 }
623 shaderFile.close();
624 const char* shaderCString = shaderString.c_str();
625
626 shaderId = glCreateShader(type);
627 glShaderSource(shaderId, 1, &shaderCString, NULL);
628 glCompileShader(shaderId);
629
630 cout << "Loaded successfully" << endl;
631 } else {
632 cout << "Failed to load the file" << endl;
633 }
634
635 return shaderId;
636}
637
638GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) {
639 GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath);
640 GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath);
641
642 GLuint shader_program = glCreateProgram();
643 glAttachShader(shader_program, vs);
644 glAttachShader(shader_program, fs);
645
646 glLinkProgram(shader_program);
647
648 return shader_program;
649}
650
651unsigned char* loadImage(string file_name, int* x, int* y) {
652 int n;
653 int force_channels = 4; // This forces RGBA (4 bytes per pixel)
654 unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels);
655
656 int width_in_bytes = *x * 4;
657 unsigned char *top = NULL;
658 unsigned char *bottom = NULL;
659 unsigned char temp = 0;
660 int half_height = *y / 2;
661
662 // flip image upside-down to account for OpenGL treating lower-left as (0, 0)
663 for (int row = 0; row < half_height; row++) {
664 top = image_data + row * width_in_bytes;
665 bottom = image_data + (*y - row - 1) * width_in_bytes;
666 for (int col = 0; col < width_in_bytes; col++) {
667 temp = *top;
668 *top = *bottom;
669 *bottom = temp;
670 top++;
671 bottom++;
672 }
673 }
674
675 if (!image_data) {
676 fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str());
677 }
678
679 // Not Power-of-2 check
680 if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) {
681 fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str());
682 }
683
684 return image_data;
685}
686
687bool faceClicked(ObjectFace* face, vec4 world_ray, vec4 cam, vec4& click_point) {
688 // LINE EQUATION: P = O + Dt
689 // O = cam
690 // D = ray_world
691
692 // PLANE EQUATION: P dot n + d = 0
693 // n is the normal vector
694 // d is the offset from the origin
695
696 // Take the cross-product of two vectors on the plane to get the normal
697 vec3 v1 = face->points[1] - face->points[0];
698 vec3 v2 = face->points[2] - face->points[0];
699
700 vec3 normal = vec3(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
701
702 print4DVector("Full world ray", world_ray);
703
704 SceneObject* obj = &objects[face->object_id];
705 vec3 local_ray = (inverse(obj->model_mat) * world_ray).xyz();
706 vec3 local_cam = (inverse(obj->model_mat) * cam).xyz();
707
708 local_ray = local_ray - local_cam;
709
710 float d = -glm::dot(face->points[0], normal);
711 cout << "d: " << d << endl;
712
713 float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal);
714 cout << "t: " << t << endl;
715
716 vec3 intersection = local_cam + t*local_ray;
717 printVector("Intersection", intersection);
718
719 if (insideTriangle(intersection, face->points)) {
720 click_point = obj->model_mat * vec4(intersection, 1.0f);
721 return true;
722 } else {
723 return false;
724 }
725}
726
727bool insideTriangle(vec3 p, array<vec3, 3> triangle_points) {
728 vec3 v21 = triangle_points[1]- triangle_points[0];
729 vec3 v31 = triangle_points[2]- triangle_points[0];
730 vec3 pv1 = p- triangle_points[0];
731
732 float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y);
733 float x = (pv1.x-y*v31.x) / v21.x;
734
735 cout << "(" << x << ", " << y << ")" << endl;
736
737 return x > 0.0f && y > 0.0f && x+y < 1.0f;
738}
739
740void printVector(string label, vec3 v) {
741 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl;
742}
743
744void print4DVector(string label, vec4 v) {
745 cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl;
746}
Note: See TracBrowser for help on using the repository browser.