source: opengl-game/new-game.cpp@ 1a530df

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

Design an algorithm for rendering objects using colors or shaders and try to use a ubo for storing model matrices

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