GLFWwindow* initContext() { if (!glfwInit()) { return nullptr; } glfwSetErrorCallback(errorCallback); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); auto window = glfwCreateWindow(wWidth, wHeight, "Hello Triangle", nullptr, nullptr); glfwMakeContextCurrent(window); if (window) { if (gl3wInit()) { std::fprintf(stderr, "Failed to initialize gl3w.\n"); return nullptr; } if (!gl3wIsSupported(3, 2)) { std::fprintf(stderr, "Context doesn't support OpenGL 3.2\n"); return nullptr; } glfwSetFramebufferSizeCallback(window, reshape); } return window; }
int main(int argc, char **argv) { glutInit(&argc, argv); unsigned mode = GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE; #ifdef __APPLE__ mode |= GLUT_3_2_CORE_PROFILE; #endif glutInitDisplayMode(mode); glutInitWindowSize(width, height); glutCreateWindow("cookie"); glutReshapeFunc(reshape); glutDisplayFunc(display); if (gl3wInit()) { fprintf(stderr, "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)); glutMainLoop(); return 0; }
Init() { if(!glfwInit()) { std::cerr << "\nCould not initialize glfw!"; return; } glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, true); if(!glfwOpenWindow(screenSizeX, screenSizeY, 8, 8, 8, 8, 8, 8, GLFW_WINDOW)) { std::cerr << "\nCould not open the window!"; glfwTerminate(); return; } glfwSetWindowTitle("Colorful Game of Life"); glfwSetWindowPos(350, 150); glfwSwapInterval(0); glfwSetTime(0); if(gl3wInit() != 0) { std::cerr << "\nCould not initialize gl3w!"; glfwTerminate(); return; } }
void Demo_3::setupOpenGl(){ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); ctxt = SDL_GL_CreateContext(window); //vsync ON SDL_GL_SetSwapInterval(1); if (gl3wInit()) { std::cerr << "Failed to initialize gl3w." << std::endl; return; } if (!gl3wIsSupported(4, 2)) { std::cerr << "OpenGL 4.2 not supported" << std::endl; return; } std::cout << "OpenGL " << glGetString(GL_VERSION) << "\nGLSL " << glGetString(GL_SHADING_LANGUAGE_VERSION); }
/** * @brief ParticleSystem initialization method */ bool ParticleSystem::Init(void) { if (gl3wInit()) { fprintf(stderr, "Error: Failed to initialize gl3w.\n"); return false; } return true; }
/// <summary>Loads in SDL, and OpenGL functions</summary> /// <remarks>If <code>initialize</code> fails, <code>ErrorReport</code> and consequently <code>Terminate</code> will be called, /// <para>unloading resources. All that needs to be done on failed intialize is return -1 in main</para></remarks> /// <returns>true if all content loaded successfully, false otherwise</returns> void load(int windowWidth, int windowHeight) { // SDL Initialization if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { throw SDLInitError("SDL Libs failed to initialize"); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // sets sdl to provide gl core context // creation of a window context to allow open gl function references to be obtained SDL_Window* window = SDL_CreateWindow("Hello SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, SDL_WINDOW_OPENGL); if (window == NULL) { throw SDLInitError("Window failed to create"); } SDL_GLContext glContext = SDL_GL_CreateContext(window); if (glContext == NULL) { throw SDLInitError("GLContext failed to create"); } if (gl3wInit()) { throw InitError("gl3w failed to initialize"); } }
int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_ALPHA ); glutInitContextVersion (3, 3); glutInitContextProfile(GLUT_CORE_PROFILE); glutInitWindowSize (windowWidth, windowHeight); glutInitWindowPosition (300, 200); glutCreateWindow ("My window GL"); if(gl3wInit()<0) return 1; glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutSpecialFunc(keyboardS); glutSpecialUpFunc(keyboardSpecialUpFunc); glutMouseFunc(mouseFcn); glutMotionFunc(mouseMoveFnc); glutMouseWheelFunc(mouseWheelFnc); glutMainLoop(); finalizeProgram(gouraudShading); return(0); }
void Subsystem::Startup() { gl3wInit(); ImGui_ImplGlfwGL3_Init(Graphics::Subsystem::Instance()->Adapter->Window, true); Initialized = true; }
void init_gl3w() { if (gl3wInit()) { throw std::runtime_error("Failed to initialize opengl."); } if (!gl3wIsSupported(3, 3)) { throw std::runtime_error("OpenGL 3.3 not supported."); } }
int main(int argc, char** argv) { try { if (argc < 2) { printUsage(); exit(EXIT_FAILURE); } std::string configurationFile = argv[1]; if (configurationFile.empty()) { printUsage(); exit(EXIT_FAILURE); } Application application("RoadNetworkGenerator", DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT); if (gl3wInit()) { throw std::runtime_error("gl3wInit() failed"); } cudaDeviceProp deviceProperties; cudaGetDeviceProperties(&deviceProperties, 0); cudaSetDevice(0); RoadNetworkGeometry geometry; Camera camera(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, FOVY_DEG, ZNEAR, ZFAR); RoadNetworkInputController inputController(camera); SceneRenderer renderer(camera, geometry); application.setCamera(camera); application.setRenderer(renderer); application.setInputController(inputController); // --- // TODO: // --- return application.run(); } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } // DEBUG: system("pause"); return -1; }
//============================================================================================= // //============================================================================================= opengl_device::opengl_device(window *win) : m_impl(new internal::opengl_device_impl(win->platform_impl())) { if(gl3wInit()) throw light::runtime_error("Initializing gl3w failed"); int major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); GRAF_INFO_MSG("OpenGL {}.{} context created\n", major, minor); }
void WGLRenderer::init() { nativeGraphicsContext->makeCurrent(); if (gl3wInit()) { throw std::runtime_error("Failed to initialize OpenGL"); } if (!gl3wIsSupported(3, 3)) { throw std::runtime_error("OpenGL 3.3 is not supported"); } }
int main(int, char**) { // Setup window glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(1); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(1280, 720, "Empty imgui program", NULL, NULL); glfwMakeContextCurrent(window); gl3wInit(); // Setup ImGui binding ImGui_ImplGlfwGL3_Init(window, true); ImVec4 clear_color = ImColor(114, 144, 154); // Main loop while (!glfwWindowShouldClose(window)) { ImGuiIO& io = ImGui::GetIO(); glfwPollEvents(); ImGui_ImplGlfwGL3_NewFrame(); make_gui(); // Rendering glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ImGui::Render(); glfwSwapBuffers(window); } // Cleanup ImGui_ImplGlfwGL3_Shutdown(); glfwTerminate(); return 0; }
WGLContextObj::WGLContextObj(HDC deviceContext) : deviceContext(deviceContext) { openGLContext = wglCreateContext(deviceContext); wglMakeCurrent(deviceContext, openGLContext); if (gl3wInit()) { throw std::runtime_error("Failed to initialize OpenGL"); } if (!gl3wIsSupported(3, 3)) { throw std::runtime_error("OpenGL 3.3 is not supported"); } }
MainWindow::MainWindow() { // Setup window glfwSetErrorCallback(on_error); if (!glfwInit()) exit(1); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(1280, 720, "xds", NULL, NULL); if (window) { glfwMakeContextCurrent(window); gl3wInit(); ImGui_ImplGlfwGL3_Init(window, true); while (!glfwWindowShouldClose(window)) { ImGuiIO& io = ImGui::GetIO(); glfwPollEvents(); ImGui_ImplGlfwGL3_NewFrame(); ImGui::SetNextWindowSize(ImVec2(400, 100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Test Window"); ImGui::Text("TODO: Move this to new thread so xds can run in the background."); ImGui::Text("Close the window to continue xds execution."); ImGui::End(); // Rendering glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); ImVec4 clear_color = ImColor(114, 144, 154); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); glfwSwapBuffers(window); } // Cleanup ImGui_ImplGlfwGL3_Shutdown(); glfwTerminate(); } }
bool glInit() { if (gl3wInit()) { printf("Problem initializing OpenGL\n"); return false; } int maj, min, slmaj, slmin; getGlVersion(&maj, &min); getGlslVersion(&slmaj, &slmin); printf("OpenGL version: %d.%d\n", maj, min); printf("GLSL version: %d.%d\n", slmaj, slmin); return true; }
int main(int argc, char ** argv) { GLFWwindow* window; if (!glfwInit()) { std::cout << "glfw failed, aborting...\n"; exit(-1); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Procedural Sphere", NULL, NULL); if (!window){ std::cout << "No window available, aborting..."; glfwTerminate(); exit(-1); } glfwMakeContextCurrent(window); if(gl3wInit() != 0) { std::cout << "gl3w failed, aborting...\n"; exit(-1); }; std::cout << glGetString(GL_VERSION) << "\n"; glEnable(GL_DEPTH_TEST); Sphere sphere = Sphere(atoi(argv[1])); while (!glfwWindowShouldClose(window)) { usleep( 40 * 1000 ); sphere.renderSphere->Render(WINDOW_WIDTH, WINDOW_HEIGHT); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
void ToonixGLDrawer_Init ( XSI::CRef in_pSequencerContext, LPVOID *in_pUserData ) { int initGL3W = gl3wInit(); // Cast the CRef into a GraphicSequencerContext SDK object XSI::GraphicSequencerContext l_vGraphicSequencerContext = in_pSequencerContext; // make sure the cast succeeded assert ( l_vGraphicSequencerContext.IsValid() ); // get the sequencer from the context object XSI::CGraphicSequencer in_pSequencer = l_vGraphicSequencerContext.GetGraphicSequencer (); // use the sequencer to register the callback in_pSequencer.RegisterDisplayCallback(L"ToonixGLDrawer",0,XSI::siPostPass,XSI::siCustom,L"ToonixPass"); //in_pSequencer.RegisterDisplayCallback ( L"ToonixGLDrawer", 0, XSI::siPostEndFrame, XSI::siRealtimePortMaterial, L"ToonixPass"); }
void main(int argc, char** argv) { glutInit(&argc,argv); glutCreateWindow("GLSL Texture Mapping Demo"); glutDisplayFunc(&redraw); glutTimerFunc(20,&update,0); glutKeyboardFunc(&key_down); glutReshapeWindow(600,600); gl3wInit(); // must initialize OpenGL 3.0 or else crashy crashy! init_program(); init_vertex_buffer(); texid = gl_loadtexture("checker.png"); //texid = gl_loadtexture("checker_small.png"); //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glutMainLoop(); }
GLAPIInitializer( int gl_ver_major = 3, int gl_ver_minor = 3 ) { auto init_failed = gl3wInit(); glGetError(); if(init_failed) { throw std::runtime_error( "OpenGL/GL3W initialization error." ); } if(!gl3wIsSupported(gl_ver_major, gl_ver_minor)) { throw std::runtime_error( "Requested OpenGL version not supported" ); } }
void Context::InitSimpleWindow() { #if defined(DSGL_GLFW) if (!glfwInit()) { throw Exception(DSGL_GLFW_INIT_FAILED, DSGL_MSG_GLFW_INIT_FAILED); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, this->glMajorVersion); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, this->glMinorVersion); this->window = glfwCreateWindow(this->width, this->height, this->name.c_str(), NULL, NULL); if (!window) { throw Exception(DSGL_WINDOW_POINTER_NULL, DSGL_MSG_WINDOW_POINTER_NULL); } glfwMakeContextCurrent(window); #endif #if defined(DSGL_GL3W) if(gl3wInit() != 0) { throw Exception(DSGL_GL3W_INIT_FAILED, DSGL_MSG_GL3W_INIT_FAILED); } #endif }
/* 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() { int width = 640; int height = 480; if(glfwInit() == GL_FALSE) { std::cerr << "failed to init GLFW" << std::endl; return 1; } // sadly glew doesn't play nice with core profiles... glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3); // create a window if(glfwOpenWindow(width, height, 0, 0, 0, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { std::cerr << "failed to open window" << std::endl; glfwTerminate(); return 1; } // setup windows close callback glfwSetWindowCloseCallback(closedWindow); if (gl3wInit()) { std::cerr << "failed to init GL3W" << std::endl; glfwCloseWindow(); glfwTerminate(); return 1; } // shader source code std::string vertex_source = "#version 330\n" "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec2 vtexcoord;\n" "out vec2 ftexcoord;\n" "void main() {\n" " ftexcoord = vtexcoord;\n" " gl_Position = vposition;\n" "}\n"; std::string fragment_source = "#version 330\n" "uniform sampler2D tex;\n" // texture uniform "in vec2 ftexcoord;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = texture(tex, ftexcoord);\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); check_program_link_status(shader_program); // get texture uniform location GLint texture_location = glGetUniformLocation(shader_program, "tex"); // vao and vbo handle GLuint vao, vbo, ibo; // generate and bind the vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); // generate and bind the vertex buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // data for a fullscreen quad (this time with texture coords) GLfloat vertexData[] = { // X Y Z U V 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // vertex 0 -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // vertex 1 1.0f,-1.0f, 0.0f, 1.0f, 0.0f, // vertex 2 -1.0f,-1.0f, 0.0f, 0.0f, 0.0f, // vertex 3 }; // 4 vertices with 5 components (floats) each // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*4*5, vertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); // generate and bind the index buffer object glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); GLuint indexData[] = { 0,1,2, // first triangle 2,1,3, // second triangle }; // fill with data glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*3, indexData, GL_STATIC_DRAW); // "unbind" vao glBindVertexArray(0); // texture handle GLuint texture; // generate texture glGenTextures(1, &texture); // bind the texture glBindTexture(GL_TEXTURE_2D, texture); // create some image data std::vector<GLubyte> image(4*width*height); for(int j = 0;j<height;++j) for(int i = 0;i<width;++i) { size_t index = j*width + i; image[4*index + 0] = 0xFF*(j/10%2)*(i/10%2); // R image[4*index + 1] = 0xFF*(j/13%2)*(i/13%2); // G image[4*index + 2] = 0xFF*(j/17%2)*(i/17%2); // B image[4*index + 3] = 0xFF; // A } // set texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // set texture content glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]); running = true; while(running) { // terminate on excape if(glfwGetKey(GLFW_KEY_ESC)) { running = false; } // clear first glClear(GL_COLOR_BUFFER_BIT); // use the shader program glUseProgram(shader_program); // bind texture to texture unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); // set texture uniform glUniform1i(texture_location, 0); // bind the vao glBindVertexArray(vao); // draw glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << gluErrorString(error); running = false; } // finally swap buffers glfwSwapBuffers(); } // delete the created objects glDeleteTextures(1, &texture); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); glfwCloseWindow(); glfwTerminate(); return 0; }
int main(int argc, char** argv) { if(argc != 2) { std::cout << "Usage:\n\t" << argv[0] << " IMAGE" << std::endl; return 1; } // Setup window glfwSetErrorCallback(error_callback); if (!glfwInit()) return 1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow* window = glfwCreateWindow(1280, 720, "HBVisionGraphEditor", NULL, NULL); glfwMakeContextCurrent(window); gl3wInit(); // Setup ImGui binding ImGui_ImplGlfwGL3_Init(window, true); ImVec4 clear_color = ImColor(39, 40, 34); cv::Mat image = cv::imread(argv[1]); Solution solution(image); AlgSimple simple; Preview preview{solution}; Preview preview2{solution}; while (!glfwWindowShouldClose(window)) { if(!glfwGetWindowAttrib(window, GLFW_ICONIFIED) && glfwGetWindowAttrib(window, GLFW_VISIBLE)) { glfwPollEvents(); ImGui_ImplGlfwGL3_NewFrame(); // Settings ImGui::BeginMainMenuBar(); int menuHeight = ImGui::GetTextLineHeightWithSpacing(); if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Quit")) { glfwSetWindowShouldClose(window, GL_TRUE); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); bool open = false; ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::SetNextWindowPos(ImVec2(0, menuHeight)); ImGui::SetNextWindowSize(ImVec2(400, ImGui::GetIO().DisplaySize.y - menuHeight)); if (ImGui::Begin("###main", &open, ImVec2(0, 0), 0.5f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoSavedSettings)) { if (ImGui::TreeNodeEx("Solution", ImGuiTreeNodeFlags_DefaultOpen)) { solution.draw(); ImGui::TreePop(); } if (ImGui::TreeNodeEx("Algorithm", ImGuiTreeNodeFlags_DefaultOpen)) { static int currentAlgorithm = 0; ImGui::Combo("###AlgorithmCombo", ¤tAlgorithm, "simple\0empty\0\0"); simple.draw(); ImGui::TreePop(); } ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); if (ImGui::Button("Calculate Pattern", ImVec2(ImGui::GetContentRegionAvailWidth(), 20))) { simple.calculate(solution); } } ImGui::End(); ImGui::PopStyleVar(); // Preview preview.draw(solution); preview2.draw(solution); // Rendering int display_w, display_h; glfwGetFramebufferSize(window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui::Render(); glfwSwapBuffers(window); } else { glfwWaitEvents(); } } // Cleanup ImGui_ImplGlfwGL3_Shutdown(); glfwTerminate(); return 0; }
void Application::init(const string &name) { if(glfwInit() == GL_FALSE) { throw runtime_error("Could not initialize GLFW"); } vector<int> hint { GLFW_CONTEXT_VERSION_MAJOR, 3, GLFW_CONTEXT_VERSION_MINOR, 2, GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE, GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE, GLFW_DEPTH_BITS, 16, GLFW_SAMPLES, 4, GLFW_REFRESH_RATE, 60, }; for (size_t h = 0; h < hint.size(); h += 2) glfwWindowHint(hint[h], hint[h+1]); ivec2 size(640, 480); m_window = glfwCreateWindow(size.x, size.y, name.c_str(), nullptr, nullptr); if (!m_window) { throw runtime_error("OpenGL initialization failed, invalid window hints"); } glfwMakeContextCurrent(m_window); #ifndef EMSCRIPTEN if(gl3wInit()) { throw runtime_error("failed to initialize gl3w"); } FMOD_RESULT result = FMOD::System_Create(&m_audio); checkError(result); result = m_audio->init(100, FMOD_INIT_NORMAL, nullptr); checkError(result); printf("ApplicationPath: %s\n", getApplicationPath()->c_str()); printf("ResourcePath: %s\n", getResourcePath()->c_str()); #else audioInit(); #endif // shader test auto handleVertex = glCreateShader(GL_VERTEX_SHADER); auto handleFragment = glCreateShader(GL_FRAGMENT_SHADER); string sourceVertexStr = "#version 150\n in vec3 a_pos; void main() { }"; string sourceFragmentStr = "#version 150\n in vec3 a_pos; out vec4 o_fragColor; void main() { o_fragColor = vec4(1, 0, 1, 1); }"; const GLchar *sv = sourceVertexStr.c_str(); const GLchar *sf = sourceVertexStr.c_str(); auto check = [](GLuint handle) { GLint status; glGetShaderiv(handle, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint logLength; glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logLength); GLchar *logStr = new GLchar[logLength + 1]; glGetShaderInfoLog(handle, logLength, nullptr, logStr); fprintf(stderr, "Shader compiler error:\n%s\n", logStr); delete[] logStr; } }; glShaderSource(handleVertex, 1, &sv, nullptr); glShaderSource(handleFragment, 1, &sf, nullptr); glCompileShader(handleVertex); check(handleVertex); glCompileShader(handleFragment); check(handleFragment); GLint status; auto handleProgram = glCreateProgram(); glAttachShader(handleProgram, handleVertex); glAttachShader(handleProgram, handleFragment); glLinkProgram(handleProgram); glGetProgramiv(handleProgram, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint logLength; glGetProgramiv(handleProgram, GL_INFO_LOG_LENGTH, &logLength); GLchar *logStr = new GLchar[logLength + 1]; glGetProgramInfoLog(handleProgram, logLength, nullptr, logStr); fprintf(stderr, "Linker error:\n%s\n", logStr); delete[] logStr; return; } glDetachShader(handleProgram, handleVertex); glDetachShader(handleProgram, handleFragment); }
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; }
int main() { int width = 640; int height = 480; if(glfwInit() == GL_FALSE) { std::cerr << "failed to init GLFW" << std::endl; return 1; } // select opengl version glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3); // create a window if(glfwOpenWindow(width, height, 0, 0, 0, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { std::cerr << "failed to open window" << std::endl; glfwTerminate(); return 1; } // setup windows close callback glfwSetWindowCloseCallback(closedWindow); if (gl3wInit()) { std::cerr << "failed to init GL3W" << std::endl; glfwCloseWindow(); glfwTerminate(); return 1; } // shader source code std::string vertex_source = "#version 330\n" "layout(std140) uniform Matrices {\n" " mat4 ViewProjection;\n" " mat4 Model[8];\n" "};\n" "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec4 vcolor;\n" "out vec4 fcolor;\n" "void main() {\n" " fcolor = vcolor;\n" " gl_Position = ViewProjection*Model[gl_InstanceID]*vposition;\n" "}\n"; std::string fragment_source = "#version 330\n" "in vec4 fcolor;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = fcolor;\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); check_program_link_status(shader_program); // obtain location of the uniform block GLuint Matrices_binding = 0; GLint uniform_block_index = glGetUniformBlockIndex(shader_program, "Matrices"); // assign the block binding glUniformBlockBinding(shader_program, uniform_block_index, Matrices_binding); // create uniform buffer GLuint ubo; glGenBuffers(1, &ubo); glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferData(GL_UNIFORM_BUFFER, 9*sizeof(float)*4*4, 0, GL_STREAM_DRAW); // fill the Model matrix array glm::mat4 ModelMatrices[8]; ModelMatrices[0] = glm::translate(glm::mat4(1.0f), glm::vec3( 2.0f, 2.0f, 2.0f)); ModelMatrices[1] = glm::translate(glm::mat4(1.0f), glm::vec3( 2.0f, 2.0f,-2.0f)); ModelMatrices[2] = glm::translate(glm::mat4(1.0f), glm::vec3( 2.0f,-2.0f, 2.0f)); ModelMatrices[3] = glm::translate(glm::mat4(1.0f), glm::vec3( 2.0f,-2.0f,-2.0f)); ModelMatrices[4] = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f, 2.0f, 2.0f)); ModelMatrices[5] = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f, 2.0f,-2.0f)); ModelMatrices[6] = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f,-2.0f, 2.0f)); ModelMatrices[7] = glm::translate(glm::mat4(1.0f), glm::vec3(-2.0f,-2.0f,-2.0f)); glBufferSubData(GL_UNIFORM_BUFFER, sizeof(float)*4*4, 8*sizeof(float)*4*4, ModelMatrices); // vao and vbo handle GLuint vao, vbo, ibo; // generate and bind the vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); // generate and bind the vertex buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // data for a cube GLfloat vertexData[] = { // X Y Z R G B // face 0: 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 0 -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 1 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 2 -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 3 // face 1: 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // vertex 0 1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // vertex 1 1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 0.0f, // vertex 2 1.0f,-1.0f,-1.0f, 0.0f, 1.0f, 0.0f, // vertex 3 // face 2: 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // vertex 0 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, // vertex 1 -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // vertex 2 -1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, // vertex 3 // face 3: 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 0 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 1 -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 3 // face 4: -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // vertex 0 -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f, // vertex 1 -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 0.0f, 1.0f, 1.0f, // vertex 3 // face 5: 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // vertex 0 -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // vertex 1 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // vertex 3 }; // 6 faces with 4 vertices with 6 components (floats) // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*4*6, vertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); // generate and bind the index buffer object glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); GLuint indexData[] = { // face 0: 0,1,2, // first triangle 2,1,3, // second triangle // face 1: 4,5,6, // first triangle 6,5,7, // second triangle // face 2: 8,9,10, // first triangle 10,9,11, // second triangle // face 3: 12,13,14, // first triangle 14,13,15, // second triangle // face 4: 16,17,18, // first triangle 18,17,19, // second triangle // face 5: 20,21,22, // first triangle 22,21,23, // second triangle }; // fill with data glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*6*2*3, indexData, GL_STATIC_DRAW); // "unbind" vao glBindVertexArray(0); // we are drawing 3d objects so we want depth testing glEnable(GL_DEPTH_TEST); running = true; while(running) { // get the time in seconds float t = glfwGetTime(); // terminate on escape if(glfwGetKey(GLFW_KEY_ESC)) { running = false; } // clear first glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // use the shader program glUseProgram(shader_program); // calculate ViewProjection matrix glm::mat4 Projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 100.f); // translate the world/view position glm::mat4 View = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f)); // make the camera rotate around the origin View = glm::rotate(View, 90.0f*t, glm::vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ViewProjection = Projection*View; // set the ViewProjection in the uniform buffer glBindBuffer(GL_UNIFORM_BUFFER, ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(float)*4*4, glm::value_ptr(ViewProjection)); glBindBufferRange(GL_UNIFORM_BUFFER, Matrices_binding, ubo, 0, sizeof(float)*4*4*9); // bind the vao glBindVertexArray(vao); // draw // the additional parameter indicates how many instances to render glDrawElementsInstanced(GL_TRIANGLES, 6*6, GL_UNSIGNED_INT, 0, 8); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << gluErrorString(error); running = false; } // finally swap buffers glfwSwapBuffers(); } // delete the created objects glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); glfwCloseWindow(); glfwTerminate(); return 0; }
int main() { int width = 640; int height = 480; if(glfwInit() == GL_FALSE) { std::cerr << "failed to init GLFW" << std::endl; return 1; } // sadly glew doesn't play nice with core profiles... glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3); // create a window if(glfwOpenWindow(width, height, 0, 0, 0, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { std::cerr << "failed to open window" << std::endl; glfwTerminate(); return 1; } // setup windows close callback glfwSetWindowCloseCallback(closedWindow); if (gl3wInit()) { std::cerr << "failed to init GL3W" << std::endl; glfwCloseWindow(); glfwTerminate(); return 1; } // shader source code std::string vertex_source = "#version 330\n" "uniform mat4 ViewProjection;\n" // the projection matrix uniform "layout(location = 0) in vec4 vposition;\n" "layout(location = 1) in vec4 vcolor;\n" "layout(location = 2) in vec3 voffset;\n" // the per instance offset "out vec4 fcolor;\n" "void main() {\n" " fcolor = vcolor;\n" " gl_Position = ViewProjection*(vposition + vec4(voffset, 0));\n" "}\n"; std::string fragment_source = "#version 330\n" "in vec4 fcolor;\n" "layout(location = 0) out vec4 FragColor;\n" "void main() {\n" " FragColor = fcolor;\n" "}\n"; // program and shader handles GLuint shader_program, vertex_shader, fragment_shader; // we need these to properly pass the strings const char *source; int length; // create and compiler vertex shader vertex_shader = glCreateShader(GL_VERTEX_SHADER); source = vertex_source.c_str(); length = vertex_source.size(); glShaderSource(vertex_shader, 1, &source, &length); glCompileShader(vertex_shader); if(!check_shader_compile_status(vertex_shader)) { return 1; } // create and compiler fragment shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); source = fragment_source.c_str(); length = fragment_source.size(); glShaderSource(fragment_shader, 1, &source, &length); glCompileShader(fragment_shader); if(!check_shader_compile_status(fragment_shader)) { return 1; } // create program shader_program = glCreateProgram(); // attach shaders glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); // link the program and check for errors glLinkProgram(shader_program); check_program_link_status(shader_program); // obtain location of projection uniform GLint ViewProjection_location = glGetUniformLocation(shader_program, "ViewProjection"); // vao and vbo handles GLuint vao, vbo, tbo, ibo; // generate and bind the vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); // generate and bind the vertex buffer object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // data for a cube GLfloat vertexData[] = { // X Y Z R G B // face 0: 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 0 -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 1 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 2 -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // vertex 3 // face 1: 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // vertex 0 1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // vertex 1 1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 0.0f, // vertex 2 1.0f,-1.0f,-1.0f, 0.0f, 1.0f, 0.0f, // vertex 3 // face 2: 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // vertex 0 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, // vertex 1 -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // vertex 2 -1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, // vertex 3 // face 3: 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 0 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 1 -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 0.0f, // vertex 3 // face 4: -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // vertex 0 -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f, // vertex 1 -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 0.0f, 1.0f, 1.0f, // vertex 3 // face 5: 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // vertex 0 -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, // vertex 1 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // vertex 2 -1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // vertex 3 }; // 6 faces with 4 vertices with 6 components (floats) // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*4*6, vertexData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat)); // generate and bind the index buffer object glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); GLuint indexData[] = { // face 0: 0,1,2, // first triangle 2,1,3, // second triangle // face 1: 4,5,6, // first triangle 6,5,7, // second triangle // face 2: 8,9,10, // first triangle 10,9,11, // second triangle // face 3: 12,13,14, // first triangle 14,13,15, // second triangle // face 4: 16,17,18, // first triangle 18,17,19, // second triangle // face 5: 20,21,22, // first triangle 22,21,23, // second triangle }; // fill with data glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*6*2*3, indexData, GL_STATIC_DRAW); // generate and bind the vertex buffer object containing the // instance offsets glGenBuffers(1, &tbo); glBindBuffer(GL_ARRAY_BUFFER, tbo); // the offsets GLfloat translationData[] = { 2.0f, 2.0f, 2.0f, // cube 0 2.0f, 2.0f,-2.0f, // cube 1 2.0f,-2.0f, 2.0f, // cube 2 2.0f,-2.0f,-2.0f, // cube 3 -2.0f, 2.0f, 2.0f, // cube 4 -2.0f, 2.0f,-2.0f, // cube 5 -2.0f,-2.0f, 2.0f, // cube 6 -2.0f,-2.0f,-2.0f, // cube 7 }; // 8 offsets with 3 components each // fill with data glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*8, translationData, GL_STATIC_DRAW); // set up generic attrib pointers glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat)); // a attrib divisor of 1 means that attribute 2 will advance once // every instance (0 would mean once per vertex) glVertexAttribDivisor(2, 1); // "unbind" vao glBindVertexArray(0); // we are drawing 3d objects so we want depth testing glEnable(GL_DEPTH_TEST); running = true; while(running) { // get the time in seconds float t = glfwGetTime(); // terminate on excape if(glfwGetKey(GLFW_KEY_ESC)) { running = false; } // clear first glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // use the shader program glUseProgram(shader_program); // calculate ViewProjection matrix glm::mat4 Projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 100.f); // translate the world/view position glm::mat4 View = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f)); // make the camera rotate around the origin View = glm::rotate(View, 90.0f*t, glm::vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ViewProjection = Projection*View; // set the uniform glUniformMatrix4fv(ViewProjection_location, 1, GL_FALSE, glm::value_ptr(ViewProjection)); // bind the vao glBindVertexArray(vao); // draw // the additional parameter indicates how many instances to render glDrawElementsInstanced(GL_TRIANGLES, 6*6, GL_UNSIGNED_INT, 0, 8); // check for errors GLenum error = glGetError(); if(error != GL_NO_ERROR) { std::cerr << gluErrorString(error); running = false; } // finally swap buffers glfwSwapBuffers(); } // delete the created objects glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); glDeleteBuffers(1, &tbo); glDetachShader(shader_program, vertex_shader); glDetachShader(shader_program, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(shader_program); glfwCloseWindow(); glfwTerminate(); return 0; }
int main(int argc, char** argv) { try { int cudaDevice; std::string lsystemFile; int screenWidth; int screenHeight; CmdOptions cmdOptions(argc, argv); cmdOptions.read("device", cudaDevice, 0); cmdOptions.read<std::string>("lsystemFile", lsystemFile, ""); cmdOptions.read("screenWidth", screenWidth, DEFAULT_SCREEN_WIDTH); cmdOptions.read("screenHeight", screenHeight, DEFAULT_SCREEN_HEIGHT); if (lsystemFile == "") { printUsage(); exit(EXIT_FAILURE); } Framework::GLWindow window("LSystem", screenWidth, screenHeight, true, false); if (gl3wInit()) { throw std::runtime_error("gl3wInit() failed"); } cudaDeviceProp deviceProperties; cudaGetDeviceProperties(&deviceProperties, cudaDevice); cudaSetDevice(cudaDevice); LSystem lsystem(lsystemFile); /********************************/ /* CENTER L-SYSTEM ON SCREEN */ /********************************/ float width = lsystem.getBounds().extents().x; float height = lsystem.getBounds().extents().y; float screenDiagonal = sqrt(pow(width, 2) + pow(height, 2) + 1); float distance = min((screenDiagonal / 2.0f) / tan(HALF_FOV_RAD), ZFAR); float aspectRatio = screenWidth / (float)screenHeight; math::float3 cameraCenter(lsystem.getBounds().center().x, lsystem.getBounds().center().y, -distance); math::float3 cameraForward = cameraCenter + math::float3(0, 0, -1); math::float3 cameraUp(0, 1, 0); ////////////////////////////////////////////////////////////////////////// SimpleCamera camera(FOV_RAD, aspectRatio, ZNEAR, ZFAR, cameraCenter, cameraForward, cameraUp); LSystemRenderer renderer(window, lsystem, camera); window.attach(&renderer); FirstPersonCameraNavigator navigator(&camera); LSystemInputHandler inputHandler(renderer, navigator); window.attach(static_cast<Framework::MouseInputHandler*>(&inputHandler)); window.attach(static_cast<Framework::KeyboardInputHandler*>(&inputHandler)); Framework::run(renderer, &inputHandler); return 0; } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; } catch (...) { std::cout << "Unknown error" << std::endl; } // DEBUG: system("pause"); return -1; }