#include "logger.h" #include "stb_image.h" #define _USE_MATH_DEFINES #define GLM_SWIZZLE // This is to fix a non-alignment issue when passing vec4 params. // Check if it got fixed in a later version of GLM #define GLM_FORCE_PURE #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace glm; #define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444 /* * If I use one array to store the points for all the object faces in the scene, I'll probably remove the ObjectFace object, * and store the start and end indices of a given object's point coordinates in that array in the SceneObject. * * Should probably do something similar with colors and texture coordinates, once I figure out the best way to store tex coords * for all objects in one array. */ // might also want to store the shader to be used for the object struct SceneObject { mat4 model_mat; GLuint shader_program; GLvoid* vbo_offset; unsigned int num_points; }; struct ObjectFace { unsigned int object_id; array points; }; const bool FULLSCREEN = false; int width = 640; int height = 480; vec3 cam_pos; mat4 view_mat; mat4 proj_mat; vector objects; vector faces; SceneObject* clickedObject = NULL; SceneObject* selectedObject; double fps; bool faceClicked(ObjectFace* face, vec4 world_ray, vec4 cam, vec4& click_point); bool insideTriangle(vec3 p, array triangle_points); GLuint loadShader(GLenum type, string file); GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath); unsigned char* loadImage(string file_name, int* x, int* y); void printVector(string label, vec3 v); void print4DVector(string label, vec4 v); float NEAR_CLIP = 0.1f; float FAR_CLIP = 100.0f; void glfw_error_callback(int error, const char* description) { gl_log_err("GLFW ERROR: code %i msg: %s\n", error, description); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { double mouse_x, mouse_y; glfwGetCursorPos(window, &mouse_x, &mouse_y); if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { cout << "Mouse clicked (" << mouse_x << "," << mouse_y << ")" << endl; selectedObject = NULL; float x = (2.0f*mouse_x) / width - 1.0f; float y = 1.0f - (2.0f*mouse_y) / height; cout << "x: " << x << ", y: " << y << endl; vec4 ray_clip = vec4(x, y, -1.0f, 1.0f); vec4 ray_eye = inverse(proj_mat) * ray_clip; ray_eye = vec4(ray_eye.xy(), -1.0f, 1.0f); vec4 ray_world = inverse(view_mat) * ray_eye; vec4 cam_pos_temp = vec4(cam_pos, 1.0f); vec4 click_point; 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 int closest_face_id = -1; for (int i = 0; i= click_point.z && click_point.z > -FAR_CLIP && click_point.z > closest_point.z) { closest_point = click_point.xyz(); closest_face_id = i; } } } if (closest_face_id == -1) { cout << "No object was clicked" << endl; } else { clickedObject = &objects[faces[closest_face_id].object_id]; cout << "Clicked object: " << faces[closest_face_id].object_id << endl; } } } int main(int argc, char* argv[]) { cout << "New OpenGL Game" << endl; if (!restart_gl_log()) {} gl_log("starting GLFW\n%s\n", glfwGetVersionString()); glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) { fprintf(stderr, "ERROR: could not start GLFW3\n"); return 1; } #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow* window = NULL; GLFWmonitor* mon = NULL; if (FULLSCREEN) { mon = glfwGetPrimaryMonitor(); const GLFWvidmode* vmode = glfwGetVideoMode(mon); width = vmode->width; height = vmode->height; cout << "Fullscreen resolution " << vmode->width << "x" << vmode->height << endl; } window = glfwCreateWindow(width, height, "New OpenGL Game", mon, NULL); if (!window) { fprintf(stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwSetMouseButtonCallback(window, mouse_button_callback); glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; glewInit(); const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); // glCullFace(GL_BACK); // glFrontFace(GL_CW); int x, y; unsigned char* texImage = loadImage("test.png", &x, &y); if (texImage) { cout << "Yay, I loaded an image!" << endl; cout << x << endl; cout << y << endl; printf("first 4 bytes are: %i %i %i %i\n", texImage[0], texImage[1], texImage[2], texImage[3]); } GLuint tex = 0; glGenTextures(1, &tex); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); GLfloat points[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, }; GLfloat colors[] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, }; GLfloat colors_new[] = { 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, }; GLfloat points2[] = { 0.5f, 0.5f, 0.0f, -0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, }; GLfloat colors2[] = { 0.0, 0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.9, 0.9, 0.0, 0.9, 0.9, }; GLfloat texcoords[] = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0 }; mat4 T_model, R_model; // triangle objects.push_back(SceneObject()); objects[0].shader_program = 0; objects[0].vbo_offset = (GLvoid*) (0 * sizeof(float) * 3); objects[0].num_points = 6; T_model = translate(mat4(), vec3(0.45f, 0.0f, 0.0f)); R_model = rotate(mat4(), 0.0f, vec3(0.0f, 1.0f, 0.0f)); objects[0].model_mat = T_model*R_model; faces.push_back(ObjectFace()); faces[0].object_id = 0; faces[0].points = { vec3(points[0], points[1], points[2]), vec3(points[3], points[4], points[5]), vec3(points[6], points[7], points[8]), }; // square objects.push_back(SceneObject()); objects[1].shader_program = 0; objects[1].vbo_offset = (GLvoid*) (6 * sizeof(float) * 3); objects[1].num_points = 6; T_model = translate(mat4(), vec3(-0.5f, 0.0f, -1.00f)); R_model = rotate(mat4(), 0.5f, vec3(0.0f, 1.0f, 0.0f)); objects[1].model_mat = T_model*R_model; faces.push_back(ObjectFace()); faces[1].object_id = 1; faces[1].points = { vec3(points2[0], points2[1], points2[2]), vec3(points2[3], points2[4], points2[5]), vec3(points2[6], points2[7], points2[8]), }; faces.push_back(ObjectFace()); faces[2].object_id = 1; faces[2].points = { vec3(points2[9], points2[10], points2[11]), vec3(points2[12], points2[13], points2[14]), vec3(points2[15], points2[16], points2[17]), }; GLuint points_vbo = 0; glGenBuffers(1, &points_vbo); glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(points2), NULL, GL_DYNAMIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(points), points); glBufferSubData(GL_ARRAY_BUFFER, sizeof(points), sizeof(points2), points2); GLuint colors_vbo = 0; glGenBuffers(1, &colors_vbo); glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW); GLuint vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); GLuint colors2_vbo = 0; glGenBuffers(1, &colors2_vbo); glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(colors2), colors2, GL_STATIC_DRAW); GLuint vt_vbo; glGenBuffers(1, &vt_vbo); glBindBuffer(GL_ARRAY_BUFFER, vt_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW); GLuint vao2 = 0; glGenVertexArrays(1, &vao2); glBindVertexArray(vao2); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); // I can create a vbo to store all points for all models, // and another vbo to store all colors for all models, but how do I allow alternating between // using colors and textures for each model? // Do I create a third vbo for texture coordinates and change which vertex attribute array I have bound // when I want to draw a textured model? // Or do I create one vao with vertices and colors and another with vertices and textures and switch between the two? // Since I would have to switch shader programs to toggle between using colors or textures, // I think I should use one vao for both cases and have a points vbo, a colors vbo, and a textures vbo // One program will use the points and colors, and the other will use the points and texture coords // Review how to bind vbos to vertex attributes in the shader. // // Binding vbos is done using glVertexAttribPointer(...) on a per-vao basis and is not tied to any specific shader. // This means, I could create two vaos, one for each shader and have one use points+colors, while the other // uses points+texxcoords. // // At some point, when I have lots of objects, I want to group them by shader when drawing them. // I'd probably create some sort of set per shader and have each set contain the ids of all objects currently using that shader // Most likely, I'd want to implement each set using a bit field. Makes it constant time for updates and iterating through them // should not be much of an issue either. // Assuming making lots of draw calls instead of one is not innefficient, I should be fine. // I might also want to use one glDrawElements call per shader to draw multiple non-memory-adjacent models // // DECISION: Use a glDrawElements call per shader since I use a regular array to specify the elements to draw // Actually, this will only work once I get UBOs working since each object will have a different model matrix // For now, I could implement this with a glDrawElements call per object and update the model uniform for each object GLuint shader_program = loadShaderProgram("./color.vert", "./color.frag"); GLuint shader_program2 = loadShaderProgram("./texture.vert", "./texture.frag"); float speed = 1.0f; float last_position = 0.0f; float cam_speed = 1.0f; float cam_yaw_speed = 60.0f*ONE_DEG_IN_RAD; // glm::lookAt can create the view matrix // glm::perspective can create the projection matrix cam_pos = vec3(0.0f, 0.0f, 2.0f); float cam_yaw = 0.0f * 2.0f * 3.14159f / 360.0f; mat4 T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z)); mat4 R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f)); view_mat = R*T; float fov = 67.0f * ONE_DEG_IN_RAD; float aspect = (float)width / (float)height; float range = tan(fov * 0.5f) * NEAR_CLIP; float Sx = NEAR_CLIP / (range * aspect); float Sy = NEAR_CLIP / range; float Sz = -(FAR_CLIP + NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP); float Pz = -(2.0f * FAR_CLIP * NEAR_CLIP) / (FAR_CLIP - NEAR_CLIP); float proj_arr[] = { Sx, 0.0f, 0.0f, 0.0f, 0.0f, Sy, 0.0f, 0.0f, 0.0f, 0.0f, Sz, -1.0f, 0.0f, 0.0f, Pz, 0.0f, }; proj_mat = make_mat4(proj_arr); GLint model_test_loc = glGetUniformLocation(shader_program, "model"); GLint view_test_loc = glGetUniformLocation(shader_program, "view"); GLint proj_test_loc = glGetUniformLocation(shader_program, "proj"); GLint model_mat_loc = glGetUniformLocation(shader_program2, "model"); GLint view_mat_loc = glGetUniformLocation(shader_program2, "view"); GLint proj_mat_loc = glGetUniformLocation(shader_program2, "proj"); glUseProgram(shader_program); glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[0].model_mat)); glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat)); glUniformMatrix4fv(proj_test_loc, 1, GL_FALSE, value_ptr(proj_mat)); glUseProgram(shader_program2); glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[1].model_mat)); glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat)); glUniformMatrix4fv(proj_mat_loc, 1, GL_FALSE, value_ptr(proj_mat)); objects[0].shader_program = shader_program; objects[1].shader_program = shader_program2; vector program1_objects, program2_objects; vector::iterator it; bool cam_moved = false; int frame_count = 0; double elapsed_seconds_fps = 0.0f; double previous_seconds = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double current_seconds = glfwGetTime(); double elapsed_seconds = current_seconds - previous_seconds; previous_seconds = current_seconds; elapsed_seconds_fps += elapsed_seconds; if (elapsed_seconds_fps > 0.25f) { fps = (double)frame_count / elapsed_seconds_fps; cout << "FPS: " << fps << endl; frame_count = 0; elapsed_seconds_fps = 0.0f; } frame_count++; if (fabs(last_position) > 1.0f) { speed = -speed; } program1_objects.clear(); program2_objects.clear(); // Handle events (Ideally, move all event-handling code // before the render code) clickedObject = NULL; glfwPollEvents(); if (clickedObject == &objects[0]) { selectedObject = &objects[0]; } if (clickedObject == &objects[1]) { selectedObject = &objects[1]; } if (selectedObject == &objects[1] && objects[1].shader_program == shader_program2) { objects[1].shader_program = shader_program; } else if (selectedObject != &objects[1] && objects[1].shader_program == shader_program) { objects[1].shader_program = shader_program2; } // group scene objects by shader for (int i=0; i < objects.size(); i++) { if (objects[i].shader_program == shader_program) { program1_objects.push_back(i); } else if (objects[i].shader_program == shader_program2) { program2_objects.push_back(i); } } /* model[12] = last_position + speed*elapsed_seconds; last_position = model[12]; */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shader_program); glBindVertexArray(vao); for (it=program1_objects.begin(); it != program1_objects.end(); it++) { glUniformMatrix4fv(model_test_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat)); glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vbo_offset); if (selectedObject == &objects[*it]) { if (*it == 1) { glBindBuffer(GL_ARRAY_BUFFER, colors2_vbo); } else { glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors_new, GL_STATIC_DRAW); } } else { glBindBuffer(GL_ARRAY_BUFFER, colors_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW); } glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL); glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points); } glUseProgram(shader_program2); glBindVertexArray(vao2); for (it = program2_objects.begin(); it != program2_objects.end(); it++) { glUniformMatrix4fv(model_mat_loc, 1, GL_FALSE, value_ptr(objects[*it].model_mat)); glBindBuffer(GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, objects[*it].vbo_offset); glBindBuffer(GL_ARRAY_BUFFER, vt_vbo); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL); glDrawArrays(GL_TRIANGLES, 0, objects[*it].num_points); } glfwSwapBuffers(window); if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window, 1); } float dist = cam_speed * elapsed_seconds; if (glfwGetKey(window, GLFW_KEY_A)) { cam_pos.x -= cos(cam_yaw)*dist; cam_pos.z += sin(cam_yaw)*dist; cam_moved = true; } if (glfwGetKey(window, GLFW_KEY_D)) { cam_pos.x += cos(cam_yaw)*dist; cam_pos.z -= sin(cam_yaw)*dist; cam_moved = true; } if (glfwGetKey(window, GLFW_KEY_W)) { cam_pos.x -= sin(cam_yaw)*dist; cam_pos.z -= cos(cam_yaw)*dist; cam_moved = true; } if (glfwGetKey(window, GLFW_KEY_S)) { cam_pos.x += sin(cam_yaw)*dist; cam_pos.z += cos(cam_yaw)*dist; cam_moved = true; } if (glfwGetKey(window, GLFW_KEY_LEFT)) { cam_yaw += cam_yaw_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey(window, GLFW_KEY_RIGHT)) { cam_yaw -= cam_yaw_speed * elapsed_seconds; cam_moved = true; } if (cam_moved) { T = translate(mat4(), vec3(-cam_pos.x, -cam_pos.y, -cam_pos.z)); R = rotate(mat4(), -cam_yaw, vec3(0.0f, 1.0f, 0.0f)); view_mat = R*T; glUseProgram(shader_program); glUniformMatrix4fv(view_test_loc, 1, GL_FALSE, value_ptr(view_mat)); glUseProgram(shader_program2); glUniformMatrix4fv(view_mat_loc, 1, GL_FALSE, value_ptr(view_mat)); cam_moved = false; } } glfwTerminate(); return 0; } GLuint loadShader(GLenum type, string file) { cout << "Loading shader from file " << file << endl; ifstream shaderFile(file); GLuint shaderId = 0; if (shaderFile.is_open()) { string line, shaderString; while(getline(shaderFile, line)) { shaderString += line + "\n"; } shaderFile.close(); const char* shaderCString = shaderString.c_str(); shaderId = glCreateShader(type); glShaderSource(shaderId, 1, &shaderCString, NULL); glCompileShader(shaderId); cout << "Loaded successfully" << endl; } else { cout << "Failed to load the file" << endl; } return shaderId; } GLuint loadShaderProgram(string vertexShaderPath, string fragmentShaderPath) { GLuint vs = loadShader(GL_VERTEX_SHADER, vertexShaderPath); GLuint fs = loadShader(GL_FRAGMENT_SHADER, fragmentShaderPath); GLuint shader_program = glCreateProgram(); glAttachShader(shader_program, vs); glAttachShader(shader_program, fs); glLinkProgram(shader_program); return shader_program; } unsigned char* loadImage(string file_name, int* x, int* y) { int n; int force_channels = 4; // This forces RGBA (4 bytes per pixel) unsigned char* image_data = stbi_load(file_name.c_str(), x, y, &n, force_channels); int width_in_bytes = *x * 4; unsigned char *top = NULL; unsigned char *bottom = NULL; unsigned char temp = 0; int half_height = *y / 2; // flip image upside-down to account for OpenGL treating lower-left as (0, 0) for (int row = 0; row < half_height; row++) { top = image_data + row * width_in_bytes; bottom = image_data + (*y - row - 1) * width_in_bytes; for (int col = 0; col < width_in_bytes; col++) { temp = *top; *top = *bottom; *bottom = temp; top++; bottom++; } } if (!image_data) { fprintf(stderr, "ERROR: could not load %s\n", file_name.c_str()); } // Not Power-of-2 check if ((*x & (*x - 1)) != 0 || (*y & (*y - 1)) != 0) { fprintf(stderr, "WARNING: texture %s is not power-of-2 dimensions\n", file_name.c_str()); } return image_data; } bool faceClicked(ObjectFace* face, vec4 world_ray, vec4 cam, vec4& click_point) { // LINE EQUATION: P = O + Dt // O = cam // D = ray_world // PLANE EQUATION: P dot n + d = 0 // n is the normal vector // d is the offset from the origin // Take the cross-product of two vectors on the plane to get the normal vec3 v1 = face->points[1] - face->points[0]; vec3 v2 = face->points[2] - face->points[0]; 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); print4DVector("Full world ray", world_ray); SceneObject* obj = &objects[face->object_id]; vec3 local_ray = (inverse(obj->model_mat) * world_ray).xyz(); vec3 local_cam = (inverse(obj->model_mat) * cam).xyz(); local_ray = local_ray - local_cam; float d = -glm::dot(face->points[0], normal); cout << "d: " << d << endl; float t = -(glm::dot(local_cam, normal) + d) / glm::dot(local_ray, normal); cout << "t: " << t << endl; vec3 intersection = local_cam + t*local_ray; printVector("Intersection", intersection); if (insideTriangle(intersection, face->points)) { click_point = obj->model_mat * vec4(intersection, 1.0f); return true; } else { return false; } } bool insideTriangle(vec3 p, array triangle_points) { vec3 v21 = triangle_points[1]- triangle_points[0]; vec3 v31 = triangle_points[2]- triangle_points[0]; vec3 pv1 = p- triangle_points[0]; float y = (pv1.y*v21.x - pv1.x*v21.y) / (v31.y*v21.x - v31.x*v21.y); float x = (pv1.x-y*v31.x) / v21.x; cout << "(" << x << ", " << y << ")" << endl; return x > 0.0f && y > 0.0f && x+y < 1.0f; } void printVector(string label, vec3 v) { cout << label << " -> (" << v.x << "," << v.y << "," << v.z << ")" << endl; } void print4DVector(string label, vec4 v) { cout << label << " -> (" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" << endl; }