source: opengl-game/new-game.cpp@ 07ed460

feature/imgui-sdl points-test
Last change on this file since 07ed460 was 07ed460, checked in by Dmitry Portnoy <dmp1488@…>, 7 years ago

Move all the point and color data into the SceneObjects and populate all the different vbos by looping over all the SceneObjects.

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