source: opengl-game/new-game.cpp@ 4f3262f

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

Move all function definitions in new-game.cpp after main.

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