source: opengl-game/new-game.cpp@ 14ff67c

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

Use uniform buffers to store model matrices and add constants to toggle FPS display and vsync.

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