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

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

Create a new rendering algorithm that supports a variable number of objects in the scene.

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