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

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

Show the example ImGui gui in the OpenGL game.

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