int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // ======================================================= // INITIALIZE // ======================================================= glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGl Program", nullptr, nullptr); if (window == nullptr) { printf("Failed to create GLFW window\n"); glfwTerminate(); return false; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { printf("Failed to initialize GLEW\n"); return false; } glViewport(0, 0, WIDTH, HEIGHT); glEnable(GL_DEPTH_TEST); glfwSetKeyCallback(window, Key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // Build and compile our shader program Shader lightingShader("../Data/Shaders/vertexShaderLighting_nano.vs", "../Data/Shaders/fragmentShaderLighting_nano.frag", 2); Shader lampShader("../Data/Shaders/vertexShaderLighting_Lamp.vs", "../Data/Shaders/fragmentShaderLighting_Lamp.frag", 0); // set the application to capture the cursor glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glm::vec3 pointLightPositions[] = { glm::vec3(2.0f, 0.0f, 2.0f), glm::vec3(-2.0f, 0.0f, -2.0f), }; DirLight dirlight(lightingShader, vect3(-0.2f, -1.0f, -0.3f), vect3(255, 255, 255), 0.5f); PointLight pointLight1(lightingShader, pointLightPositions[0], vect3(255, 255, 255), 0.5f); PointLight pointLight2(lightingShader, pointLightPositions[1], vect3(255, 255, 255), 0.5f); //PointLight pointLight3(lightingShader, pointLightPositions[2], vect3(255, 255, 255), 1.0f); //PointLight pointLight4(lightingShader, pointLightPositions[3], vect3(255, 255, 255), 1.0f); SpotLight spotLight(lightingShader, MainCamera.Position, MainCamera.Front, vect3(255, 255, 255), 1.0f); GLfloat time = glfwGetTime(); Model nanosuit("../Data/Models/Box/OutPutModel.txt"); time = glfwGetTime() - time; printf("Time to load: %f", time); nanosuit.SetPosition(glm::vec3(0.0f, 0.0f, 0.0f)); // ======================================================= // MAIN UPDATE LOOP // ======================================================= //float count = 0; //GLfloat time = 0; while (!glfwWindowShouldClose(window)) { // Update deltaTime GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // FPS check //if (time >= 1.0f) //{ // printf("FPS: %f", count); // time = 0; // count = 0; //} // check and call events glfwPollEvents(); UpdateCamera(); // Rendering commands here //glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw triangle lightingShader.Use(); GLint viewPosLoc = lightingShader.GetUniformLocation("viewPos"); glUniform3f(viewPosLoc, MainCamera.Position.x, MainCamera.Position.y, MainCamera.Position.z); // Directional light dirlight.Update(); // Point lights pointLight1.Update(0); pointLight2.Update(1); // SpotLight spotLight.SetPosDir(MainCamera.Position, MainCamera.Front); spotLight.Update(); // Camera/View transformation glm::mat4 view; view = MainCamera.GetViewMatrix(); // set the projection matrix (perspective) glm::mat4 projectionMatrix; // FOV, aspect ratio, near plane, far plane projectionMatrix = glm::perspective(glm::radians(MainCamera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, farPlane); // specify matrices GLint modelLoc = lightingShader.GetUniformLocation("modelMat"); GLint viewLoc = lightingShader.GetUniformLocation("viewMat"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); GLint projLoc = lightingShader.GetUniformLocation("projectionMat"); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); //glm::mat4 model; //model = glm::translate(model, glm::vec3(0, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene //model += glm::translate(model, glm::vec3(0.2f, 0.0f, 0.0f)); //model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // It's a bit too big for our scene, so scale it down //glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "modelMat"), 1, GL_FALSE, glm::value_ptr(model)); nanosuit.Draw(lightingShader); // Swap the buffers glfwSwapBuffers(window); } // ======================================================= // CLEANUP // ======================================================= glfwTerminate(); return 0; }
int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(800, 600, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwSetScrollCallback(window, OnScroll); // GLFW settings glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(window, 0, 0); /* Make the window's context current */ glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { glfwTerminate(); return -1; } // print out some info about the graphics drivers std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; // OpenGL settings glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); init(); gCamera.setPosition(glm::vec3(0, 0, 4)); gCamera.setViewportAspectRatio(800.0f / 600.0f); double lastTime = glfwGetTime(); while (!glfwWindowShouldClose(window)) { /* Poll for and process events */ glfwPollEvents(); double thisTime = glfwGetTime(); Update((float)(thisTime - lastTime), window); lastTime = thisTime; Render(window); // check for errors GLenum error = glGetError(); if (error != GL_NO_ERROR) std::cerr << "OpenGL Error " << error << std::endl; //exit program if escape key is pressed if (glfwGetKey(window, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(window, GL_TRUE); } glfwTerminate(); return 0; }
// the program starts here void AppMain() { // initialise GLFW glfwSetErrorCallback(OnError); if(!glfwInit()) throw std::runtime_error("glfwInit failed"); // open a window with GLFW glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "Mek", NULL /*glfwGetPrimaryMonitor()*/, NULL); if (!gWindow) throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.3?"); // GLFW settings glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(gWindow, 0, 0); glfwSetScrollCallback(gWindow, OnScroll); glfwMakeContextCurrent(gWindow); // required or we crash on VAO creation glewExperimental = GL_TRUE; // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } // GLEW throws some errors so discard all the errors so far while(glGetError() != GL_NO_ERROR) {} // Init DevIL ilInit(); // enable vsync using windows only code #ifdef _WIN32 // Turn on vertical screen sync under Windows. typedef BOOL(WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval); PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL; wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapIntervalEXT) wglSwapIntervalEXT(1); #endif // print out some info about the graphics drivers std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; // make sure OpenGL version 3.2 API is available if(!GLEW_VERSION_3_3) throw std::runtime_error("OpenGL 3.3 API is not available."); // OpenGL settings glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialise the gWoodenCrate asset LoadWoodenCrateAsset(); // create all the instances in the 3D scene based on the gWoodenCrate asset CreateInstances(); // setup Camera::getInstance() Camera::getInstance().setPosition(glm::vec3(1100, 75, 0)); Camera::getInstance().setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y); Camera::getInstance().setNearAndFarPlanes(1.f, 500.0f); Camera::getInstance().setFieldOfView(179); crosshair = new twodOverlay("crosshair.png", 0, 0, 1); skull = new twodOverlayAnim("killSkull.png", 5, 0.5); startscreen = new twodOverlay("pressStart.png", 0, 0, 10); skull->updatePos(-0.85f, -0.75f, 4); skull ->cycle = true; //MODEL INITS prepProjectiles(); model = new GameObject(0); model->SetName("Moving"); gModel = new ComponentGraphics(); gModel->setOwner(model); gModel->loadModel("models/TallCube.dae"); Component* gp = gModel; model->AddComponent(GRAPHICS, gp); gCol = new ComponentCollision(); gCol->setCollisionMask(gModel->getScene()); gCol->setOwner(model); model->pos = glm::vec3(7.5, 0.5, -11); model->vel = 0.01; model->dir = glm::vec3(1, 0, 0); model->scale = glm::vec3(5, 5, 5); gCol->type = MOVING; gCol->createHitboxRender(); gp = gCol; model->AddComponent(PHYSICS, gp); ComponentInput* ci = new ComponentInput(0.05,0.05); gp = ci; model->AddComponent(CONTROLLER, gp); //PROPER INIT for (int i = 0; i < 22; i++) { if (i != 3 && i != 0 && i != 4 && i != 8 && i != 18 && i != 19 && i != 20 && i !=21) { GameObject *gObject = new GameObject(goVec.size()); ComponentGraphics *cModel = new ComponentGraphics(); ComponentCollision *cCollision = new ComponentCollision(); Component *c; if (i == 0) { gObject->SetName("Spawn Container 1"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(60, 0, -110); } else if (i == 1) { gObject->SetName("Water Tower"); cModel->loadModel("models/Watertower.dae"); gObject->scale = glm::vec3(3, 3, 3); gObject->pos = glm::vec3(-65, 0, -90); } else if (i == 2) { gObject->SetName("MenuScene"); cModel->loadModel("models/Warehouse_One_mesh_No_roof.dae"); gObject->scale = glm::vec3(1, 1, 1);// glm::vec3(1.6, 1.6, 1.6); gObject->pos = glm::vec3(10000, 0, 0); } else if (i == 3) { gObject->SetName("Spawn Container 2"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(85, 0, -75); } else if (i == 4) { gObject->SetName("Middle Plus"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(15, 0, -20); } else if (i == 5) { gObject->SetName("North Wall"); cModel->loadModel("models/Container_Wal_LPl.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(100, 0, 165); } else if (i == 6) { gObject->SetName("Dumbster");//Crane cModel->loadModel("models/Dumspter2.dae"); gObject->pos = glm::vec3(0, 0, -140); gObject->scale = glm::vec3(0.4, 0.4, 0.4); } else if (i == 7) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(0, 0, 120); } else if (i == 8) { gObject->SetName("Middle Plus"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-5, 0, -20); } else if (i == 9) { gObject->SetName("Container 2"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(80, 0, 100); } else if (i == 10) { gObject->SetName("South Wall"); cModel->loadModel("models/Container_Wal_LPl.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(-100, 0, 165); } else if (i == 11) { gObject->SetName("East Wall"); cModel->loadModel("models/Container_Wal_LP90.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(50, 0, 145); } else if (i == 12) { gObject->SetName("West Wall"); cModel->loadModel("models/Container_Wal_LP90.dae"); gObject->scale = glm::vec3(0.7, 0.70, 0.70); gObject->pos = glm::vec3(50, 0, -125); } else if (i == 13) { gObject->SetName("Container 2"); cModel->loadModel("models/Container.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(60, 0, 100); } else if (i == 14) { gObject->SetName("Container 90"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.70, 0.70, 0.70); gObject->pos = glm::vec3(70, 0, 70); } else if (i == 15) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(-30, 0, 120); } else if (i == 16) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(30, 0, 120); } else if (i == 17) { gObject->SetName("Shack"); cModel->loadModel("models/Shack.dae"); gObject->scale = glm::vec3(0.75, 0.75, 0.75); gObject->pos = glm::vec3(-60, 0, 120); } else if (i == 18) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(27, 0, -5); } else if (i == 19) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(27, 0, 15); } else if (i == 20) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-20, 0, 15); } else if (i == 21) { gObject->SetName("Middle Plus North"); cModel->loadModel("models/Container90.dae"); gObject->scale = glm::vec3(0.7, 0.7, 0.7); gObject->pos = glm::vec3(-20, 0, -5); } gObject->pos /= 10.f; cModel->setOwner(gObject); c = cModel; gObject->AddComponent(GRAPHICS, c); cCollision->setOwner(gObject); cCollision->setCollisionMask(cModel->getScene()); cCollision->type = STATIC; cCollision->setCollisionElip(glm::vec3(1, 1, 1)); cCollision->createHitboxRender(); gObject->AddComponent(PHYSICS, cCollision); goVec.push_back(gObject); } } LoadTargets(); spotLightColour = glm::normalize(spotLightColour); for (int i = 0; i < 6; i++) { LightComponent* light; if (i == 0) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.1f; lc->Base.Base.DiffuseIntensity = 0.1f; lc->Base.Atten.Constant = 0.1f; lc->Base.Atten.Exp = 0.1f; lc->Base.Atten.Linear = 0.1f; lc->Cutoff = 0.75f; lc->Base.Position = glm::vec3(-6, 1, 11); lc->Direction = glm::vec3(0, 0, -1); light->SetVars(lSPOT, lc); } if (i == 1) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.5f; lc->Base.Base.DiffuseIntensity = 0.5f; lc->Base.Atten.Constant = 0.5f; lc->Base.Atten.Exp = 0.5f; lc->Base.Atten.Linear = 0.5f; lc->Cutoff = 0.75f; lc->Base.Position = glm::vec3(3, 1, 11); lc->Direction = (glm::vec3(0, 0, 10)); light->SetVars(lSPOT, lc); } if (i == 2) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = glm::vec3(0,0.1,0); //lc->Base.Base.AmbientIntensity = 0.5f; //lc->Base.Base.DiffuseIntensity = 0.5f; // //lc->Base.Atten.Constant = 0.5f; //lc->Base.Atten.Exp = 0.5f; //lc->Base.Atten.Linear = 0.5f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(-3, 1, 11); //lc->Direction = (glm::vec3(-3, 0, 12)); // //light->SetVars(lSPOT, lc); } if (i == 3) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = spotLightColour; //lc->Base.Base.AmbientIntensity = 0.5f; //lc->Base.Base.DiffuseIntensity = 0.5f; // //lc->Base.Atten.Constant = 0.5f; //lc->Base.Atten.Exp = 0.5f; //lc->Base.Atten.Linear = 0.5f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(-6, 1, 11); //lc->Direction = (glm::vec3(-6, 1, 12)); // //light->SetVars(lSPOT, lc); } if (i == 4) { //light = new LightComponent(lSPOT); //SpotLight* lc = new SpotLight; //lc->Base.Base.Color = spotLightColour; //lc->Base.Base.AmbientIntensity = 0.1f; //lc->Base.Base.DiffuseIntensity = 0.1f; // //lc->Base.Atten.Constant = 0.1f; //lc->Base.Atten.Exp = 0.1f; //lc->Base.Atten.Linear = 0.1f; // //lc->Cutoff = 0.75f; //lc->Base.Position = glm::vec3(0, 1, 0); //lc->Direction = glm::vec3(0, -1, 0); // //light->SetVars(lSPOT, lc); } if (i == 5) { light = new LightComponent(lSPOT); SpotLight* lc = new SpotLight; lc->Base.Base.Color = spotLightColour; lc->Base.Base.AmbientIntensity = 0.5f; lc->Base.Base.DiffuseIntensity = 0.5f; lc->Base.Atten.Constant = 0.5f; lc->Base.Atten.Exp = 0.5f; lc->Base.Atten.Linear = 0.5f; lc->Cutoff = 0.5f; lc->Base.Position = glm::vec3(1000, 1, 0);//4 1 0 lc->Direction = glm::vec3(0, -1, 0);// 5 0 0 light->SetVars(lSPOT, lc); } } animatedMech = new GameObject(100); animatedMechGC = new ComponentGraphics(); animatedMechGC->loadModel("models/Test_Animation_DAE.dae"); Component* c = animatedMechGC; animatedMech->AddComponent(GRAPHICS, c); animatedMech->pos = glm::vec3(0, 0, 0); animatedMech->scale = glm::vec3(1, 1, 1); //END MODEL INITS camInterp.points.push_back(glm::vec3(1025, 1, 0)); camInterp.points.push_back(glm::vec3(1000, 1, 25)); camInterp.points.push_back(glm::vec3(975, 1, 0)); camInterp.points.push_back(glm::vec3(1000, 1, -25)); camInterp.points.push_back(glm::vec3(1025, 1, 0)); camInterp.state = SLERP; camInterp.buildCurve(); TextRendering::getInstance().initText2D("MekFont.bmp"); fontColour = glm::normalize(fontColour); wglSwapIntervalEXT(1); // run while the window is open double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(gWindow)){ // process pending events glfwPollEvents(); // update the scene based on the time elapsed since last update double thisTime = glfwGetTime(); Update((float)(thisTime - lastTime)); lastTime = thisTime; // draw one frame Render(); // check for errors GLenum error = glGetError(); if (error != GL_NO_ERROR) { std::cerr << "OpenGL Error " << error << " - " << glewGetErrorString(error) << std::endl; } //exit program if escape key is pressed if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(gWindow, GL_TRUE); } // clean up and exit glfwTerminate(); }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader ourShader("7.4.camera.vs", "7.4.camera.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // world space positions of our cubes glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // activate shader ourShader.use(); // pass projection matrix to shader (note that in this case it could change every frame) glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); // camera/view transformation glm::mat4 view = camera.GetViewMatrix(); ourShader.setMat4("view", view); // render boxes glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
void dtemu_activate_context(void* context) { GLFWwindow* w = context; glfwMakeContextCurrent(*w); }
int _tmain(int argc, _TCHAR* argv[]) { GLFWwindow* window = 0; glfwSetErrorCallback(glfw_error_callback_func); // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } //----------------------------------------------------------------------------- glfwWindowHint(GLFW_SAMPLES, 4); // GL3.3 Core profile 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); glfwWindowHint(GLFW_VISIBLE, 0); //オフスクリーン // Open a window and create its OpenGL context window = glfwCreateWindow(1, 1, "GPGPU Test", NULL, NULL); if (window == NULL){ fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); #if defined _WIN32 // Initialize GLEW glewExperimental = GL_TRUE; ///!!!! important for core profile // コアプロファイルで必要となります if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } #endif { cout << "GL_VENDOR:" << glGetString(GL_VENDOR) << endl; cout << "GL_RENDERER:" << glGetString(GL_RENDERER) << endl; cout << "GL_VERSION:" << glGetString(GL_VERSION) << endl; cout << "GL_SHADING_LANGUAGE_VERSION:" << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } // Mat imgSrc = Mat(Size(32, 24), CV_32FC1); Mat imgSrc = Mat(Size(8, 4), CV_32FC1); Mat imgDst = Mat::zeros(imgSrc.size(), imgSrc.type()); //--------------------------------- //init Src image { const int width = imgSrc.cols; const int height = imgSrc.rows; for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++){ imgSrc.at<float>(y,x) = y*100.0f + x; } } } //--------------------------------- //Execute GPGPU { const int width = imgSrc.cols; const int height = imgSrc.rows; // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("GpGpuVertexShader.vertexshader", "GpGpuFragmentShader.fragmentshader"); // FBO identifier GLuint fbo = 0; //--------------------------------- // FBO // create FBO (off-screen framebuffer) glGenFramebuffers(1, &fbo); // bind offscreen framebuffer (that is, skip the window-specific render target) glBindFramebuffer(GL_FRAMEBUFFER, fbo); // texture enum E_TextureID{ SRC, DST, SIZEOF, }; unsigned int textureID[E_TextureID::SIZEOF]; //src dst //--------------------------------- // CreateTexture { GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float GLenum internalFormat = GL_R32F; //single channel float glGenTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); // create (reference to) a new texture for (int i = 0; i < sizeof(textureID) / sizeof(textureID[0]); i++){ glBindTexture(GL_TEXTURE_2D, textureID[i]); // (set texture parameters here) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //create the texture glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, 0); glBindTexture(GL_TEXTURE_2D, 0); } } //upload imgSrc to texture { GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgSrc.data; glBindTexture(GL_TEXTURE_2D, textureID[E_TextureID::SRC]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data); glBindTexture(GL_TEXTURE_2D, 0); } //Execute { glUseProgram(programID); GLuint vao; GLuint vbo; // [-1, 1] の正方形 static GLfloat position[][2] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { 1.0f, 1.0f }, { -1.0f, 1.0f } }; // create vao&vbo glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); // bind vao & vbo glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); // upload vbo data glBufferData(GL_ARRAY_BUFFER, (int)sizeof(position), position, GL_STATIC_DRAW); // Set VertexAttribute GLint attrLoc = glGetAttribLocation(programID, "position"); glEnableVertexAttribArray(attrLoc); //enable attribute Location glVertexAttribPointer( attrLoc, // attribute 0. No particular reason for 0, but must match the layout in the shader. 2, // size (Specifies the number of components) x,y GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (Specifies the byte offset between consecutive generic vertex attributes) (void*)0 // array buffer offset (Specifies a pointer to the first generic vertex attribute in the array) ); //Bind Texture & Fbo const int textureUnit = 0; glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, textureID[E_TextureID::SRC]); glUniform1i(glGetUniformLocation(programID, "texSrc"), textureUnit); glUniform2f(glGetUniformLocation(programID, "texSrcSize"),width,height); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID[E_TextureID::DST], 0); //Viewport glViewport(0, 0, width, height); //Render!! glDrawArrays(GL_TRIANGLE_FAN, 0, (int)(sizeof(position) / sizeof(position[0]))); glFlush(); // delete vao&vbo glBindVertexArray(0); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } { //download from framebuffer GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgDst.data; int width = imgDst.cols; int height = imgDst.rows; //wait for Rendering glFinish(); // ReadBuffer glReadBuffer(GL_COLOR_ATTACHMENT0); // ReadPixels glReadPixels(0, 0, width, height, format, type, data); } //clean up glDeleteFramebuffers(1, &fbo); glDeleteTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); glDeleteProgram(programID); } //dump { cout << "imgSrc" << endl; cout << imgSrc << endl; cout << "imgDst" << endl; cout << imgDst << endl; } //verify int errNum = 0; { //verify int width = imgSrc.cols; int height = imgSrc.rows; for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++){ float src = imgSrc.at<float>(y, x); float dst = imgDst.at<float>(y, x); if (src != dst) errNum++; } } cout << "ErrNum:" << errNum << endl; } #if 0 //visualize { imshow("src", imgSrc); imshow("dst", imgDst); waitKey(); } #endif // Close OpenGL window and terminate GLFW glfwTerminate(); cout << "Hit return key" << endl; cin.get(); return errNum; }
int main(int argc, char** argv) { int ch, api = 0, profile = 0, strategy = 0, major = 1, minor = 0, revision; GLboolean debug = GL_FALSE, forward = GL_FALSE, list = GL_FALSE; GLint flags, mask; GLFWwindow* window; if (!valid_version()) exit(EXIT_FAILURE); while ((ch = getopt(argc, argv, "a:dfhlm:n:p:r:")) != -1) { switch (ch) { case 'a': if (strcasecmp(optarg, API_OPENGL) == 0) api = GLFW_OPENGL_API; else if (strcasecmp(optarg, API_OPENGL_ES) == 0) api = GLFW_OPENGL_ES_API; else { usage(); exit(EXIT_FAILURE); } case 'd': debug = GL_TRUE; break; case 'f': forward = GL_TRUE; break; case 'h': usage(); exit(EXIT_SUCCESS); case 'l': list = GL_TRUE; break; case 'm': major = atoi(optarg); break; case 'n': minor = atoi(optarg); break; case 'p': if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0) profile = GLFW_OPENGL_CORE_PROFILE; else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0) profile = GLFW_OPENGL_COMPAT_PROFILE; else { usage(); exit(EXIT_FAILURE); } break; case 'r': if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0) strategy = GLFW_NO_RESET_NOTIFICATION; else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0) strategy = GLFW_LOSE_CONTEXT_ON_RESET; else { usage(); exit(EXIT_FAILURE); } break; default: usage(); exit(EXIT_FAILURE); } } argc -= optind; argv += optind; // Initialize GLFW and create window glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); if (major != 1 || minor != 0) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); } if (api != 0) glfwWindowHint(GLFW_CLIENT_API, api); if (debug) glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); if (forward) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); if (profile != 0) glfwWindowHint(GLFW_OPENGL_PROFILE, profile); if (strategy) glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, strategy); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); window = glfwCreateWindow(200, 200, "Version", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // Report client API version api = glfwGetWindowAttrib(window, GLFW_CLIENT_API); major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); printf("%s context version string: \"%s\"\n", get_client_api_name(api), glGetString(GL_VERSION)); printf("%s context version parsed by GLFW: %u.%u.%u\n", get_client_api_name(api), major, minor, revision); // Report client API context properties if (api == GLFW_OPENGL_API) { if (major >= 3) { glGetIntegerv(GL_CONTEXT_FLAGS, &flags); printf("%s context flags (0x%08x):", get_client_api_name(api), flags); if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) printf(" forward-compatible"); if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) printf(" debug"); if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB) printf(" robustness"); putchar('\n'); printf("%s context flags parsed by GLFW:", get_client_api_name(api)); if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT)) printf(" forward-compatible"); if (glfwGetWindowAttrib(window, GLFW_OPENGL_DEBUG_CONTEXT)) printf(" debug"); if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) != GLFW_NO_ROBUSTNESS) printf(" robustness"); putchar('\n'); } if (major > 3 || (major == 3 && minor >= 2)) { int profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE); glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask); printf("%s profile mask (0x%08x): %s\n", get_client_api_name(api), mask, get_profile_name_gl(mask)); printf("%s profile mask parsed by GLFW: %s\n", get_client_api_name(api), get_profile_name_glfw(profile)); } if (glfwExtensionSupported("GL_ARB_robustness")) { int robustness; GLint strategy; glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy); printf("%s robustness strategy (0x%08x): %s\n", get_client_api_name(api), strategy, get_strategy_name_gl(strategy)); robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS); printf("%s robustness strategy parsed by GLFW: %s\n", get_client_api_name(api), get_strategy_name_glfw(robustness)); } } printf("%s context renderer string: \"%s\"\n", get_client_api_name(api), glGetString(GL_RENDERER)); printf("%s context vendor string: \"%s\"\n", get_client_api_name(api), glGetString(GL_VENDOR)); if (major > 1) { printf("%s context shading language version: \"%s\"\n", get_client_api_name(api), glGetString(GL_SHADING_LANGUAGE_VERSION)); } // Report client API extensions if (list) list_extensions(api, major, minor); glfwTerminate(); exit(EXIT_SUCCESS); }
int main() { std::cout << glfwGetVersionString() << std::endl; GLuint texture{ 0 }, sampler{ 0 }; GLuint vbo{ 0 }, vao{ 0 }; GLuint vs{ 0 }, fs{ 0 }, program{ 0 }; FT_Library ft_lib{ nullptr }; FT_Face face{ nullptr }; auto cleanup = [&]() { FT_Done_Face(face); FT_Done_FreeType(ft_lib); glDeleteTextures(1, &texture); glDeleteSamplers(1, &sampler); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); glDeleteShader(vs); glDeleteShader(fs); glDeleteProgram(program); }; // Initialize and load our freetype face if (FT_Init_FreeType(&ft_lib) != 0) { std::cerr << "Couldn't initialize FreeType library\n"; cleanup(); return 1; } if (FT_New_Face(ft_lib, "../Dependencies/fonts/Kalypsa-Medium.ttf", 0, &face) != 0) { std::cerr << "Unable to load myfont.ttf\n"; cleanup(); return 1; } // Create a GLFW window if (glfwInit() != GL_TRUE) { std::cerr << "Couldn't load GLFW library\n"; cleanup(); return 1; } 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); const int WIDTH = 640; const int HEIGHT = 480; const double SCALEX = 2.0 / WIDTH; const double SCALEY = 2.0 / HEIGHT; auto window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL Text Rendering", nullptr, nullptr); glfwMakeContextCurrent(window); glViewport(0, 0, WIDTH, HEIGHT); // Initialize our texture and VBOs glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); glGenTextures(1, &texture); glGenSamplers(1, &sampler); glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Initialize shader vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &VERTEX_SHADER, 0); glCompileShader(vs); fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &FRAGMENT_SHADER, 0); glCompileShader(fs); program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); // Set some initialize GL state glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.1, 0.2, 0.4, 0); // Get shader uniforms glUseProgram(program); glBindAttribLocation(program, 0, "in_Position"); GLuint texUniform = glGetUniformLocation(program, "tex"); GLuint colorUniform = glGetUniformLocation(program, "color"); while (glfwWindowShouldClose(window) != GL_TRUE) { glfwMakeContextCurrent(window); glClear(GL_COLOR_BUFFER_BIT); // Bind stuff glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glBindSampler(0, sampler); glBindVertexArray(vao); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glUseProgram(program); glUniform4f(colorUniform, 1, 1, 1, 1); glUniform1i(texUniform, 0); FT_Set_Pixel_Sizes(face, 0, 50); render_text("Hello World!", face, -0.5, 0, SCALEX, SCALEY); glfwSwapBuffers(window); glfwPollEvents(); } cleanup(); return 0; }
int main(int argc, const char * argv[]) { const int WIDTH = 800; const int HEIGHT = 600; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwSetErrorCallback(glfwErrorCallback); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { printf("Failed to create GLFW window"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // GLEW负责管理每个平台上应该调用哪个函数指针,所以在调用openGL之前,先初始化它 glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } // Define the viewport dimensions int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glfwSetKeyCallback(window, key_callback); // Build and compile our shader program // Vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); // Check for compile time errors GLint success; GLchar infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // Fragment shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); // Check for compile time errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // Link shaders GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // Check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { 0.5f, 0.5f, 0.0f, // Top Right 0.5f, -0.5f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, // bottom left }; GLfloat vertices2[] = { 0.8f, 0.5f, 0.0f, // Top Right 0.8f, -0.5f, 0.0f, // Bottom Right -0.2f, -0.5f, 0.0f, // bottom left }; GLuint VBO, VAO, VBO2, VAO2; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenVertexArrays(2, &VAO2); glGenBuffers(2, &VBO2); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO glBindVertexArray(VAO2); glBindBuffer(GL_ARRAY_BUFFER, VBO2); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); while(!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glBindVertexArray(VAO2); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO2); glDeleteBuffers(1, &VBO2); glfwTerminate(); return 0; }
bool ctx_init(struct context *ctx, int w, int h, bool debug) { assert(! ctx->win); glfwSetErrorCallback(error_callback); if (! glfwInit()) { return false; } GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); int mw, mh; glfwGetMonitorPhysicalSize(monitor, &mw, &mh); ctx->dpi = mode->width / (mw / 25.4); ctx->hidpi = ctx->dpi > 180.0; ctx->vidmode = mode; if (ctx->hidpi) { w *= 2; h *= 2; } glfwWindowHint(GLFW_RESIZABLE, true); glfwWindowHint(GLFW_SRGB_CAPABLE, true); // Require OpenGL 3.3 or later glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Only support new core functionality glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_SAMPLES, 16); if ((ctx->win = glfwCreateWindow(w, h, "px", NULL, NULL)) == NULL) { return false; } glfwMakeContextCurrent(ctx->win); glfwSetWindowUserPointer(ctx->win, ctx); glfwSetInputMode(ctx->win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwSetInputMode(ctx->win, GLFW_STICKY_KEYS, true); glfwSetKeyCallback(ctx->win, key_callback); glfwSetMouseButtonCallback(ctx->win, mouse_button_callback); glfwSetCursorPosCallback(ctx->win, cursor_pos_callback); glfwSetCursorEnterCallback(ctx->win, focus_callback); glfwSetFramebufferSizeCallback(ctx->win, framebuffer_size_callback); glfwSetWindowPosCallback(ctx->win, window_pos_callback); glfwSetCharCallback(ctx->win, char_callback); glfwSetWindowAspectRatio(ctx->win, w, h); glfwGetFramebufferSize(ctx->win, &ctx->winw, &ctx->winh); ctx_win_center(ctx); gl_init(ctx->winw, ctx->winh, debug); int vw = ctx->winw, /* Virtual screen */ vh = ctx->winh; if (ctx->hidpi) { vw /= 2; vh /= 2; /* We can't create odd-sized framebuffer textures, so we make * the screen framebuffer even in case the virtual screen isn't. */ if (vw % 2 != 0) vw ++; if (vh % 2 != 0) vh ++; } infof("ctx", "real screen size: %dx%d", ctx->winw, ctx->winh); infof("ctx", "virtual screen size: %dx%d", vw, vh); ctx->lastframe = 0; ctx->frametime = 0; ctx->transforms = NULL; ctx->ortho = mat4ortho(ctx->winw, ctx->winh); ctx->font = malloc(sizeof(*ctx->font)); ctx->screen = framebuffer_screen(vw, vh, NULL); ctx->width = ctx->hidpi ? ctx->winw / 2 : ctx->winw; ctx->height = ctx->hidpi ? ctx->winh / 2 : ctx->winh; ctx_update_cursor_pos(ctx); ctx_blend_alpha(ctx); ctx_save(ctx); glfwSetTime(0); infof("ctx", "dpi = %f", ctx->dpi); return true; }
GLWindow::GLWindow(const UknString& name, const RenderSettings& settings): mFrameBuffer(new GLFrameBuffer(false)), Window(name) { glfwSetErrorCallback(ErrorCallback); glfwInit(); switch(settings.color_fmt) { case EF_RGBA8: glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); break; default: // error break; } switch(settings.depth_stencil_fmt) { case EF_D16: glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_STENCIL_BITS, 0); mFrameBuffer->mIsDepthBuffered = true; mFrameBuffer->mDepthBits = 16; mFrameBuffer->mStencilBits = 0; break; case EF_D24S8: glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_STENCIL_BITS, 8); mFrameBuffer->mIsDepthBuffered = true; mFrameBuffer->mDepthBits = 24; mFrameBuffer->mStencilBits = 8; break; default: glfwWindowHint(GLFW_DEPTH_BITS, 0); glfwWindowHint(GLFW_STENCIL_BITS, 0); mFrameBuffer->mIsDepthBuffered = false; mFrameBuffer->mDepthBits = 0; mFrameBuffer->mStencilBits = 0; break; } if(settings.sample_quality > 0) { glfwWindowHint(GLFW_SAMPLES, settings.sample_quality); } glfwWindowHint(GLFW_RESIZABLE, settings.resizable); /* maybe there are bugs... let glfw decide the best version */ /* glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, UKN_OPENGL_VERSION_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, UKN_OPENGL_VERSION_MINOR); if(UKN_OPENGL_VERSION_MAJOR >= 3) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #if defined(MIST_OS_OSX) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); #endif } */ if(!settings.native_window_handle) { if((mGlfwWindow = glfwCreateWindow(settings.width, settings.height, string::WStringToString(name).c_str(), settings.full_screen ? glfwGetPrimaryMonitor() : 0, 0)) == 0) { MIST_THROW_EXCEPTION(L"GLWindow::GLWindow: Error opening window"); } } else { if((mGlfwWindow = glfwCreateWindowSlave((void*)settings.native_window_handle, 0)) == 0) { MIST_THROW_EXCEPTION(L"GLWindow::GLWindow: Error creating slave window on native handle"); } } glfwMakeContextCurrent(mGlfwWindow); #if !defined(UKN_OSX_REQUEST_OPENGL_32_CORE_PROFILE) GLenum err = glewInit(); if (GLEW_OK != err) { MIST_THROW_EXCEPTION(mist::string::StringToWString(format_string("GLWindow::GLWindow: error initializing glew profilem, error; %s", glewGetErrorString(err)))); } #endif // if wnd pos is (0, 0), then put it in the center of current screen int32 wndPosX = settings.left, wndPosY = settings.top; if(wndPosX == 0 && wndPosY == 0) { Array<SystemInformation::DesktopMode> desktop_modes = SystemInformation::EnumDesktopMode(); wndPosX = (desktop_modes[0].width - settings.width) / 2; wndPosY = (desktop_modes[0].height - settings.height) / 2; } glfwSetWindowPos(mGlfwWindow, wndPosX, wndPosY); glfwSetWindowUserPointer(mGlfwWindow, this); glfwSetErrorCallback(ErrorFunc); glfwSetWindowSizeCallback(mGlfwWindow, WindowSizeFunc); glfwSetWindowCloseCallback(mGlfwWindow, WindowCloseFunc); glfwSetWindowRefreshCallback(mGlfwWindow, WindowRefreshFunc); glfwSetWindowFocusCallback(mGlfwWindow, WindowFocusFunc); glfwSetWindowIconifyCallback(mGlfwWindow, WindowIconifyFunc); glfwSetKeyCallback(mGlfwWindow, KeyFunc); glfwSetCursorPosCallback(mGlfwWindow, MousePosFunc); glfwSetMouseButtonCallback(mGlfwWindow, MouseButtonFunc); glfwSetScrollCallback(mGlfwWindow, ScrollFunc); glfwSetCharCallback(mGlfwWindow, CharFunc); // to do with joysticks glfwSwapInterval(0); mFrameBuffer->attach(ATT_Color0, RenderViewPtr(new GLScreenColorRenderView(settings.width, settings.height, settings.color_fmt))); mFrameBuffer->attach(ATT_DepthStencil, RenderViewPtr(new GLScreenDepthStencilRenderView(settings.width, settings.height, settings.depth_stencil_fmt))); onResize() += Bind(this, &GLWindow::onWindowResize); updateWindowProperties(wndPosX, wndPosY, settings.width, settings.height); }
// Main entry point int main (int argc, char** argv) { std::string pathToThisFile=__FILE__; if(gDataPath.empty()) gDataPath=rt::Math::getParentDirectoryFromFilePath(pathToThisFile); std::cerr<<"Using data path: "<<gDataPath<<std::endl; std::cerr<<"Use your mouse to rotate,pan and zoom the camera"<<std::endl; std::cerr<<"left mouse button + drag -> rotate"<<std::endl; std::cerr<<"middle mouse button + drag -> pan"<<std::endl; std::cerr<<"scroll wheel up / down -> zoom in / out"<<std::endl; if( !glfwInit() ) { std::cerr<<"Failed to initialize GLFW\n"<<std::endl; return -1; } glfwSetErrorCallback(glfwErrorCallback); // Create the OpenGL window glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_SAMPLES, 4); //Those stop GLFW from initializing successfully? 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); // Open OpenGL fullscreen window gGLFWWindow = glfwCreateWindow(gWidth,gHeight,"GLFW OpenGL Window",nullptr,nullptr); //// Open OpenGL fullscreen window //if( !glfwOpenWindow( gWidth, gHeight, 0,0,0,0, 16,0, GLFW_WINDOW ) ) //{ // fprintf( stderr, "Failed to open GLFW window\n" ); // glfwTerminate(); // exit( EXIT_FAILURE ); //} if(!gGLFWWindow) { std::cerr<<"Failed to open GLFW window\n"<<std::endl; glfwTerminate(); return -1; } // Disable VSync (we want to get as high FPS as possible!) glfwMakeContextCurrent(gGLFWWindow); glfwSwapInterval( 1 ); // Setting this is necessary for core profile (tested with MSVC 2013 x64, Windows 7) glewExperimental = GL_TRUE; // GLEW wraps all OpenGL functions and extensions GLenum err = glewInit(); if(err != GLEW_OK) { std::cerr<<"Failed to initialize GLEW"<<std::endl; std::cerr<<(char*)glewGetErrorString(err)<<std::endl; glfwTerminate(); return -1; } glGetError(); //GLEW might cause an 'invalid enum' error, safely ignore it? // Print OpenGL context information to console ogl::printContextInformation(); // Perform our initialization (OpenGL states, shader, camera, geometry) if(!init()) return -1; // Set the appropriate callback functions // Window resize callback function glfwSetFramebufferSizeCallback(gGLFWWindow,resizeCB); glfwSetMouseButtonCallback(gGLFWWindow,mouseCB); glfwSetScrollCallback(gGLFWWindow,wheelCB); glfwSetCursorPosCallback(gGLFWWindow,motionCB); while( !glfwWindowShouldClose(gGLFWWindow) ) { // Get the current time (in milliseconds since program start) double t0 =glfwGetTime(); // Clear frame and depth buffers glClearColor(gBackgroundColor[0],gBackgroundColor[1],gBackgroundColor[2], 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw... displayCB(); // Hopefully there hasn't been any mistake? ogl::printOpenGLError(); // Swap the rendering target with the frame buffer shown on the monitor glfwSwapBuffers(gGLFWWindow); glfwPollEvents() ; // Compute rendering time in seconds by taking difference to current time double t1=glfwGetTime(); gLastFrameTime = float(t1-t0); } // Terminate OpenGL glfwTerminate(); return 0; }
OculusManager& OculusManager::getOculusManager() { static OculusManager* oculusManager = NULL; if (oculusManager == NULL) { oculusManager = new OculusManager(); if (!ovr_Initialize()) { fprintf(stderr, "Failed to initialize the Oculus SDK"); } //= *OculusManager::getHmd(); g_Hmd = ovrHmd_Create(0); if (!g_Hmd) { printf("No Oculus Rift device attached, using virtual version...\n"); g_Hmd = ovrHmd_CreateDebug(ovrHmd_DK2); } printf("initialized HMD: %s - %s\n", g_Hmd->Manufacturer, g_Hmd->ProductName); if (!glfwInit()) exit(EXIT_FAILURE); if (l_MultiSampling) glfwWindowHint(GLFW_SAMPLES, 4); else glfwWindowHint(GLFW_SAMPLES, 0); bool l_DirectMode = ((g_Hmd->HmdCaps & ovrHmdCap_ExtendDesktop) == 0); GLFWmonitor* l_Monitor; ovrSizei l_ClientSize; if (l_DirectMode) { printf("Running in \"Direct\" mode...\n"); l_Monitor = NULL; l_ClientSize.w = g_Hmd->Resolution.w / 2; // Something reasonable, smaller, but maintain aspect ratio... l_ClientSize.h = g_Hmd->Resolution.h / 2; // Something reasonable, smaller, but maintain aspect ratio... } else // Extended Desktop mode... { printf("Running in \"Extended Desktop\" mode...\n"); int l_Count; GLFWmonitor** l_Monitors = glfwGetMonitors(&l_Count); switch (l_Count) { case 0: printf("No monitors found, exiting...\n"); exit(EXIT_FAILURE); break; case 1: printf("Two monitors expected, found only one, using primary...\n"); l_Monitor = glfwGetPrimaryMonitor(); break; case 2: printf("Two monitors found, using second monitor...\n"); l_Monitor = l_Monitors[1]; break; default: printf("More than two monitors found, using second monitor...\n"); l_Monitor = l_Monitors[1]; } l_ClientSize.w = g_Hmd->Resolution.w; // 1920 for DK2... l_ClientSize.h = g_Hmd->Resolution.h; // 1080 for DK2... } l_Window = glfwCreateWindow(l_ClientSize.w, l_ClientSize.h, "GLFW Oculus Rift Test", l_Monitor, NULL); if (!l_Window) { glfwTerminate(); exit(EXIT_FAILURE); } #if defined(_WIN32) if (l_DirectMode) { ovrBool l_AttachResult = ovrHmd_AttachToWindow(g_Hmd, glfwGetWin32Window(l_Window), NULL, NULL); if (!l_AttachResult) { printf("Could not attach to window..."); exit(EXIT_FAILURE); } } #endif glfwMakeContextCurrent(l_Window); glewExperimental = GL_TRUE; GLenum l_GlewResult = glewInit(); if (l_GlewResult != GLEW_OK) { printf("glewInit() error.\n"); exit(EXIT_FAILURE); } int l_Major = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MAJOR); int l_Minor = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MINOR); int l_Profile = glfwGetWindowAttrib(l_Window, GLFW_OPENGL_PROFILE); printf("OpenGL: %d.%d ", l_Major, l_Minor); if (l_Major >= 3) // Profiles introduced in OpenGL 3.0... { if (l_Profile == GLFW_OPENGL_COMPAT_PROFILE) printf("GLFW_OPENGL_COMPAT_PROFILE\n"); else printf("GLFW_OPENGL_CORE_PROFILE\n"); } printf("Vendor: %s\n", (char*)glGetString(GL_VENDOR)); printf("Renderer: %s\n", (char*)glGetString(GL_RENDERER)); ovrSizei l_EyeTextureSizes[2]; l_EyeTextureSizes[ovrEye_Left] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Left, g_Hmd->MaxEyeFov[ovrEye_Left], 1.0f); l_EyeTextureSizes[ovrEye_Right] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Right, g_Hmd->MaxEyeFov[ovrEye_Right], 1.0f); // Combine for one texture for both eyes... g_RenderTargetSize.w = l_EyeTextureSizes[ovrEye_Left].w + l_EyeTextureSizes[ovrEye_Right].w; g_RenderTargetSize.h = (l_EyeTextureSizes[ovrEye_Left].h > l_EyeTextureSizes[ovrEye_Right].h ? l_EyeTextureSizes[ovrEye_Left].h : l_EyeTextureSizes[ovrEye_Right].h); // Create the FBO being a single one for both eyes (this is open for debate)... glGenFramebuffers(1, &l_FBOId); glBindFramebuffer(GL_FRAMEBUFFER, l_FBOId); // The texture we're going to render to... glGenTextures(1, &l_TextureId); // "Bind" the newly created texture : all future texture functions will modify this texture... glBindTexture(GL_TEXTURE_2D, l_TextureId); // Give an empty image to OpenGL (the last "0") glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_RenderTargetSize.w, g_RenderTargetSize.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); // Linear filtering... glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Create Depth Buffer... glGenRenderbuffers(1, &l_DepthBufferId); glBindRenderbuffer(GL_RENDERBUFFER, l_DepthBufferId); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, g_RenderTargetSize.w, g_RenderTargetSize.h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, l_DepthBufferId); // Set the texture as our colour attachment #0... glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, l_TextureId, 0); // Set the list of draw buffers... GLenum l_GLDrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, l_GLDrawBuffers); // "1" is the size of DrawBuffers // Check if everything is OK... GLenum l_Check = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (l_Check != GL_FRAMEBUFFER_COMPLETE) { printf("There is a problem with the FBO.\n"); exit(EXIT_FAILURE); } // Unbind... glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Setup textures for each eye... // Left eye... g_EyeTextures[ovrEye_Left].Header.API = ovrRenderAPI_OpenGL; g_EyeTextures[ovrEye_Left].Header.TextureSize = g_RenderTargetSize; g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.x = 0; g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.y = 0; g_EyeTextures[ovrEye_Left].Header.RenderViewport.Size = l_EyeTextureSizes[ovrEye_Left]; ((ovrGLTexture&)(g_EyeTextures[ovrEye_Left])).OGL.TexId = l_TextureId; // Right eye (mostly the same as left but with the viewport on the right side of the texture)... g_EyeTextures[ovrEye_Right] = g_EyeTextures[ovrEye_Left]; g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = (g_RenderTargetSize.w + 1) / 2; g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.y = 0; // Oculus Rift eye configurations... g_Cfg.OGL.Header.API = ovrRenderAPI_OpenGL; g_Cfg.OGL.Header.RTSize.w = l_ClientSize.w; g_Cfg.OGL.Header.RTSize.h = l_ClientSize.h; g_Cfg.OGL.Header.Multisample = (l_MultiSampling ? 1 : 0); #if defined(_WIN32) g_Cfg.OGL.Window = glfwGetWin32Window(l_Window); g_Cfg.OGL.DC = GetDC(g_Cfg.OGL.Window); #elif defined(__linux__) l_Cfg.OGL.Win = glfwGetX11Window(l_Window); l_Cfg.OGL.Disp = glfwGetX11Display(); #endif // Enable capabilities... // ovrHmd_SetEnabledCaps(g_Hmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); ovrBool l_ConfigureResult = ovrHmd_ConfigureRendering(g_Hmd, &g_Cfg.Config, g_DistortionCaps, g_Hmd->MaxEyeFov, g_EyeRenderDesc); glUseProgram(0); // Avoid OpenGL state leak in ovrHmd_ConfigureRendering... if (!l_ConfigureResult) { printf("Configure failed.\n"); exit(EXIT_FAILURE); } // Start the sensor which provides the Rift’s pose and motion... uint32_t l_SupportedSensorCaps = ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position; uint32_t l_RequiredTrackingCaps = 0; ovrBool l_TrackingResult = ovrHmd_ConfigureTracking(g_Hmd, l_SupportedSensorCaps, l_RequiredTrackingCaps); if (!l_TrackingResult) { printf("Could not start tracking..."); exit(EXIT_FAILURE); } // Projection matrici for each eye will not change at runtime, we can set them here... g_ProjectionMatrici[ovrEye_Left] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Left].Fov, 0.3f, 100.0f, true); g_ProjectionMatrici[ovrEye_Right] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Right].Fov, 0.3f, 100.0f, true); // IPD offset values will not change at runtime, we can set them here... g_EyeOffsets[ovrEye_Left] = g_EyeRenderDesc[ovrEye_Left].HmdToEyeViewOffset; g_EyeOffsets[ovrEye_Right] = g_EyeRenderDesc[ovrEye_Right].HmdToEyeViewOffset; ovrHmd_RecenterPose(g_Hmd); return *oculusManager; } }
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; }
int main(int argc, char ** argv) { // // Setup GLFW, glew and some initial GL state // static const char windowTitle[] = "CPU Subdivision Example"; if (not glfwInit()) { printf("Failed to initialize GLFW\n"); return 1; } #define CORE_PROFILE #ifdef CORE_PROFILE setGLCoreProfile(); #endif #if GLFW_VERSION_MAJOR>=3 if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) { printf("Failed to open window.\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(g_window); glfwSetWindowSizeCallback(g_window, reshape); glfwSetWindowCloseCallback(g_window, windowClose); #else if (glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) { printf("Failed to open window.\n"); glfwTerminate(); return 1; } glfwSetWindowTitle(windowTitle); glfwSetWindowSizeCallback(reshape); glfwSetWindowCloseCallback(windowClose); #endif #if defined(OSD_USES_GLEW) #ifdef CORE_PROFILE // this is the only way to initialize glew correctly under core profile context. glewExperimental = true; #endif if (GLenum r = glewInit() != GLEW_OK) { printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r)); exit(1); } #ifdef CORE_PROFILE // clear GL errors which was generated during glewInit() glGetError(); #endif #endif initOsd(); // // Start the main drawing loop // while (g_running) { idle(); display(); #if GLFW_VERSION_MAJOR>=3 glfwPollEvents(); glfwSwapBuffers(g_window); #else glfwSwapBuffers(); #endif glFinish(); } }
int main(void) { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); printf("monitor mode: %d, %d\n", mode->width, mode->height); // if DEBUG { // glfw.WindowHint(glfw.OpenGLDebugContext, gl.TRUE) // } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow *window = glfwCreateWindow(mode->width, mode->height, "Hialin", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSwapInterval(0); p_glBindFragDataLocation = (glBindFragDataLocation_t)glfwGetProcAddress("glBindFragDataLocation"); if (!p_glBindFragDataLocation) { printf("\n failed glBindFragDataLocation"); glfwTerminate(); exit(EXIT_FAILURE); } p_glGenVertexArrays = (glGenVertexArrays_t)glfwGetProcAddress("glGenVertexArrays"); if (!p_glGenVertexArrays) { printf("\n failed glGenVertexArrays"); glfwTerminate(); exit(EXIT_FAILURE); } p_glBindVertexArray = (glBindVertexArray_t)glfwGetProcAddress("glBindVertexArray"); if (!p_glBindVertexArray) { printf("\n failed glBindVertexArray"); glfwTerminate(); exit(EXIT_FAILURE); } GLuint vsh = glCreateShader(GL_VERTEX_SHADER); { glShaderSource(vsh, 1, &vertex_shader_text, NULL); glCompileShader(vsh); int result; glGetShaderiv(vsh, GL_COMPILE_STATUS, &result ); if (result == GL_FALSE) { int logLength; glGetShaderiv(vsh, GL_INFO_LOG_LENGTH, &logLength); char log[10*1024] = {0}; glGetShaderInfoLog(vsh, logLength, NULL, log); printf("\nvertex shader compile: %s", log); glfwTerminate(); exit(EXIT_FAILURE); } } glCheck(); GLuint fsh = glCreateShader(GL_FRAGMENT_SHADER); { glShaderSource(fsh, 1, &fragment_shader_text, NULL); glCompileShader(fsh); int result; glGetShaderiv(fsh, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { int logLength; glGetShaderiv(fsh, GL_INFO_LOG_LENGTH, &logLength); char log[10*1024] = {0}; glGetShaderInfoLog(fsh, logLength, NULL, log); printf("\nfragment shader compile: %s", log); glfwTerminate(); exit(EXIT_FAILURE); } } glCheck(); GLuint program = glCreateProgram(); { glAttachShader(program, vsh); glAttachShader(program, fsh); glLinkProgram(program); int result; glGetProgramiv(program, GL_LINK_STATUS, &result); if (result == GL_FALSE) { int logLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); char log[10*1024] = {0}; glGetProgramInfoLog(program, logLength, NULL, log); printf("\nprogram link: \n%s", log); glfwTerminate(); exit(EXIT_FAILURE); } } glCheck(); glUseProgram(program); glCheck(); GLint projectionU = glGetUniformLocation(program, "projection"); mat4x4 camera; vec3 eye = {3, 3, 3}, center = {0, 0, 0}, up = {0, 1, 0}; mat4x4_look_at(camera, eye, center, up); GLint cameraU = glGetUniformLocation(program, "camera"); glUniformMatrix4fv(cameraU, 1, GL_FALSE, (const float*)camera); glCheck(); mat4x4 model; mat4x4_identity(model); GLint modelU = glGetUniformLocation(program, "model"); glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model); glCheck(); GLint texU = glGetUniformLocation(program, "tex"); glUniform1i(texU, 0); p_glBindFragDataLocation(program, 0, "outputColor"); glCheck(); // Load the texture // char *texturePath = "./Resources/code.png" // GLuint texture = MakeTexture(0, texturePath); GLuint texture = MakeTexture(0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glCheck(); // Configure the vertex data GLuint vao; p_glGenVertexArrays(1, &vao); p_glBindVertexArray(vao); glCheck(); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); glCheck(); GLuint val = glGetAttribLocation(program, "vert"); glEnableVertexAttribArray(val); glVertexAttribPointer(val, 3, GL_FLOAT, GL_FALSE, 5*4, (const void *)(0*4)); glCheck(); GLuint valTC = glGetAttribLocation(program, "vertTexCoord"); glEnableVertexAttribArray(valTC); glVertexAttribPointer(valTC, 2, GL_FLOAT, GL_FALSE, 5*4, (const void *)(3*4)); glCheck(); // Configure global settings glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glClearColor(0.0, 0.0, 0.0, 1.0); glCheck(); long time0 = tick(); float angle = 0.01; int width = 0, height = 0; int i = 0; while (!glfwWindowShouldClose(window)) { int w, h; glfwGetFramebufferSize(window, &w, &h); if (w != width || h != height) { width = w; height = h; glViewport(0, 0, width, height); printf("buffer size: %d %d\n", w, h); } float ratio = width/(float)height; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mat4x4_rotate_Y(model, model, angle); mat4x4 projection; mat4x4_perspective(projection, 0.785, ratio, 0.1, 10.0); // 45 degrees == 0.785 radians glUniformMatrix4fv(projectionU, 1, GL_FALSE, (const float*)projection); glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model); for (int i = 0; i < 1*1000; i++) { glDrawArrays(GL_TRIANGLES, 0, 6*2*3); // 12 triangles } i++; if (i == 100) { printf("time for 100 frames: %ld\n", tick()-time0); } else if (i == 1000) { printf("time for 1000 frames: %ld\n", tick()-time0); break; } glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader zprogram // ------------------------------------ Shader ourShader("5.2.transform.vs", "5.2.transform.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { // positions // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glm::mat4 transform; // first container // --------------- transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f)); transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); // get their uniform location and set matrix (using glm::value_ptr) unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); // with the uniform matrix set, draw the first container glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // second transformation // --------------------- transform = glm::mat4(); // reset it to an identity matrix transform = glm::translate(transform, glm::vec3(-0.5f, 0.5f, 0.0f)); float scaleAmount = sin(glfwGetTime()); transform = glm::scale(transform, glm::vec3(scaleAmount, scaleAmount, scaleAmount)); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &transform[0][0]); // this time take the matrix value array's first element as its memory pointer value // now with the uniform matrix being replaced with new transformations, draw it again. glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
void main(int argc, char ** argv) { int argc_ = 1; char *argv_[1] = {(char *)"something"}; //glutInit(&argc_, argv_); // initialize the toolkit //GLuint glutwindow = glutCreateWindow("something"); // open the screen window if(!glfwInit()) { printf("glfwinit fail"); return ; } CheckGlErrors("glfwInit"); GLFWwindow *glfwwindow = glfwCreateWindow(screenWidth, screenHeight, "example", NULL, NULL); CheckGlErrors("glfwCreateWindow"); if(glfwwindow == NULL) { printf("glfwCreateWindow fail"); glfwTerminate(); return ; } glfwHideWindow(glfwwindow); CheckGlErrors("glfwHideWindow"); glfwMakeContextCurrent(glfwwindow); CheckGlErrors("glfwMakeContextCurrent"); #ifndef FBO glutDisplayFunc(renderFBO); // register the redraw function #endif GLenum err = glewInit(); if(GLEW_OK != err) { printf("glewInit Error: %s\n", glewGetErrorString(err)); getchar(); return ; } myInit(); glslProcess(); #ifdef FBO for(int i=1;i<3;++i) { char filename[30]; sprintf(filename, "%d.png", i+1); img = cv::imread(filename); if(img.empty()) return ; //cv::cvtColor(img, img, CV_BGR2RGB); renderFBO(); readBack(); //cv::cvtColor(img1, img1, CV_BGR2RGB); printf("output img, width is %d, height is %d, %d\n", img1.cols, img1.rows, img1.channels()); sprintf(filename, "D:\\%d.bmp", 20+i); cv::imwrite(filename, img1); } //getchar(); #else glutMainLoop(); // go into a perpetual loop #endif glDeleteFramebuffers(1, &fb); glDeleteTextures(2, texId); //glutDestroyWindow(glutwindow); glfwTerminate(); getchar(); }
static void test_modes(GLFWmonitor* monitor) { int i, count; GLFWwindow* window; const GLFWvidmode* modes = glfwGetVideoModes(monitor, &count); for (i = 0; i < count; i++) { const GLFWvidmode* mode = modes + i; GLFWvidmode current; glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); printf("Testing mode %u on monitor %s: %s\n", (unsigned int) i, glfwGetMonitorName(monitor), format_mode(mode)); window = glfwCreateWindow(mode->width, mode->height, "Video Mode Test", glfwGetPrimaryMonitor(), NULL); if (!window) { printf("Failed to enter mode %u: %s\n", (unsigned int) i, format_mode(mode)); continue; } glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); glfwSetTime(0.0); while (glfwGetTime() < 5.0) { glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); if (glfwWindowShouldClose(window)) { printf("User terminated program\n"); glfwTerminate(); exit(EXIT_SUCCESS); } } glGetIntegerv(GL_RED_BITS, ¤t.redBits); glGetIntegerv(GL_GREEN_BITS, ¤t.greenBits); glGetIntegerv(GL_BLUE_BITS, ¤t.blueBits); glfwGetWindowSize(window, ¤t.width, ¤t.height); if (current.redBits != mode->redBits || current.greenBits != mode->greenBits || current.blueBits != mode->blueBits) { printf("*** Color bit mismatch: (%i %i %i) instead of (%i %i %i)\n", current.redBits, current.greenBits, current.blueBits, mode->redBits, mode->greenBits, mode->blueBits); } if (current.width != mode->width || current.height != mode->height) { printf("*** Size mismatch: %ix%i instead of %ix%i\n", current.width, current.height, mode->width, mode->height); } printf("Closing window\n"); glfwDestroyWindow(window); window = NULL; glfwPollEvents(); } }
int main(int argc, char** argv) { Slot* slots; GLFWmonitor* monitor = NULL; int ch, i, width, height, count = 1; setlocale(LC_ALL, ""); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); printf("Library initialized\n"); glfwSetMonitorCallback(monitor_callback); while ((ch = getopt(argc, argv, "hfn:")) != -1) { switch (ch) { case 'h': usage(); exit(EXIT_SUCCESS); case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'n': count = (int) strtol(optarg, NULL, 10); break; default: usage(); exit(EXIT_FAILURE); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); width = mode->width; height = mode->height; } else { width = 640; height = 480; } if (!count) { fprintf(stderr, "Invalid user\n"); exit(EXIT_FAILURE); } slots = calloc(count, sizeof(Slot)); for (i = 0; i < count; i++) { char title[128]; slots[i].closeable = GLFW_TRUE; slots[i].number = i + 1; sprintf(title, "Event Linter (Window %i)", slots[i].number); if (monitor) { printf("Creating full screen window %i (%ix%i on %s)\n", slots[i].number, width, height, glfwGetMonitorName(monitor)); } else { printf("Creating windowed mode window %i (%ix%i)\n", slots[i].number, width, height); } slots[i].window = glfwCreateWindow(width, height, title, monitor, NULL); if (!slots[i].window) { free(slots); glfwTerminate(); exit(EXIT_FAILURE); } glfwSetWindowUserPointer(slots[i].window, slots + i); glfwSetWindowPosCallback(slots[i].window, window_pos_callback); glfwSetWindowSizeCallback(slots[i].window, window_size_callback); glfwSetFramebufferSizeCallback(slots[i].window, framebuffer_size_callback); glfwSetWindowCloseCallback(slots[i].window, window_close_callback); glfwSetWindowRefreshCallback(slots[i].window, window_refresh_callback); glfwSetWindowFocusCallback(slots[i].window, window_focus_callback); glfwSetWindowIconifyCallback(slots[i].window, window_iconify_callback); glfwSetMouseButtonCallback(slots[i].window, mouse_button_callback); glfwSetCursorPosCallback(slots[i].window, cursor_position_callback); glfwSetCursorEnterCallback(slots[i].window, cursor_enter_callback); glfwSetScrollCallback(slots[i].window, scroll_callback); glfwSetKeyCallback(slots[i].window, key_callback); glfwSetCharCallback(slots[i].window, char_callback); glfwSetCharModsCallback(slots[i].window, char_mods_callback); glfwSetDropCallback(slots[i].window, drop_callback); glfwMakeContextCurrent(slots[i].window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); } printf("Main loop starting\n"); for (;;) { for (i = 0; i < count; i++) { if (glfwWindowShouldClose(slots[i].window)) break; } if (i < count) break; glfwWaitEvents(); // Workaround for an issue with msvcrt and mintty fflush(stdout); } free(slots); glfwTerminate(); exit(EXIT_SUCCESS); }
int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint vao; GLuint vbo; GLuint colours_vbo; /* geometry to use. these are 3 xyz points (9 floats total) to make a triangle */ GLfloat points[] = { 0.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.00f, 0.8f, 0.0f, -0.5f, -0.2f, 0.0f, 0.5f, -0.2f, 0.0f }; GLfloat colours[] = { 1.0f, 1.0f, 0.0f, //yellow rgb(255,255,0) 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, //red rgb(255,0,0) 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; /* these are the strings of code for the shaders the vertex shader positions each vertex point */ const char* vertex_shader = "#version 400\n" "layout(location = 0) in vec3 vertex_position;" "layout(location = 1) in vec3 vertex_colour;" "out vec3 color;" "uniform mat4 matrix;" "void main () {" " color = vertex_colour;" " gl_Position=matrix * vec4(vertex_position, 1.0);" "}"; /* the fragment shader colours each fragment (pixel-sized area of the triangle) */ const char* fragment_shader = "#version 400\n" "in vec3 color;" "out vec4 frag_colour;" "void main () {" " frag_colour = vec4 (color, 1.0);" "}"; /* GL shader objects for vertex and fragment shader [components] */ GLuint vs, fs; /* GL shader programme object [combined, to link] */ GLuint shader_programme; /* start GL context and O/S window using the GLFW helper library */ if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X */ glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow ( 640, 480, "Hello Triangle", NULL, NULL ); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent (window); /* start GLEW extension handler */ glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); /* tell GL to only draw onto a pixel if the shape is closer to the viewer */ glEnable (GL_DEPTH_TEST); /* enable depth-testing */ glDepthFunc (GL_LESS);/*depth-testing interprets a smaller value as "closer"*/ /* a vertex buffer object (VBO) is created here. this stores an array of data on the graphics adapter's memory. in our case - the vertex points */ glGenBuffers (1, &vbo); glBindBuffer (GL_ARRAY_BUFFER, vbo); glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), points, GL_STATIC_DRAW); glGenBuffers (1, &colours_vbo); glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (colours), colours, GL_STATIC_DRAW); /* the vertex array object (VAO) is a little descriptor that defines which data from vertex buffer objects should be used as input variables to vertex shaders. in our case - use our only VBO, and say 'every three floats is a variable' */ glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); //enable glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL); /* here we copy the shader strings into GL shaders, and compile them. we then create an executable shader 'program' and attach both of the compiled shaders. we link this, which matches the outputs of the vertex shader to the inputs of the fragment shader, etc. and it is then ready to use */ vs = glCreateShader (GL_VERTEX_SHADER); glShaderSource (vs, 1, &vertex_shader, NULL); glCompileShader (vs); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (fs, 1, &fragment_shader, NULL); glCompileShader (fs); shader_programme = glCreateProgram (); glAttachShader (shader_programme, fs); glAttachShader (shader_programme, vs); glLinkProgram (shader_programme); double theta=180; GLfloat matrix[] = { 0.5f,0.0f,0.0f,0.00f, 0.0f,0.5f,0.0f,0.00f, 0.0f,0.0f,0.5f,0.00f, 0.25f,0.5f,0.75f,1.0f, }; int matrix_location = glGetUniformLocation (shader_programme, "matrix"); while (!glfwWindowShouldClose (window)) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram (shader_programme); glBindVertexArray (vao); glDrawArrays (GL_TRIANGLES, 0, 3); glDrawArrays (GL_TRIANGLES, 3, 6); // update other events like input handling glfwPollEvents (); if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (window, 1); } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_U)) { //return to normal matrix[0] += 0.015f; matrix[5] += 0.005f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_J)) { //return to normal matrix[0] -= 0.015f; matrix[5] -= 0.005f; } //uniformed scaling make smaller if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_D)) { //return to normal matrix[0] -= 0.005f; matrix[5] -= 0.005f; } //uniformed scaling bigger if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_E)) { //return to normal matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] += 0.005f; } //non-uniform scaling if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_X)) { //return to normal matrix[5] = cos(theta); matrix[6] = sin(theta); matrix[9] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Y axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Y)) { //return to normal matrix[0] = cos(theta); matrix[2] = sin(theta); matrix[8] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Z axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Z)) { //return to normal matrix[0] = cos(theta); matrix[1] = -sin(theta); matrix[4] = sin(theta); matrix[5] = cos(theta); theta+=0.025; } //combined transformations if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_C)) { matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] +=0.005f; matrix[12] += 0.025f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_V)) { matrix[0] -= 0.005f; matrix[5] -= 0.005f; matrix[10] -=0.005f; matrix[12] -= 0.025f; } // X left if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_LEFT)) { matrix[12] -= 0.025f; } //X Right if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_RIGHT)) { matrix[12] += 0.025f; } //Y Down if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_DOWN)) { matrix[13] -= 0.025f; } //Y UP if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_UP)) { matrix[13] += 0.025f; } glUniformMatrix4fv (matrix_location, 1, GL_FALSE, matrix); //control triangle seperately // draw points 0-3 from the currently bound VAO with current in-use shader // put the stuff we've been drawing onto the display glfwSwapBuffers (window); } /* close GL context and any other GLFW resources */ glfwTerminate(); return 0; }
int main() { glfw_context glfw_ctx; if (!glfw_ctx.ok) { fprintf(stderr, "failed to initialize GLFW context.\n"); return 1; } glfw_window_context glfw_window_ctx(screen_width, screen_height, "voronoi"); GLFWwindow* window = glfw_window_ctx.window; if (!window) { fprintf(stderr, "failed to create GLFW window.\n"); return 1; } glfwMakeContextCurrent(window); glfwSwapInterval(1); glewInit(); if (clewInit("OpenCL.dll") != CLEW_SUCCESS) { return 1; } const unsigned char* vendor = glGetString(GL_VENDOR); const unsigned char* version = glGetString(GL_VERSION); printf("opengl vendor=%s version=%s\n", vendor, version); corridormap::Memory_Malloc mem; float obstacle_verts_x[] = { 546.04233f, 586.87983f, 586.87983f, 546.04233f, 484.7861f, 443.9486f, 443.9486f, 484.7861f, 219.27517f, 299.49779f, 367.03349f, 286.81087f, 461.04229f, 567.87837f, 549.26637f, 442.43029f, 655.31886f, 757.95437f, 790.9898f, 688.35429f, 103.76307f, 307.49818f, 332.23693f, 128.50182f, 482.48372f, 665.65059f, 633.51629f, 450.34941f, 862.14993f, 778.93614f, 719.02164f, 802.23542f, 87.27517f, 167.49779f, 235.03349f, 154.81087f, 359.17335f, 439.50653f, 507.13531f, 426.80213f, 886.58172f, 791.09332f, 761.96796f, 792.52284f, 828.33099f, 845.80621f, 952.58172f, 857.09332f, 827.96796f, 858.52284f, 894.33099f, 911.80621f, 83.84732f, 221.04656f, 272.15267f, 134.95344f, 159.50583f, 175.66538f, 165.88157f, 130.15439f, 91.23934f, 75.07979f, 84.8636f, 120.59078f, }; float obstacle_verts_y[] = { 366.49453f, 413.80088f, 461.10723f, 508.41357f, 508.41357f, 461.10723f, 413.80088f, 366.49453f, 276.47356f, 203.07432f, 276.8883f, 350.28754f, 135.41626f, 155.64419f, 253.9456f, 233.71767f, 259.41453f, 223.51093f, 317.94733f, 353.85093f, 639.66596f, 563.66847f, 622.46545f, 698.46295f, 602.91856f, 720.10861f, 775.21285f, 658.02281f, 470.77478f, 673.8586f, 651.35665f, 448.27281f, 432.47356f, 359.07432f, 432.8883f, 506.28754f, 868.83723f, 823.54104f, 869.09317f, 914.38936f, 901.90592f, 949.29104f, 890.59889f, 802.29103f, 784.52161f, 819.73691f, 219.90592f, 267.29104f, 208.59889f, 120.29103f, 102.52161f, 137.73691f, 914.32913f, 745.62826f, 783.80228f, 952.5032f, 122.51486f, 161.9206f, 193.21563f, 216.39993f, 204.23386f, 164.82812f, 133.53309f, 110.34879f, }; int num_poly_verts[] = { 8, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 4, 8, }; corridormap::Footprint obstacles; obstacles.x = obstacle_verts_x; obstacles.y = obstacle_verts_y; obstacles.num_polys = sizeof(num_poly_verts)/sizeof(num_poly_verts[0]); obstacles.num_verts = sizeof(obstacle_verts_x)/sizeof(obstacle_verts_x[0]); obstacles.num_poly_verts = num_poly_verts; const float border = 10.f; corridormap::Bbox2 obstacle_bounds = corridormap::bounds(obstacles, border); const float max_dist = corridormap::max_distance(obstacle_bounds); const float max_error = 0.1f; corridormap::Distance_Mesh mesh = corridormap::allocate_distance_mesh(&mem, obstacles.num_polys, max_distance_mesh_verts(obstacles, max_dist, max_error)); corridormap::build_distance_mesh(obstacles, obstacle_bounds, max_dist, max_error, mesh); corridormap::set_segment_colors(mesh, colors, sizeof(colors)/sizeof(colors[0])); corridormap::Renderer_GL render_iface; corridormap::Renderer::Parameters render_params; render_params.render_target_width = render_target_width; render_params.render_target_height = render_target_height; render_params.min[0] = obstacle_bounds.min[0]; render_params.min[1] = obstacle_bounds.min[1]; render_params.max[0] = obstacle_bounds.max[0]; render_params.max[1] = obstacle_bounds.max[1]; render_params.far_plane = max_dist + 0.1f; if (!render_iface.initialize(render_params, &mem)) { fprintf(stderr, "failed to initialize render interface.\n"); return 1; } corridormap::render_distance_mesh(&render_iface, mesh); corridormap::Renderer::Opencl_Shared cl_shared = render_iface.create_opencl_shared(); corridormap::Opencl_Runtime cl_runtime = corridormap::init_opencl_runtime(cl_shared); // build kernels. { corridormap::Compilation_Status status = corridormap::build_kernels(cl_runtime); if (status.kernel != corridormap::kernel_id_count) { fprintf(stderr, "failed to build kernels: code=%d, kernel=%d\n", status.code, status.kernel); size_t build_log_size; clGetProgramBuildInfo(cl_runtime.programs[status.kernel], cl_runtime.device, CL_PROGRAM_BUILD_LOG, 0, 0, &build_log_size); char* build_log = corridormap::allocate<char>(&mem, build_log_size); clGetProgramBuildInfo(cl_runtime.programs[status.kernel], cl_runtime.device, CL_PROGRAM_BUILD_LOG, build_log_size, build_log, 0); fprintf(stderr, "build log: %s\n", build_log); return 1; } } { cl_int error_code; cl_mem voronoi_image = render_iface.share_pixels(cl_runtime.context, CL_MEM_READ_WRITE, &error_code); if (error_code != CL_SUCCESS) { fprintf(stderr, "failed to create opencl voronoi image.\n"); return 1; } render_iface.acquire_shared(cl_runtime.queue, voronoi_image); error_code = corridormap::mark_voronoi_features(cl_runtime, voronoi_image); error_code = corridormap::debug_voronoi_features(cl_runtime, voronoi_image, cl_runtime.voronoi_edges_img, 0xff000000, 0); error_code = corridormap::debug_voronoi_features(cl_runtime, voronoi_image, cl_runtime.voronoi_vertices_img, 0xffffffff, 4); error_code = corridormap::compact_voronoi_features(cl_runtime); error_code = corridormap::store_obstacle_ids(cl_runtime, voronoi_image); render_iface.release_shared(cl_runtime.queue, voronoi_image); clFinish(cl_runtime.queue); corridormap::Voronoi_Features features = corridormap::allocate_voronoi_features(&mem, render_target_width, render_target_height, cl_runtime.voronoi_vertex_mark_count, cl_runtime.voronoi_edge_mark_count); error_code = corridormap::transfer_voronoi_features(cl_runtime, features); clFinish(cl_runtime.queue); if (error_code != CL_SUCCESS) { fprintf(stderr, "failed to run opencl kernels.\n"); return 1; } printf("voronoi vertices: %d\n", cl_runtime.voronoi_vertex_mark_count); printf("voronoi edge marks: %d\n", cl_runtime.voronoi_edge_mark_count); } while (!glfwWindowShouldClose(window)) { int width, height; glfwGetFramebufferSize(window, &width, &height); render_iface.blit_frame_buffer(width, height); glfwSwapBuffers(window); glfwPollEvents(); } corridormap::deallocate(&mem, mesh); return 0; }
int main(int argc, char** argv) { if (!glewInit()) return EXIT_FAILURE; GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return EXIT_FAILURE; /* Create a windowed mode window and its OpenGL context */ glfwHints(); window = glfwCreateWindow( g_windowWidth, g_windowHeight, "Dunjun", nullptr, nullptr); if (!window) { glfwTerminate(); return EXIT_FAILURE; } /* Make the window's context current */ glfwMakeContextCurrent(window); glewInit(); float vertices[] = { +0.0f, +0.5f, //Vertex 1 -0.5f, -0.5f, //Vertex 2 +0.5f, -0.5f, //Vertex 3 }; GLuint vbo; // Vertex Buffer Object glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); const char* vertexShaderText = { "#version 120\n" "\n" "attribute vec2 position;" "void main()" "{" " gl_Position = vec4(position, 0.0, 1.0);" "}" }; const char* fragmentShaderText = { "#version 120\n" "\n" "void main()" "{" " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);" "}" }; GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderText, nullptr); glCompileShader(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderText, nullptr); glCompileShader(fragmentShader); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glBindAttribLocation(shaderProgram, 0, "position"); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); bool running = true; bool fullscreen = false; /* Loop until the user closes the window */ while (running) { /* Render here */ glClearColor(0.5f, 0.69f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); /* Draw Things*/ { glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); } /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); if (glfwWindowShouldClose(window) || glfwGetKey(window, GLFW_KEY_ESCAPE)) running = false; /*if (glfwGetKey(window, GLFW_KEY_F11)) { fullscreen = !fullscreen; GLFWwindow* newWindow; glfwHints(); if (fullscreen) { int count; const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count); newWindow = glfwCreateWindow(modes[count - 1].width, modes[count - 1].height, "Dunjun", glfwGetPrimaryMonitor(), window); } else { newWindow = glfwCreateWindow( g_windowWidth, g_windowHeight, "Dunjun", nullptr, window); } glfwDestroyWindow(window); window = newWindow; glfwMakeContextCurrent(window); }*/ } glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; }
void GUI::Main() { // Setup window glfwSetErrorCallback(error_callback); if (!glfwInit()) { //return 1; } Window = glfwCreateWindow(1280, 720, "ImGui OpenGL2 example", NULL, NULL); glfwMakeContextCurrent(Window); // Setup ImGui binding ImGui_ImplGlfw_Init(Window, true); bool show_test_window = true; bool show_another_window = false; ImVec4 clear_color = ImColor(114, 144, 154); // Main loop while (!glfwWindowShouldClose(Window)) { glfwPollEvents(); ImGui_ImplGlfw_NewFrame(); // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } // 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); } }
void WindowGL33::makeCurrent() { glfwMakeContextCurrent(m_pWndHandle); }
int main(int argc, char** argv) { int ch, width, height; thrd_t physics_thread = 0; GLFWwindow* window; GLFWmonitor* monitor = NULL; if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(EXIT_FAILURE); } while ((ch = getopt(argc, argv, "fh")) != -1) { switch (ch) { case 'f': monitor = glfwGetPrimaryMonitor(); break; case 'h': usage(); exit(EXIT_SUCCESS); } } if (monitor) { const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); width = mode->width; height = mode->height; } else { width = 640; height = 480; } window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL); if (!window) { fprintf(stderr, "Failed to create GLFW window\n"); glfwTerminate(); exit(EXIT_FAILURE); } if (monitor) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); glfwSetFramebufferSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); // Set initial aspect ratio glfwGetFramebufferSize(window, &width, &height); resize_callback(window, width, height); // Upload particle texture glGenTextures(1, &particle_tex_id); glBindTexture(GL_TEXTURE_2D, particle_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture); // Upload floor texture glGenTextures(1, &floor_tex_id); glBindTexture(GL_TEXTURE_2D, floor_tex_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture); if (glfwExtensionSupported("GL_EXT_separate_specular_color")) { glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT); } // Set filled polygon mode as default (not wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); wireframe = 0; // Set initial times thread_sync.t = 0.0; thread_sync.dt = 0.001f; thread_sync.p_frame = 0; thread_sync.d_frame = 0; mtx_init(&thread_sync.particles_lock, mtx_timed); cnd_init(&thread_sync.p_done); cnd_init(&thread_sync.d_done); if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetTime(0.0); while (!glfwWindowShouldClose(window)) { draw_scene(window, glfwGetTime()); glfwSwapBuffers(window); glfwPollEvents(); } thrd_join(physics_thread, NULL); glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
void AnalyzeSequence_GLSL(std::shared_ptr<DatasetUtils::Segm::Video::Sequence> pCurrSequence) { srand(0); // for now, assures that two consecutive runs on the same data return the same results //srand((unsigned int)time(NULL)); size_t nCurrFrameIdx = 0; size_t nNextFrameIdx = nCurrFrameIdx+1; bool bGPUContextInitialized = false; try { glfwSetErrorCallback(GLFWErrorCallback); CV_Assert(pCurrSequence.get() && pCurrSequence->GetTotalImageCount()>1); if(pCurrSequence->m_pEvaluator==nullptr && EVALUATE_OUTPUT) throw std::runtime_error(cv::format("Missing evaluation impl for video segmentation dataset '%s'",g_pDatasetInfo->m_sDatasetName.c_str())); const std::string sCurrSeqName = pCurrSequence->m_sName.size()>12?pCurrSequence->m_sName.substr(0,12):pCurrSequence->m_sName; const size_t nFrameCount = pCurrSequence->GetTotalImageCount(); const cv::Mat oROI = LIMIT_MODEL_TO_SEQUENCE_ROI?pCurrSequence->GetROI():cv::Mat(); cv::Mat oCurrInputFrame = pCurrSequence->GetInputFromIndex(nCurrFrameIdx).clone(); CV_Assert(!oCurrInputFrame.empty()); CV_Assert(oCurrInputFrame.isContinuous()); #if NEED_GT_MASK cv::Mat oCurrGTMask = pCurrSequence->GetGTFromIndex(nCurrFrameIdx).clone(); CV_Assert(!oCurrGTMask.empty() && oCurrGTMask.isContinuous()); #endif //NEED_GT_MASK #if DISPLAY_OUTPUT cv::Mat oLastInputFrame = oCurrInputFrame.clone(); #endif //DISPLAY_OUTPUT cv::Mat oNextInputFrame = pCurrSequence->GetInputFromIndex(nNextFrameIdx); #if NEED_GT_MASK #if NEED_LAST_GT_MASK cv::Mat oLastGTMask = oCurrGTMask.clone(); #endif // NEED_LAST_GT_MASK cv::Mat oNextGTMask = pCurrSequence->GetGTFromIndex(nNextFrameIdx); #endif //NEED_GT_MASK #if NEED_FG_MASK cv::Mat oLastFGMask(oCurrInputFrame.size(),CV_8UC1,cv::Scalar_<uchar>(0)); #endif //NEED_FG_MASK #if DISPLAY_OUTPUT cv::Mat oLastBGImg; #endif //DISPLAY_OUTPUT glAssert(oCurrInputFrame.channels()==1 || oCurrInputFrame.channels()==4); cv::Size oWindowSize = oCurrInputFrame.size(); // note: never construct GL classes before context initialization if(glfwInit()==GL_FALSE) glError("Failed to init GLFW"); bGPUContextInitialized = true; glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,TARGET_GL_VER_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,TARGET_GL_VER_MINOR); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); #if !DISPLAY_OUTPUT glfwWindowHint(GLFW_VISIBLE,GL_FALSE); #endif //!DISPLAY_OUTPUT std::unique_ptr<GLFWwindow,void(*)(GLFWwindow*)> pWindow(glfwCreateWindow(oWindowSize.width,oWindowSize.height,(pCurrSequence->m_sRelativePath+" [GPU]").c_str(),nullptr,nullptr),glfwDestroyWindow); if(!pWindow) glError("Failed to create window via GLFW"); glfwMakeContextCurrent(pWindow.get()); glewInitErrorCheck; #if USE_LOBSTER std::shared_ptr<BackgroundSubtractorLOBSTER_GLSL> pAlgo(new BackgroundSubtractorLOBSTER_GLSL()); const double dDefaultLearningRate = BGSLOBSTER_DEFAULT_LEARNING_RATE; pAlgo->initialize(oCurrInputFrame,oROI); #elif USE_SUBSENSE #error "Missing glsl impl." // ... @@@@@ std::shared_ptr<BackgroundSubtractorSuBSENSE_GLSL> pAlgo(new BackgroundSubtractorSuBSENSE_GLSL()); const double dDefaultLearningRate = 0; pAlgo->initialize(oCurrInputFrame,oROI); #elif USE_PAWCS #error "Missing glsl impl." // ... @@@@@ std::shared_ptr<BackgroundSubtractorPAWCS_GLSL> pAlgo(new BackgroundSubtractorPAWCS_GLSL()); const double dDefaultLearningRate = 0; pAlgo->initialize(oCurrInputFrame,oROI); #else //USE_VIBE || USE_PBAS #error "Missing glsl impl." // ... @@@@@ const size_t m_nInputChannels = (size_t)oCurrInputFrame.channels(); #if USE_VIBE std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL> pAlgo; if(m_nInputChannels==3) pAlgo = std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL>(new BackgroundSubtractorViBe_GLSL_3ch()); else pAlgo = std::shared_ptr<cv::BackgroundSubtractorViBe_GLSL>(new BackgroundSubtractorViBe_GLSL_1ch()); const double dDefaultLearningRate = BGSVIBE_DEFAULT_LEARNING_RATE; #else //USE_PBAS std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL> pAlgo; if(m_nInputChannels==3) pAlgo = std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL>(new BackgroundSubtractorPBAS_GLSL_3ch()); else pAlgo = std::shared_ptr<cv::BackgroundSubtractorPBAS_GLSL>(new BackgroundSubtractorPBAS_GLSL_1ch()); const double dDefaultLearningRate = BGSPBAS_DEFAULT_LEARNING_RATE_OVERRIDE; #endif //USE_PBAS pAlgo->initialize(oCurrInputFrame); #endif //USE_VIBE || USE_PBAS #if DISPLAY_OUTPUT bool bContinuousUpdates = false; std::string sDisplayName = pCurrSequence->m_sRelativePath; cv::namedWindow(sDisplayName); #endif //DISPLAY_OUTPUT #if (WRITE_IMG_OUTPUT || WRITE_AVI_OUTPUT) #if WRITE_AVI_OUTPUT cv::VideoWriter oSegmWriter(pCurrSequence->m_sResultsPath+"../"+pCurrSequence->m_sName+"_segm.avi",CV_FOURCC('F','F','V','1'),30,pCurrSequence->GetImageSize(),false); #endif //WRITE_AVI_OUTPUT #endif //(WRITE_IMG_OUTPUT || WRITE_AVI_OUTPUT) std::shared_ptr<GLImageProcAlgo> pGLSLAlgo = std::dynamic_pointer_cast<GLImageProcAlgo>(pAlgo); if(pGLSLAlgo==nullptr) glError("Segmentation algorithm has no GLImageProcAlgo interface"); pGLSLAlgo->setOutputFetching(NEED_FG_MASK); if(!pGLSLAlgo->getIsUsingDisplay() && DISPLAY_OUTPUT) // @@@@ determine in advance to hint window to hide? or just always hide, and show when needed? glfwHideWindow(pWindow.get()); #if USE_GLSL_EVALUATION std::shared_ptr<DatasetUtils::EvaluatorBase::GLEvaluatorBase> pGLSLAlgoEvaluator; if(pCurrSequence->m_pEvaluator!=nullptr) pGLSLAlgoEvaluator = std::dynamic_pointer_cast<DatasetUtils::EvaluatorBase::GLEvaluatorBase>(pCurrSequence->m_pEvaluator->CreateGLEvaluator(pGLSLAlgo,nFrameCount)); if(pGLSLAlgoEvaluator==nullptr) glError("Segmentation evaluation algorithm has no GLSegmEvaluator interface"); pGLSLAlgoEvaluator->initialize(oCurrGTMask,oROI.empty()?cv::Mat(oCurrInputFrame.size(),CV_8UC1,cv::Scalar_<uchar>(255)):oROI); oWindowSize.width *= pGLSLAlgoEvaluator->m_nSxSDisplayCount; #else //!USE_GLSL_EVALUATION oWindowSize.width *= pGLSLAlgo->m_nSxSDisplayCount; #endif //!USE_GLSL_EVALUATION glfwSetWindowSize(pWindow.get(),oWindowSize.width,oWindowSize.height); glViewport(0,0,oWindowSize.width,oWindowSize.height); TIMER_TIC(MainLoop); while(nNextFrameIdx<=nFrameCount) { if(!((nCurrFrameIdx+1)%100)) std::cout << "\t\t" << std::setfill(' ') << std::setw(12) << sCurrSeqName << " @ F:" << std::setfill('0') << std::setw(PlatformUtils::decimal_integer_digit_count((int)nFrameCount)) << nCurrFrameIdx+1 << "/" << nFrameCount << " [GPU]" << std::endl; const double dCurrLearningRate = (BOOTSTRAP_100_FIRST_FRAMES&&nCurrFrameIdx<=100)?1:dDefaultLearningRate; TIMER_INTERNAL_TIC(OverallLoop); TIMER_INTERNAL_TIC(PipelineUpdate); pAlgo->apply_async(oNextInputFrame,dCurrLearningRate); TIMER_INTERNAL_TOC(PipelineUpdate); #if USE_GLSL_EVALUATION pGLSLAlgoEvaluator->apply_async(oNextGTMask); #endif //USE_GLSL_EVALUATION TIMER_INTERNAL_TIC(VideoQuery); #if DISPLAY_OUTPUT oCurrInputFrame.copyTo(oLastInputFrame); oNextInputFrame.copyTo(oCurrInputFrame); #endif //DISPLAY_OUTPUT if(++nNextFrameIdx<nFrameCount) oNextInputFrame = pCurrSequence->GetInputFromIndex(nNextFrameIdx); #if DEBUG_OUTPUT cv::imshow(sMouseDebugDisplayName,oNextInputFrame); #endif //DEBUG_OUTPUT #if NEED_GT_MASK #if NEED_LAST_GT_MASK oCurrGTMask.copyTo(oLastGTMask); oNextGTMask.copyTo(oCurrGTMask); #endif //NEED_LAST_GT_MASK if(nNextFrameIdx<nFrameCount) oNextGTMask = pCurrSequence->GetGTFromIndex(nNextFrameIdx); #endif //NEED_GT_MASK TIMER_INTERNAL_TOC(VideoQuery); glErrorCheck; if(glfwWindowShouldClose(pWindow.get())) break; glfwPollEvents(); #if DISPLAY_OUTPUT if(glfwGetKey(pWindow.get(),GLFW_KEY_ESCAPE) || glfwGetKey(pWindow.get(),GLFW_KEY_Q)) break; glfwSwapBuffers(pWindow.get()); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); #endif //DISPLAY_OUTPUT #if NEED_FG_MASK pAlgo->getLatestForegroundMask(oLastFGMask); if(!oROI.empty()) cv::bitwise_or(oLastFGMask,UCHAR_MAX/2,oLastFGMask,oROI==0); #endif //NEED_FG_MASK #if DISPLAY_OUTPUT pAlgo->getBackgroundImage(oLastBGImg); if(!oROI.empty()) cv::bitwise_or(oLastBGImg,UCHAR_MAX/2,oLastBGImg,oROI==0); cv::Mat oDisplayFrame = DatasetUtils::GetDisplayImage(oLastInputFrame,oLastBGImg,pCurrSequence->m_pEvaluator?pCurrSequence->m_pEvaluator->GetColoredSegmMaskFromResult(oLastFGMask,oLastGTMask,oROI):oLastFGMask,nCurrFrameIdx); cv::Mat oDisplayFrameResized; if(oDisplayImage.cols>1920 || oDisplayImage.rows>1080) cv::resize(oDisplayFrame,oDisplayFrameResized,cv::Size(oDisplayFrame.cols/2,oDisplayFrame.rows/2)); else oDisplayFrameResized = oDisplayFrame; cv::imshow(sDisplayName,oDisplayFrameResized); int nKeyPressed; if(bContinuousUpdates) nKeyPressed = cv::waitKey(1); else nKeyPressed = cv::waitKey(0); if(nKeyPressed!=-1) nKeyPressed %= (UCHAR_MAX+1); // fixes return val bug in some opencv versions if(nKeyPressed==' ') bContinuousUpdates = !bContinuousUpdates; else if(nKeyPressed==(int)'q') break; #endif //DISPLAY_OUTPUT #if WRITE_AVI_OUTPUT oSegmWriter.write(oLastFGMask); #endif //WRITE_AVI_OUTPUT #if WRITE_IMG_OUTPUT pCurrSequence->WriteResult(nCurrFrameIdx,oLastFGMask); #endif //WRITE_IMG_OUTPUT #if (EVALUATE_OUTPUT && (!USE_GLSL_EVALUATION || VALIDATE_GPU_EVALUATION)) if(pCurrSequence->m_pEvaluator) pCurrSequence->m_pEvaluator->AccumulateMetricsFromResult(oCurrFGMask,oCurrGTMask,oROI); #endif //(EVALUATE_OUTPUT && (!USE_GLSL_EVALUATION || VALIDATE_GPU_EVALUATION)) TIMER_INTERNAL_TOC(OverallLoop); #if DISPLAY_TIMERS std::cout << "VideoQuery=" << TIMER_INTERNAL_ELAPSED_MS(VideoQuery) << "ms, " << "PipelineUpdate=" << TIMER_INTERNAL_ELAPSED_MS(PipelineUpdate) << "ms, " << "OverallLoop=" << TIMER_INTERNAL_ELAPSED_MS(OverallLoop) << "ms" << std::endl; #endif //ENABLE_INTERNAL_TIMERS ++nCurrFrameIdx; } TIMER_TOC(MainLoop); const double dTimeElapsed = TIMER_ELAPSED_MS(MainLoop)/1000; const double dAvgFPS = (double)nCurrFrameIdx/dTimeElapsed; std::cout << "\t\t" << std::setfill(' ') << std::setw(12) << sCurrSeqName << " @ end, " << int(dTimeElapsed) << " sec in-thread (" << (int)floor(dAvgFPS+0.5) << " FPS)" << std::endl; #if EVALUATE_OUTPUT if(pCurrSequence->m_pEvaluator) { #if USE_GLSL_EVALUATION #if VALIDATE_GPU_EVALUATION printf("cpu eval:\n\tnTP=%" PRIu64 ", nTN=%" PRIu64 ", nFP=%" PRIu64 ", nFN=%" PRIu64 ", nSE=%" PRIu64 ", tot=%" PRIu64 "\n",pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nSE,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN); #endif //VALIDATE_USE_GLSL_EVALUATION pCurrSequence->m_pEvaluator->FetchGLEvaluationResults(pGLSLAlgoEvaluator); #if VALIDATE_GPU_EVALUATION printf("gpu eval:\n\tnTP=%" PRIu64 ", nTN=%" PRIu64 ", nFP=%" PRIu64 ", nFN=%" PRIu64 ", nSE=%" PRIu64 ", tot=%" PRIu64 "\n",pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nSE,pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nTN+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFP+pCurrSequence->m_pEvaluator->m_oBasicMetrics.nFN); #endif //VALIDATE_USE_GLSL_EVALUATION #endif //USE_GLSL_EVALUATION pCurrSequence->m_pEvaluator->dTimeElapsed_sec = dTimeElapsed; } #endif //EVALUATE_OUTPUT #if DISPLAY_OUTPUT cv::destroyWindow(sDisplayName); #endif //DISPLAY_OUTPUT } catch(const CxxUtils::Exception& e) { std::cout << "\nAnalyzeSequence caught Exception:\n" << e.what(); if(!g_sLatestGLFWErrorMessage.empty()) { std::cout << " (" << g_sLatestGLFWErrorMessage << ")" << "\n" << std::endl; g_sLatestGLFWErrorMessage = std::string(); } else std::cout << "\n" << std::endl; } catch(const cv::Exception& e) { std::cout << "\nAnalyzeSequence caught cv::Exception:\n" << e.what() << "\n" << std::endl; } catch(const std::exception& e) { std::cout << "\nAnalyzeSequence caught std::exception:\n" << e.what() << "\n" << std::endl; } catch(...) { std::cout << "\nAnalyzeSequence caught unhandled exception\n" << std::endl; } if(bGPUContextInitialized) glfwTerminate(); if(pCurrSequence.get()) { #if DATASET_PRECACHING pCurrSequence->StopPrecaching(); #endif //DATASET_PRECACHING pCurrSequence->m_nImagesProcessed.set_value(nCurrFrameIdx); } }
//-------------------------------------------------------------------------- bool Run( int argc, char* argv[], const glm::ivec2 & size, int major, int minor) { glfwSetErrorCallback(error); // GLFW initialization if (!glfwInit()) exit(-1); glfwSetErrorCallback(error); // Configure the window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_VISIBLE, GL_TRUE); glfwWindowHint(GLFW_DECORATED, GL_TRUE); glfwWindowHint(GLFW_FOCUSED, GL_TRUE); glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 32); glfwWindowHint(GLFW_SAMPLES, 0); // (no msaa) glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(size.x, size.y, "PBC", nullptr, nullptr); if (!window) { glfwTerminate(); glf::Error("Window creation failed"); exit(-1); } glfwSetWindowPos(window, 64, 64); glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetKeyCallback(window, keyboard); glfwSetWindowSizeCallback(window, reshape); glfwSetCursorPosCallback(window, motion); glfwSetMouseButtonCallback(window, mouse); glfwSetScrollCallback(window, wheel); glGetError(); glf::init(); ctx::ui = new glui::GlfwContext(); ctx::ui->Initialize(size.x, size.y); KeyboardAdapter::window = window; // Render loop double previousInSecond = glfwGetTime(); bool validRun = false; glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); if (begin()) { validRun = true; while (!glfwWindowShouldClose(window)) { double currentInSecond = glfwGetTime(); double dt = currentInSecond - previousInSecond; // Camera keyboard input are handled by pooling event rather than callback in order to have smoother response ctx::camera->KeyboardEvent((float)dt, KeyboardAdapter::evaluator); display(); glfwSwapBuffers(window); glGetError(); // 'glutSwapBuffers' generates an here with OpenGL 3 > core profile ... :/ glfwPollEvents(); previousInSecond = currentInSecond; } end(); } glfwDestroyWindow(window); delete ctx::ui; return validRun; }
int main(int argc, char** argv){ cl_int err; // START OPENGL INIT Magick::InitializeMagick(argv[0]); // start GL context and O/S window using the GLFW helper library if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } // Demand OpenGL 4.1 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); #ifdef __APPLE__ // Use Core profile to obtain a context for the latest OpenGL spec. // Otherwise we're stuck at 2.1 std::cout<<"Apple FTW\n"; glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif window = glfwCreateWindow (WIDTH, HEIGHT, "Hello Triangle", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwSetWindowSize( window, WIDTH/2 , HEIGHT/2); //glfwWindowHint(GLFW_SAMPLES, 4); //glEnable( GL_MULTISAMPLE ); glfwMakeContextCurrent (window); checkGLErr( "glfwMakeContextCurrent" ); // start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); glGetError(); //checkGLErr( "GLEW init" ); // END OPENGL INIT.. // START OPENCL.. std::vector<cl::Platform> platformList; cl::Platform::get(&platformList); checkErr(platformList.size()!=0 ? CL_SUCCESS : -1, "cl::Platform::get"); std::cerr << "Platform number is: " << platformList.size() << std::endl; std::string platformVendor; platformList[0].getInfo((cl_platform_info)CL_PLATFORM_VENDOR, &platformVendor); std::cerr << "Platform is by: " << platformVendor << "\n"; #ifdef __APPLE__ CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties cprops[6] = {CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(),CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE , (cl_context_properties) kCGLShareGroup, 0, 0}; cl::Context context( CL_DEVICE_TYPE_CPU, cprops, NULL, NULL, &err); #endif #ifdef __linux__ cl_platform_id platform; err = clGetPlatformIDs(1, &platform, NULL); cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)glfwGetGLXContext( window ), CL_GLX_DISPLAY_KHR, (cl_context_properties)glfwGetX11Display(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 }; cl::Context context( CL_DEVICE_TYPE_CPU, props, NULL, NULL, &err); //cl::Context context = clCreateContextFromType(props, CL_DEVICE_TYPE_CPU, NULL, NULL, &err); #endif checkErr(err, "Context::Context()"); std::cout<<"Created context."<< std::endl; // Create shared texture. pCLTarget = new RenderTarget( WIDTH, HEIGHT, GL_RGBA , GL_RGBA, GL_FLOAT, 0, false ); checkGLErr( "RenderTarget::RenderTarget" ); pAccumulator = new RenderTarget( WIDTH, HEIGHT, GL_RGBA, GL_RGBA, GL_FLOAT, 0, false ); checkGLErr( "RenderTarget::RenderTarget" ); const int inSizeS = 3; const int inSizeP = 0; const int inSizeT = 12; const int inSurf = 5; /* float* outH = new float[inSize]; cl::Buffer outCL( context, CL_MEM_WRITE_ONLY, inSize * sizeof( float ) ); */ Sphere* spheres = new Sphere[inSizeS]; std::cout<<"Sphere: "<< spheres[0].radius << "\n"; spheres[1].uSurf = 0; spheres[1].center = glm::vec4( 0.0f, -2.0f, 0.0f, 0.0f ); spheres[1].radius = 1.0f; /*spheres[1].uSurf = 0; spheres[1].center = glm::vec4( +1.0f, 0.0f, +1.0f, 0.0f); spheres[1].radius = 1.0f;*/ spheres[0].uSurf = 2; spheres[0].center = glm::vec4( 0.0f, +1.50f, 0.0f, 0.0f); spheres[0].radius = 0.2f; /*spheres[2].uSurf = 0; spheres[2].center = glm::vec4( +0.0f, 0.0f, -0.0f, 0.0f); spheres[2].radius = 1.0f;*/ spheres[2].uSurf = 0; spheres[2].center = glm::vec4( -2.0f, -2.0f, -2.0f, 0.0f); spheres[2].radius = 1.0f; /*spheres[4].uSurf = 0; spheres[4].center = glm::vec4( -1.0f, -0.0f, +1.0f, 0.0f); spheres[4].radius = 1.0f;*/ Plane* planes = new Plane[inSizeP]; int planeSize = 3.0f; //std::cout<<"Sphere: "<< planes[0].radius << "\n"; /*planes[0].normal = glm::vec4( 0.0f, 1.0f, 0.0f, 0.0f ); planes[0].point = glm::vec4( 0.0f, -planeSize, 0.0f, 0.0f ); planes[0].uSurf = 1; planes[1].normal = glm::vec4( 0.0f, -1.0f, 0.0f, 0.0f ); planes[1].point = glm::vec4( 0.0f, planeSize, 0.0f, 0.0f ); planes[1].uSurf = 1; planes[2].normal = glm::vec4( 1.0f, 0.0f, 0.0f, 0.0f ); planes[2].point = glm::vec4( -planeSize, 0.0f, 0.0f, 0.0f ); planes[2].uSurf = 1; planes[3].normal = glm::vec4( -1.0f, 0.0f, 0.0f, 0.0f ); planes[3].point = glm::vec4( planeSize, 0.0f, 0.0f, 0.0f ); planes[3].uSurf = 1; planes[4].normal = glm::vec4( 0.0f, 0.0f, +1.0f, +0.0f ); planes[4].point = glm::vec4( 0.0f, 0.0f, -planeSize, 0.0f ); planes[4].uSurf = 1; planes[5].normal = glm::vec4( 0.0f, 0.0f, -1.0f, 0.0f ); planes[5].point = glm::vec4( 0.0f, 0.0f, +planeSize, 0.0f ); planes[5].uSurf = 1;*/ Triangle* triangles = new Triangle[inSizeT]; //std::cout<<"Sphere: "<< spheres[0].radius << "\n"; float boxSize = 3.0f; triangles[0].uSurf = 1; triangles[0].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[0].p1 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[0].p2 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[1].uSurf = 1; triangles[1].p0 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[1].p2 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[1].p1 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[2].uSurf = 1; triangles[2].p0 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[2].p2 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[2].p1 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[3].uSurf = 1; triangles[3].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[3].p1 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[3].p2 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[4].uSurf = 1; triangles[4].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[4].p2 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[4].p1 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[5].uSurf = 1; triangles[5].p0 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[5].p1 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[5].p2 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[6].uSurf = 1; triangles[6].p0 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[6].p1 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[6].p2 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[7].uSurf = 1; triangles[7].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[7].p2 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[7].p1 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[8].uSurf = 3; triangles[8].p0 = glm::vec4( -boxSize, -boxSize, -boxSize, 0.0f); triangles[8].p1 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[8].p2 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[9].uSurf = 3; triangles[9].p0 = glm::vec4( boxSize, boxSize, -boxSize, 0.0f); triangles[9].p2 = glm::vec4( boxSize, -boxSize, -boxSize, 0.0f); triangles[9].p1 = glm::vec4( -boxSize, boxSize, -boxSize, 0.0f); triangles[10].uSurf = 4; triangles[10].p0 = glm::vec4( -boxSize, -boxSize, boxSize, 0.0f); triangles[10].p2 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[10].p1 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); triangles[11].uSurf = 4; triangles[11].p0 = glm::vec4( boxSize, boxSize, boxSize, 0.0f); triangles[11].p1 = glm::vec4( boxSize, -boxSize, boxSize, 0.0f); triangles[11].p2 = glm::vec4( -boxSize, boxSize, boxSize, 0.0f); /*triangles[12].uSurf = 1; triangles[12].p0 = glm::vec4( -boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[12].p1 = glm::vec4( boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[12].p2 = glm::vec4( -boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f); triangles[13].uSurf = 1; triangles[13].p0 = glm::vec4( boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f); triangles[13].p2 = glm::vec4( boxSize/4.0f, boxSize, -boxSize/4.0f, 0.0f); triangles[13].p1 = glm::vec4( -boxSize/4.0f, boxSize, boxSize/4.0f, 0.0f);*/ GeometryDescriptor* geometry = new GeometryDescriptor( inSizeS, inSizeP, inSizeT ); Surface* pSurf = new Surface[inSurf]; pSurf[0].vColor = glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f ); pSurf[1].vColor = glm::vec4( 1.0f, 1.0f, 1.0f, 1.0f ); pSurf[2].vColor = glm::vec4( 1.0f, 1.0f, 1.0f, 1.0f ); float lPower = 5.0f; pSurf[2].vEmissive = glm::vec4( lPower, lPower, lPower, lPower ); pSurf[3].vColor = glm::vec4( 1.0f, 0.0f, 0.0f, 1.0f ); pSurf[4].vColor = glm::vec4( 0.0f, 1.0f, 0.0f, 1.0f ); cl::Buffer clSpheres( context, CL_MEM_READ_ONLY, inSizeS * sizeof( Sphere )); checkErr(err, "Buffer::Buffer()"); cl::Buffer clPlanes( context, CL_MEM_READ_ONLY, inSizeP * sizeof( Plane ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clTriangles( context, CL_MEM_READ_ONLY, inSizeT * sizeof( Triangle ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clCamera( context, CL_MEM_READ_ONLY, 1 * sizeof( CLCamera ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clGeom( context, CL_MEM_READ_ONLY, 1 * sizeof( GeometryDescriptor ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clImgDesc( context, CL_MEM_READ_ONLY, 1 * sizeof( ImageDescriptor ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clSeed( context, CL_MEM_READ_WRITE, WIDTH * HEIGHT * 4 * sizeof( uint ) ); checkErr(err, "Buffer::Buffer()"); cl::Buffer clSurf( context, CL_MEM_READ_WRITE, inSurf * sizeof( Surface ) ); checkErr(err, "Buffer::Buffer()"); cl::ImageGL imgGL( context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, pCLTarget->getColorTexture()->glGetInternalTexture(), &err ); checkErr(err, "ImageGL::ImageGL()"); cl::ImageGL accGL( context, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, pAccumulator->getColorTexture()->glGetInternalTexture(), &err ); checkErr(err, "ImageGL::ImageGL()"); std::cout<<"Created buffers."<< std::endl; srand( time( NULL ) ); uint *pSeeds = new uint[WIDTH * HEIGHT * 4]; for( int i = 0; i < WIDTH * HEIGHT * 4; i++ ){ pSeeds[i] = rand(); } std::vector<cl::Device> devices; devices = context.getInfo<CL_CONTEXT_DEVICES>(); checkErr(devices.size() > 0 ? CL_SUCCESS : -1, "devices.size() > 0"); std::cout<<"Num available devices: "<< devices.size()<< std::endl; std::ifstream file("src/kernel/kernel0.cl"); checkErr(file.is_open() ? CL_SUCCESS:-1, "src/kernel/kernel0.cl"); std::string prog( std::istreambuf_iterator<char>(file), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(prog.c_str(), prog.length()+1)); std::cout<<"Source obtained."<< std::endl; cl::Program program(context, source); err = program.build(devices,"-cl-opt-disable"); std::cout<<"Source obtained."<< std::endl; std::string buildLog; program.getBuildInfo( devices[0], CL_PROGRAM_BUILD_LOG, &buildLog ); std::cout<<"Build log:" << buildLog<< std::endl; checkErr(err, "Program::build()"); std::cout<<"Built program"<< std::endl; cl::Kernel kernel(program, "bi_directional_path_trace", &err); checkErr(err, "Kernel::Kernel()"); err = kernel.setArg(0, clCamera); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(1, imgGL); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(2, accGL); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(3, clSpheres); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(4, clPlanes); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(5, clTriangles); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(6, clGeom); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(7, clImgDesc); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(8, clSeed); checkErr(err, "Kernel::setArg()"); err = kernel.setArg(9, clSurf); checkErr(err, "Kernel::setArg()"); std::cout<<"Built Kernel"<< std::endl; pCamera = new ModelCamera( window ); pCamera->setSpeedX( 0.03f ); pCamera->setSpeedY( 0.03f ); pCamera->setRadius( 8.0f ); pCamera->setOrientation( glm::vec3( 0.0f, -1.0f, 0.0f ) ); pCamera->reset( glm::vec3( 1.0f, 0.1f, -0.1f ) ); cl::CommandQueue queue(context, devices[0], 0, &err); checkErr(err, "CommandQueue::CommandQueue()"); CLCamera* cam = pCamera->getCLCamera(); std::cout<<cam->vPos.x<<","<<cam->vPos.y<<","<<cam->vPos.z<<std::endl; std::cout<<cam->vLookAt.x<<","<<cam->vLookAt.y<<","<<cam->vLookAt.z<<std::endl; std::cout<<cam->vUp.x<<","<<cam->vUp.y<<","<<cam->vUp.z<<std::endl; std::cout<< sizeof( Plane )<< std::endl; queue.enqueueWriteBuffer( clCamera, CL_TRUE, 0, 1 * sizeof(CLCamera), (const void*)cam ); queue.enqueueWriteBuffer( clSpheres, CL_TRUE, 0, inSizeS * sizeof(Sphere), (const void*)spheres); queue.enqueueWriteBuffer( clPlanes, CL_TRUE, 0, inSizeP * sizeof(Plane), (const void*)planes); queue.enqueueWriteBuffer( clTriangles, CL_TRUE, 0, inSizeT * sizeof(Triangle), (const void*)triangles); queue.enqueueWriteBuffer( clGeom, CL_TRUE, 0, 1 * sizeof(GeometryDescriptor), (const void*)geometry); queue.enqueueWriteBuffer( clSeed, CL_TRUE, 0, WIDTH * HEIGHT * 4 * sizeof(uint), (const void*)pSeeds); queue.enqueueWriteBuffer( clSurf, CL_TRUE, 0, inSurf * sizeof(Surface), (const void*)pSurf); vSharedUnits = new std::vector<cl::Memory>(); vSharedUnits->push_back( imgGL ); vSharedUnits->push_back( accGL ); //Initialise counter. imgDesc.numSamples = 0; imgDesc.sampleRate = SAMPLES; cLast = clock(); while( !glfwWindowShouldClose( window ) ){ //usleep( 1000000 ); mainLoop( queue, context, kernel, clImgDesc, clCamera ); } /* Previous Program. Remove these if you think they are not required. float *fout = new float[inSize]; err = queue.enqueueReadBuffer( clSpheres, CL_TRUE, 0, inSize * sizeof(Sphere), fout); */ checkErr(err, "ComamndQueue::enqueueReadBuffer()"); std::cout<<"Kernel finished executing."<< std::endl; delete vSharedUnits; return EXIT_SUCCESS; }
int main(int argc, char **argv) { int i; int filecount = 0; char* filename = NULL; { int c, option_index = 0; static struct option long_options[] = { {"help", 0, 0, 0}, {"output", 2, 0, 0}, {"size", 1, 0, 0}, {NULL, 0, NULL, 0} }; char* endptr = NULL; bool opt_fail = false; bool help = false; while ((c = getopt_long(argc, argv, "ho::s:", long_options, &option_index)) != -1) { switch (c) { case 0: switch(option_index) { case 0: // help goto help; case 1: // output goto output; case 2: // size goto size; default: goto unknown; } break; help: case 'h': // help help = true; break; output: case 'o': // output filecount = 1; // avoid leakiness if the user provided multiple --output // free(NULL) is a no-op, so this should be safe: free(filename); filename = NULL; if(optarg != NULL) { int tmp = strtol(optarg, &endptr, 10); if (endptr == optarg || (endptr != NULL && *endptr != '\0')) { int len = strlen(optarg); filename = malloc(len + 1); strcpy(filename, optarg); filename[len] = '\0'; } else { filecount = tmp; } } break; size: case 's': i = 0; while(optarg[i] != '*' && optarg[i] != '\0') i++; if(optarg[i] == '\0') { goto size_fail; } optarg[i] = '\0'; width = strtol(optarg, &endptr, 10); if (endptr == optarg || (endptr != NULL && *endptr != '\0')) { goto size_fail; } height = strtol(optarg + i + 1, &endptr, 10); if (endptr == optarg || (endptr != NULL && *endptr != '\0')) { goto size_fail; } printf("width: %d, height: %d\n", width, height); break; size_fail: fprintf(stderr, "Invalid size string '%s'\n", optarg); print_help(1); break; unknown: case '?': opt_fail = true; break; default: fprintf(stderr, "?? getopt returned character code 0%o ??\n", c); } } if(opt_fail) { print_help(1); } if(optind < argc) { fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[optind]); print_help(1); } if(help) { print_help(0); } } scale = max(width, height); srand(get_time_us()); GLFWwindow* window; glfwSetErrorCallback(error_callback); // Initialize the library if (!glfwInit()) return -1; glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a windowed mode window and its OpenGL context if(filecount) { glfwWindowHint(GLFW_VISIBLE, false); window = glfwCreateWindow(1, 1, "SpaceScape", NULL, NULL); } else { window = glfwCreateWindow(width, height, "SpaceScape", NULL, NULL); } if (!window) { glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); // Init GLEW glewExperimental = true; GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } fprintf(stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION)); if (!GLEW_ARB_vertex_buffer_object) { fputs("VBO not supported\n", stderr); exit(1); } render_init(); if(filename) { render_to_png(filename); } else if(filecount) { for(i = 0; i < filecount; i++) { render_to_png(NULL); } } else { // Render to our framebuffer render_to_screen(); while (!glfwWindowShouldClose(window)) { // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // Draw the triangles ! glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles glDisableVertexAttribArray(0); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } } render_cleanup(); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }