/* Init GLFW and window*/ void init_stage() { // GLFW init glfwSetErrorCallback(GLFW_error_callback); if (!glfwInit()) Helper::log_error("Failed to init GLFW\n"); /* Now, let's give GLFW hints about the window we need */ /* We want OpenGL version at least 3.3 */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); /* We will also request a bleeding-edge core profile*/ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif /* IMPORTANT: Tell GLFW to give us a framebuffer which can do sRGB */ glfwWindowHint(GLFW_SRGB_CAPABLE, TRUE); // Create GLFW window window = glfwCreateWindow(SCREENWIDTH, SCREENHEIGHT, "Color management demo", NULL, NULL); if (window == nullptr) { glfwTerminate(); Helper::log_error("Failed to create GLFW windonw\n"); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, GLFW_key_callback); /*Setup key call back function*/ // gl3w init, load opengl if (gl3wInit()) Helper::log_error("failed to initialize OpenGL\n"); if (!gl3wIsSupported(4, 3)) Helper::log_error("OpenGL 4.3 not supported\n"); }
bool application::initialize_opengl() { /* Create contexts */ _render_context = SDL_GL_CreateContext(_window); SDL_GL_MakeCurrent(_window, _render_context); /* Load Extensions */ gl3wInit(); if (!gl3wIsSupported(OPENGL_MAJOR_VERSION, OPENGL_MINOR_VERSION)) { std::cout << "ERROR: OpenGL " << OPENGL_MAJOR_VERSION << "." << OPENGL_MINOR_VERSION << " core not supported!" << std::endl; return false; } /* Basic OpenGL initialization */ glEnable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glEnable(GL_CULL_FACE); // TODO(Corralx): Missing initialization glClearColor(1.f, .0f, .0f, 1.f); #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback((GLDEBUGPROC)gl_debug_callback, nullptr); #endif if (glGetError() != GL_NO_ERROR) { std::cout << "ERROR: Failed to initialize OpenGL!" << std::endl; return false; } return true; }
int main() { GLFWwindow* window; if (!glfwInit()) { printf("Error initializing GLFW\n"); return -1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSION_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, GL_VERSION_MINOR); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 8); window = glfwCreateWindow(1920, 1080, "Test Window", glfwGetPrimaryMonitor(), NULL); if (!window) { printf("Error creating GLFW window\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_position_callback); glfwSetScrollCallback(window, scroll_callback); if (gl3wInit()) { printf("Error initializing OpenGL\n"); glfwTerminate(); return -1; } printf("OpenGL %s GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); if (!gl3wIsSupported(GL_VERSION_MAJOR, GL_VERSION_MINOR)) { printf("OpenGL %i.%i is not supported\n", GL_VERSION_MAJOR, GL_VERSION_MINOR); glfwTerminate(); return -1; } glViewport(0, 0, 1920, 1080); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); GLuint programID = loadShadersvf("shaders/simple.vsh", "shaders/simple.fsh"); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); //glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(sphere_model), sphere_model, GL_STATIC_DRAW); GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphere_indices), sphere_indices, GL_STATIC_DRAW); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_buffer_data), index_buffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); double timesteps[] = {1, 60, 60 * 60, 60 * 60 * 24, 60 * 60 * 24 * 7, 60 * 60 * 24 * 30, 60 * 60 * 24 * 365}; int timestepCounter = 0; World world; world.num_functions = 0; //Add the functions for gravitational attraction to the world's object list, and have it execute when updateWorld() is called addFunction(&world, attract, COMPONENT_POSITION | COMPONENT_VELOCITY); addFunction(&world, move, COMPONENT_POSITION | COMPONENT_VELOCITY); unsigned int bodies[11]; //Create all the planets with the correct masses, sizes, and velocities bodies[0] = createStar(&world, "Sun", 0, 0, 0, 0, 0, 0, 1.989 * pow(10, 30), 6.963 * pow(10,8), 1); bodies[1] = createPlanet(&world, "Mercury", -0.35790 * AU, -0.04240 * AU, -0.11618 * AU, -0.00000004 * AU, 0.00000003 * AU, 0.00000031 * AU, 3.285 * pow(10,23), 2.44 * pow(10,6), 0.4549, 0.4509, 0.4705); bodies[2] = createPlanet(&world, "Venus", -0.46075 * AU, -0.03422 * AU, -0.56289 * AU, -0.00000017 * AU, -0.00000001 * AU, 0.00000014 * AU, 4.867 * pow(10, 24), 6.052 * pow(10,6), 0.4627, 0.568, 0.380); bodies[3] = createPlanet(&world, "Earth", 0.99542 * AU, 0, 0.01938 * AU, 0.00000001 * AU, 0, -0.00000019 * AU, 5.972 * pow(10, 24), 6.371 * pow(10,6), 0, 0.4, 0.6); bodies[4] = createPlanet(&world, "Moon", 0.99708 * AU, -0.00016 * AU, 0.02141 * AU, 0.00000001 * AU + 722.66, 0, -0.00000019 * AU - 722.66, 7.348 * pow(10, 22), 1.737 * pow(10,6), 0.4, 0.4, 0.4); bodies[5] = createPlanet(&world, "Mars", 1.38763 * AU, 0.01755 * AU, -0.79510 * AU, -0.00000009 * AU, -0.00000001 * AU, -0.00000013 * AU, 6.39 * pow(10, 23), 3.39 * pow(10,6), 0.8157, 0.5294, 0.3922); bodies[6] = createPlanet(&world, "Jupiter", 5.32462 * AU, 0.11488 * AU, 1.04223 * AU, 0.00000002 * AU, 0, -0.00000008 * AU, 1.898 * pow(10,27), 69.911 * pow(10,6), 0.8824, 0.7961, 0.7412); bodies[7] = createPlanet(&world, "Saturn", 3.30063 * AU, 0.29595 * AU, -9.47771 * AU, -0.00000006 * AU, 0, -0.00000002 * AU, 5.683 * pow(10,26), 58.232 * pow(10,6), 0.7843, 0.6392, 0.4314); bodies[8] = createPlanet(&world, "Uranus", -18.76415 * AU, -0.21783 * AU, 6.83528 * AU, 0.00000002 * AU, 0, 0.00000004 * AU, 8.681 * pow(10,25), 25.362 * pow(10,6), 0.8314, 0.9804, 0.9922); bodies[9] = createPlanet(&world, "Neptune", -28.07048 * AU, -0.42924 * AU, -10.42730 * AU, -0.00000002 * AU, 0, 0.0000003 * AU, 1.024 * pow(10,26), 24.622 * pow(10,6), 0.2, 0.2902, 0.7451); bodies[10] = createPlanet(&world, "Pluto", -8.88081 * AU, 0.86973 * AU, -31.76914 * AU, -0.00000003 * AU, -0.00000001 * AU, 0.0000001 / 41.0 * AU, 1.309 * pow(10,22), 1.186 * pow(10, 6), 0.7137, 0.6824, 0.6314); double mat4d_projection[4][4] = MATRIX_IDENTITY_4; mat4dProjection(M_PI / 2.0, 16.0/9.0, pow(10,6), pow(10,13), mat4d_projection); unsigned int parent = 3; Camera camera; makeCamera(&camera, 0, 0, pow(10, 9), &world, bodies[parent]); double mat4d_camera[4][4] = MATRIX_IDENTITY_4; float mat4_camera[4][4]; double sensitivity = 0.005; printf("Starting main loop\n"); while (!glfwWindowShouldClose(window)) { clearInput(); glfwPollEvents(); //rotate or zoom out the camera depending on camera movement and scrolling double dx, dy, dz; getMouseDelta(&dx, &dy, &dz); updateCamera(&camera, dx * sensitivity, dy * sensitivity, dz); if (getClicked()) { if(++parent > 10) parent = 0; changeCameraParent(&camera, pow(10, 9), &world, bodies[parent]); } timestepCounter += getTimeStepChange(); if (timestepCounter > 6) timestepCounter = 0; else if (timestepCounter < 0) timestepCounter = 6; setTimeStep(timesteps[timestepCounter]); //get the time since the last frame to do proper delta-timing for the gravitational attraction and movement double delta = timeTick(); updateWorld(&world, delta); getCameraMatrix(&camera, mat4d_camera); double modelView[4][4]; mat4dMlt(mat4d_projection, mat4d_camera, modelView); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); glBindVertexArray(vao); glEnableVertexAttribArray(0); //For each of the objects in the world, loop through them and render them if they have a position and radius, //rendering works by rendering the same sphere over and over, with a different translation and scale //because all objects in this program are spheres for (int i = 0; i < WORLD_MAX_ENTITIES; ++i) { if (isEntity(&world, i, COMPONENT_POSITION | COMPONENT_RADIUS)) { /*double pos[4] = {world.position[i].position[0], world.position[i].position[1], world.position[i].position[2], 1}; vec4dMltMat(mat4d_camera, pos, pos); double distance = vec3dLength(pos); printf("%i: %f\n", i, distance); double mat4d_model[4][4] = MATRIX_IDENTITY_4; double radius = world.radius[i].radius; double scaleFactor = distance * (1 / pow(radius,2)); printf("Scale factor: %f\n", scaleFactor); if (scaleFactor > pow(10,-3)) { printf("Has been scaled\n"); radius = radius / scaleFactor; } printf("Radius: %f\n", radius);*/ double mat4d_model[4][4] = MATRIX_IDENTITY_4; double radius = world.radius[i].radius; double scale[3] = {radius, radius, radius}; mat4dGenScale(scale, mat4d_model); mat4dTranslate(world.position[i].position, mat4d_model); double modelViewProjection[4][4]; mat4dMlt(modelView, mat4d_model, modelViewProjection); float modelViewProjectionf[4][4]; doubleToSingle(modelViewProjection[0], modelViewProjectionf[0], 16); double color[3] = {1,1,1}; if (isEntity(&world, i, COMPONENT_COLOR)) { vec3dSetEqual(world.color[i].color, color); } float colorf[3]; doubleToSingle(color, colorf, 3); GLint colorLoc = glGetUniformLocation(programID, "in_color"); glUniform3fv(colorLoc, 1, colorf); GLint mvpLoc = glGetUniformLocation(programID, "mvp"); glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, modelViewProjectionf[0]); glDrawElements(GL_TRIANGLES, sphere_num_indices, GL_UNSIGNED_INT, 0); } } glDisableVertexAttribArray(0); glBindVertexArray(0); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
void Window_Create(char *Title, int Width, int Height, int MoniterNum, struct Window **Window) { log_info("Creating Window"); if (*Window == NULL) (*Window) = malloc(sizeof(struct Window)); check_mem((*Window)); (*Window)->WINDOW_TITLE = Title; (*Window)->WINDOW_WIDTH = Width; (*Window)->WINDOW_HEIGHT = Height; Game_Width = Width; Game_Height = Height; /* Initialize GLFW for video output */ if (!glfwInit()) { log_info("Unable to initialize GLFW"); Application_Error(); } int count; GLFWmonitor** monitors = glfwGetMonitors(&count); int xpos, ypos; glfwGetMonitorPos(monitors[MoniterNum], &xpos, &ypos); const GLFWvidmode* mode = glfwGetVideoMode(monitors[0]); 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); /* Create a 640x480 OpenGL screen */ (*Window)->Window = glfwCreateWindow((*Window)->WINDOW_WIDTH, (*Window)->WINDOW_HEIGHT, (*Window)->WINDOW_TITLE, NULL, NULL); glfwSetWindowPos((*Window)->Window, xpos + mode->width / 2 - mode->width / 4 + mode->width / 8, ypos + mode->height / 2 - mode->height / 4); if (!(*Window)->Window) { log_err("Unable to create OpenGL window"); Application_Error(); } glfwMakeContextCurrent((*Window)->Window); if (gl3wInit()) { log_err("failed to initialize OpenGL"); Application_Error(); } if (!gl3wIsSupported(3, 3)) { log_err("OpenGL 3.3 not supported"); Application_Error(); } glGenVertexArrays(1, &(*Window)->DefaultVAO); glBindVertexArray((*Window)->DefaultVAO); (*Window)->Running = true; printOpenGLError(); log_info("Window has been created"); return; error: Window_Free(Window); Application_Error(); return; }
int main(int argc, char** argv) { int running = GL_TRUE; if(!glfwInit()) { std::cerr << "Failed to initialize GLFW." << std::endl; exit(EXIT_FAILURE); } static const int width = 640; static const int height = 480; static const int red_bits = 8; static const int green_bits = 8; static const int blue_bits = 8; static const int alpha_bits = 8; static const int depth_bits = 24; static const int stencil_bits = 8; static const int mode = GLFW_WINDOW; glfwOpenWindowHint(GLFW_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_VERSION_MINOR, 3); if (!glfwOpenWindow(width, height, red_bits, green_bits, blue_bits, alpha_bits, depth_bits, stencil_bits, mode)) { std::cerr << "Failed to open window." << std::endl; exit(EXIT_FAILURE); } if (gl3wInit()) { std::cerr << "Failed on gl3w init" << std::endl; exit(EXIT_FAILURE); } if (!gl3wIsSupported(3, 3)) { std::cerr << "OpenGL 3.3 not supported." << std::endl; exit(EXIT_FAILURE); } glViewport(0, 0, (GLsizei)width, (GLsizei)height); init(); CHECK_GL_ERROR; static const double fps = 1./60.; static const double ups = 1./60.; double last_update = 0.; double last_render = 0.; while (running) { if (glfwGetTime() - last_render > fps) { glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT); display(); glfwSwapBuffers(); last_render = glfwGetTime(); } if (glfwGetTime() - last_update > ups) { //do updating stuff, I guess last_update = glfwGetTime(); } running = !glfwGetKey('q') && glfwGetWindowParam(GLFW_OPENED); glfwSleep(std::min(fps - (glfwGetTime() - last_render), ups - (glfwGetTime() - last_update))); CHECK_GL_ERROR; } }
int engine_init(void) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_AUDIO)) { DBG_LOG("Failed to initialize SDL: %s", SDL_GetError()); return -1; } SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN); fullscreen = false; /* require OpenGL 3.2 */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); main_win = SDL_CreateWindow(RPG_WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, RPG_OUT_WIDTH, RPG_OUT_HEIGHT, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL); if (!main_win) { DBG_LOG("Failed to create window: %s", SDL_GetError()); goto failure; } main_ctx = SDL_GL_CreateContext(main_win); if (!main_ctx) { DBG_LOG("Failed to initialize GL context: %s", SDL_GetError()); goto failure; } SDL_GL_MakeCurrent(main_win, main_ctx); /* now that context is created we can initialize GL */ int res = gl3wInit(); if (res != GL3W_OK) { DBG_LOG("Error opening GL library (%d)", res); goto failure; } if (!gl3wIsSupported(3, 2)) { DBG_LOG("Error OpenGL 3.2 or later required"); goto failure; } /* register published key events */ engine_key_state.left = keystate_register("left"); engine_key_state.right = keystate_register("right"); engine_key_state.up = keystate_register("up"); engine_key_state.down = keystate_register("down"); engine_key_state.button_a = keystate_register("a"); engine_key_state.button_b = keystate_register("b"); engine_key_state.button_x = keystate_register("x"); engine_key_state.button_y = keystate_register("y"); engine_key_state.start = keystate_register("start"); engine_key_state.select = keystate_register("select"); return 0; failure: engine_fini(); return -1; }
float getVer() { float ver = 0.0f; #ifdef GLEW glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); if (GLEW_VERSION_1_1) { ver = 1.1f; } if (GLEW_VERSION_1_2) { ver = 1.2f; } if (GLEW_VERSION_1_3) { ver = 1.3f; } if (GLEW_VERSION_1_4) { ver = 1.4f; } if (GLEW_VERSION_1_5) { ver = 1.5f; } if (GLEW_VERSION_2_0) { ver = 2.0f; } if (GLEW_VERSION_2_1) { ver = 2.1f; } if (GLEW_VERSION_3_0) { ver = 3.0f; } if (GLEW_VERSION_3_1) { ver = 3.1f; } if (GLEW_VERSION_3_2) { ver = 3.2f; } if (GLEW_VERSION_3_3) { ver = 3.3f; } if (GLEW_VERSION_4_0) { ver = 4.0f; } if (GLEW_VERSION_4_1) { ver = 4.1f; } if (GLEW_VERSION_4_2) { ver = 4.2f; } if (GLEW_VERSION_4_3) { ver = 4.3f; } if (GLEW_VERSION_4_4) { ver = 4.4f; } if (GLEW_VERSION_4_5) { ver = 4.5f; } #endif #ifdef GL3W if (gl3wInit()) { fprintf(stderr, "failed to initialize OpenGL\n"); } if (gl3wIsSupported(1, 1)) { ver = 1.1f; } if (gl3wIsSupported(1, 2)) { ver = 1.2f; } if (gl3wIsSupported(1, 3)) { ver = 1.3f; } if (gl3wIsSupported(1, 4)) { ver = 1.4f; } if (gl3wIsSupported(1, 5)) { ver = 1.5f; } if (gl3wIsSupported(2, 0)) { ver = 2.0f; } if (gl3wIsSupported(2, 1)) { ver = 2.1f; } if (gl3wIsSupported(3, 0)) { ver = 3.0f; } if (gl3wIsSupported(3, 1)) { ver = 3.1f; } if (gl3wIsSupported(3, 2)) { ver = 3.2f; } if (gl3wIsSupported(3, 3)) { ver = 3.3f; } if (gl3wIsSupported(4, 0)) { ver = 4.0f; } if (gl3wIsSupported(4, 1)) { ver = 4.1f; } if (gl3wIsSupported(4, 2)) { ver = 4.2f; } if (gl3wIsSupported(4, 3)) { ver = 4.3f; } if (gl3wIsSupported(4, 4)) { ver = 4.4f; } if (gl3wIsSupported(4, 5)) { ver = 4.5f; } #endif return ver; }
/** * Main */ int main(int argc, char** argv) { // Print the keyboard commands printf("i - Reset to initial view\n"); printf("R - Roll 5 degrees clockwise r - Counter-clockwise\n"); printf("P - Pitch 5 degrees clockwise p - Counter-clockwise\n"); printf("H - Heading 5 degrees clockwise h - Counter-clockwise\n"); printf("X - Slide camera right x - Slide camera left\n"); printf("Y - Slide camera up y - Slide camera down\n"); printf("F - Move camera forward f - Move camera backwards\n"); printf("V - Faster mouse movement v - Slower mouse movement\n"); // Initialize free GLUT glutInit(&argc, argv); glutInitContextVersion(3, 2); //glutInitContextFlags(GLUT_FORWARD_COMPATIBLE); // Using this causes LineWidth to error glutInitContextProfile(GLUT_CORE_PROFILE); // Set up depth buffer and double buffering glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); glutInitWindowPosition(100, 100); glutInitWindowSize(640, 480); // Set callback methods glutCreateWindow("Phong Shading"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(mouseMotion); glutKeyboardFunc(keyboard); // Initialize Open 3.2 core profile if (gl3wInit()) { fprintf(stderr, "gl3wInit: failed to initialize OpenGL\n"); return -1; } if (!gl3wIsSupported(3, 2)) { fprintf(stderr, "OpenGL 3.2 not supported\n"); return -1; } printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); // Set the clear color to black glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Enable the depth buffer glEnable(GL_DEPTH_TEST); // Enable back face polygon removal glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); // Enable mutlisample anti-aliasing glEnable(GL_MULTISAMPLE); // Construct scene ConstructScene(); glutMainLoop(); return 0; }
int main() { hmk::Logger::get_instance().initialize("engine.txt"); if (glfwInit() == GL_FALSE) { HMK_LOG_ERROR("failed glfwInit") hmk::Logger::get_instance().shutdown(); return -1; } glfwSetErrorCallback(ErrorCallback); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 8); GLFWwindow* window = glfwCreateWindow(800, 600, "HMK", nullptr, nullptr); if (window == nullptr) { HMK_LOG_ERROR("failed glfwCreateWindow") hmk::Logger::get_instance().shutdown(); glfwTerminate(); return -1; } glfwSetWindowPos(window, 500, 30); glfwMakeContextCurrent(window); if (gl3wInit() == -1) // 0 success { HMK_LOG_ERROR("failed gl3wInit") hmk::Logger::get_instance().shutdown(); glfwTerminate(); return -1; } if (!gl3wIsSupported(3, 3)) { HMK_LOG_ERROR("Upgrade your graphic card!") hmk::Logger::get_instance().shutdown(); glfwTerminate(); return -1; } #if _DEBUG if (glDebugMessageCallback) { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(glErrorCallback, nullptr); GLuint unused = 0; glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unused, true); } #endif ImGui_ImplGlfwGL3_Init(window, false); Game *game = new Game(); game->initialize(); glfwSetKeyCallback(window, KeyCallback); glfwSetCursorPosCallback(window, CursorPosCallback); glfwSetMouseButtonCallback(window, MouseButtonCallback); glfwSetDropCallback(window, DropCallback); keyCallback = HMK_CALLBACK_4(Game::key_input, game); cursorPosCallback = HMK_CALLBACK_2(Game::cursor_pos_input, game); mouseButtonCallback = HMK_CALLBACK_3(Game::mouse_button_input, game); dropCallback = HMK_CALLBACK_2(Game::drop_files_callback, game); double lastTime = glfwGetTime(); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); glEnable(GL_FRAMEBUFFER_SRGB); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // https://www.opengl.org/wiki/Cubemap_Texture#Seamless_cubemap glEnable(GL_MULTISAMPLE); glClearColor(0.2f, 0.3f, 0.2f, 1.0f); double fps = 0.0; double acc = 0.0; while (!glfwWindowShouldClose(window)) { glfwPollEvents(); ImGui_ImplGlfwGL3_NewFrame(); double now = glfwGetTime(); double delta = now - lastTime; lastTime = now; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); game->update((float)delta); game->render(); fps++; acc += delta; if (acc > 1.0) { acc = 0.0; fps = 0.0; } ImGui::Render(); glfwSwapBuffers(window); } delete game; hmk::Logger::get_instance().shutdown(); glfwDestroyWindow(window); ImGui_ImplGlfwGL3_Shutdown(); glfwTerminate(); return 0; }
px::ViewOGL* px::ViewOGL::CreateView(void* _wnd) { ViewOGL * viewOGL = new ViewOGL; if(!_wnd) return NULL; HWND hwnd = (HWND)_wnd; HDC hdc = GetDC(hwnd); // Get the device context for our window viewOGL->hwnd = hwnd; viewOGL->hdc = hdc; PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(hdc, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return NULL; bool bResult = SetPixelFormat(hdc, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (!bResult) // If it fails return NULL; HGLRC glrc = wglCreateContext(hdc); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(hdc, glrc); // Make the OpenGL 2.1 context current and active viewOGL->hrc = (void *)glrc; // init opengl core profile PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if( wglSwapIntervalEXT && wglCreateContextAttribsARB && wglChoosePixelFormatARB) { const int attribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 32, WGL_STENCIL_BITS_ARB, 8, 0,//End }; int pixelFormat; UINT numFormats; wglChoosePixelFormatARB(hdc, attribList, NULL, 1, &pixelFormat, &numFormats); static const int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, OGL_MAJOR, WGL_CONTEXT_MINOR_VERSION_ARB, OGL_MINOR, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, 0 }; HGLRC core_rc = wglCreateContextAttribsARB(hdc, 0, attribs); wglMakeCurrent(hdc, core_rc); wglDeleteContext( glrc ); } if (gl3wInit()) { fprintf(stderr, "failed to initialize OpenGL\n"); } if (!gl3wIsSupported( OGL_MAJOR, OGL_MINOR )) { fprintf(stderr, "OpenGL %d.%d not supported\n", OGL_MAJOR, OGL_MINOR ); } printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); return viewOGL; }
// Creation / loading methods void GL3PlusTexture::createInternalResourcesImpl(void) { // Adjust format if required mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); // Check requested number of mipmaps size_t maxMips = GL3PlusPixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat); if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0)) mNumRequestedMipmaps = 0; mNumMipmaps = mNumRequestedMipmaps; if (mNumMipmaps > maxMips) mNumMipmaps = maxMips; // Generate texture name OGRE_CHECK_GL_ERROR(glGenTextures(1, &mTextureID)); GLenum texTarget = getGL3PlusTextureTarget(); // Set texture type OGRE_CHECK_GL_ERROR(glBindTexture(texTarget, mTextureID)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_BASE_LEVEL, 0)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_MAX_LEVEL, (mMipmapsHardwareGenerated && (mUsage & TU_AUTOMIPMAP)) ? maxMips : mNumMipmaps )); // Set some misc default parameters, these can of course be changed later OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); // Set up texture swizzling if(mGLSupport.checkExtension("GL_ARB_texture_swizzle") || gl3wIsSupported(3, 3)) { OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_GREEN)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_BLUE)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_ALPHA)); if(mFormat == PF_BYTE_LA) { OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_GREEN)); } else if(mFormat == PF_L8 || mFormat == PF_L16) { OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED)); OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_RED)); } } // If we can do automip generation and the user desires this, do so mMipmapsHardwareGenerated = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP); // Allocate internal buffer so that glTexSubImageXD can be used // Internal format GLenum format = GL3PlusPixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma); GLenum datatype = GL3PlusPixelUtil::getGLOriginDataType(mFormat); size_t width = mWidth; size_t height = mHeight; size_t depth = mDepth; if (PixelUtil::isCompressed(mFormat)) { // Compressed formats size_t size = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not // accept a 0 pointer like normal glTexImageXD // Run through this process for every mipmap to pregenerate mipmap pyramid uint8* tmpdata = new uint8[size]; memset(tmpdata, 0, size); for (size_t mip = 0; mip <= mNumMipmaps; mip++) { size = PixelUtil::getMemorySize(width, height, depth, mFormat); switch(mTextureType) { case TEX_TYPE_1D: OGRE_CHECK_GL_ERROR(glCompressedTexImage1D(GL_TEXTURE_1D, mip, format, width, 0, size, tmpdata)); break; case TEX_TYPE_2D: OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, size, tmpdata)); break; case TEX_TYPE_2D_RECT: OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_RECTANGLE, mip, format, width, height, 0, size, tmpdata)); break; case TEX_TYPE_2D_ARRAY: case TEX_TYPE_3D: OGRE_CHECK_GL_ERROR(glCompressedTexImage3D(texTarget, mip, format, width, height, depth, 0, size, tmpdata)); break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, size, tmpdata)); } break; default: break; }; // LogManager::getSingleton().logMessage("GL3PlusTexture::create - " + StringConverter::toString(mTextureID) + // " Mip: " + StringConverter::toString(mip) + // " Width: " + StringConverter::toString(width) + // " Height: " + StringConverter::toString(height) + // " Internal Format: " + StringConverter::toString(format) // ); if(width > 1) { width = width / 2; } if(height > 1) { height = height / 2; } if(depth > 1) { depth = depth / 2; } } delete [] tmpdata; } else { if((mGLSupport.checkExtension("GL_ARB_texture_storage") || gl3wIsSupported(4, 2)) && mTextureType == TEX_TYPE_2D) { OGRE_CHECK_GL_ERROR(glTexStorage2D(GL_TEXTURE_2D, GLint(mNumMipmaps+1), format, GLsizei(width), GLsizei(height))); } else { // Run through this process to pregenerate mipmap pyramid for(size_t mip = 0; mip <= mNumMipmaps; mip++) { // Normal formats switch(mTextureType) { case TEX_TYPE_1D: OGRE_CHECK_GL_ERROR(glTexImage1D(GL_TEXTURE_1D, mip, format, width, 0, GL_RGBA, datatype, 0)); break; case TEX_TYPE_2D: OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_2D, mip, format, width, height, 0, GL3PlusPixelUtil::getGLOriginFormat(mFormat), datatype, 0)); break; case TEX_TYPE_2D_RECT: OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_RECTANGLE, mip, format, width, height, 0, GL3PlusPixelUtil::getGLOriginFormat(mFormat), datatype, 0)); break; case TEX_TYPE_3D: case TEX_TYPE_2D_ARRAY: OGRE_CHECK_GL_ERROR(glTexImage3D(texTarget, mip, format, width, height, depth, 0, GL_RGBA, datatype, 0)); break; case TEX_TYPE_CUBE_MAP: for(int face = 0; face < 6; face++) { OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, width, height, 0, GL3PlusPixelUtil::getGLOriginFormat(mFormat), datatype, 0)); } break; default: break; }; if (width > 1) { width = width / 2; } if (height > 1) { height = height / 2; } if (depth > 1) { depth = depth / 2; } } } } _createSurfaceList(); // Get final internal format mFormat = getBuffer(0,0)->getFormat(); }
int Application::run(Application* self) { m_self = self; if (!framework::Utils::exists("data/gui")) { Logger::toLog("Error: could not find gui directory. Probably working directory has not been set correctly (especially if you are running from IDE).\n"); return EXIT_FAILURE; } init(); m_isRunning = true; glfwSetErrorCallback(&Application::errorCallback); if (!glfwInit()) { Logger::toLog("Error: glfwInit failed"); return EXIT_FAILURE; } glfwWindowHint(GLFW_VISIBLE, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 0); glfwWindowHint(GLFW_DEPTH_BITS, 32); glfwWindowHint(GLFW_STENCIL_BITS, 0); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, m_info.majorVersion); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, m_info.minorVersion); #ifdef _DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, m_info.samples); glfwWindowHint(GLFW_STEREO, m_info.flags.stereo ? GL_TRUE : GL_FALSE); // create window m_window = glfwCreateWindow(m_info.windowWidth, m_info.windowHeight, m_info.title.c_str(), m_info.flags.fullscreen ? glfwGetPrimaryMonitor() : NULL, NULL); if (!m_window) { glfwTerminate(); return EXIT_FAILURE; } glfwSetWindowSizeCallback(m_window, &Application::_setWindowSize); glfwSetKeyCallback(m_window, &Application::_onKey); glfwSetCharCallback(m_window, &Application::_onChar); glfwSetMouseButtonCallback(m_window, &Application::_onMouse); glfwSetCursorPosCallback(m_window, &Application::_onCursor); glfwSetScrollCallback(m_window, &Application::_onScroll); glfwSetInputMode(m_window, GLFW_CURSOR, m_info.flags.cursor ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_HIDDEN); // center position GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary); int posx = (mode->width - m_info.windowWidth) >> 1; int posy = (mode->height - m_info.windowHeight) >> 1; glfwSetWindowPos(m_window, posx, posy); // set vsync glfwMakeContextCurrent(m_window); glfwSwapInterval((int)m_info.flags.vsync); // init GL3w gl3wInit(); std::vector<int> multisamplingLevels; if (!checkOpenGLVersion() || !checkDeviceCapabilities(multisamplingLevels)) { glfwDestroyWindow(m_window); glfwTerminate(); return EXIT_FAILURE; } #ifdef _DEBUG Logger::toLogWithFormat("Video adapter: %s - %s, OpenGL: %s\n", (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER), (const char*)glGetString(GL_VERSION)); #endif if (m_info.flags.debug) { if (gl3wIsSupported(4, 3)) { glDebugMessageCallback(debugCallback, this); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } else if (IsExtensionSupported("GL_ARB_debug_output")) { glDebugMessageCallbackARB(debugCallback, this); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); } } initGui(); if (!StandardGpuPrograms::init()) { glfwDestroyWindow(m_window); glfwTerminate(); return EXIT_FAILURE; } initAxes(); startup(m_rootWindow); do { glfwMakeContextCurrent(m_window); Texture::beginFrame(); if (fabs(m_lastTime) < 1e-7) { render(0); Texture::endFrame(); renderGui(0); m_lastTime = glfwGetTime(); } else { double curTime = glfwGetTime(); double delta = curTime - m_lastTime; // fps counter measureFps(delta); // rendering render(delta); Texture::endFrame(); renderGui(delta); m_lastTime = curTime; } glfwSwapBuffers(m_window); glfwPollEvents(); if (glfwWindowShouldClose(m_window)) { m_isRunning = GL_FALSE; } m_isRunning &= (glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_RELEASE); } while(m_isRunning); shutdown(); destroyAllDestroyable(); destroyGui(); glfwDestroyWindow(m_window); glfwTerminate(); return EXIT_SUCCESS; }