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

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

Start incorporating UBOs

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