source: opengl-game/new-game.cpp@ 9f4986b

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

Change the square's selected color to a darker blue-green

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