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

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

Add code to create a fullscreen window, which will be used to create the main menu screen.

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