xdl_int XdevLOpenGLWGL::create(XdevLWindow* window) { if(window == NULL) { XDEVL_MODULE_ERROR("Parameter invalid.\n"); return ERR_ERROR; } m_window = window; m_wnd = static_cast<HWND>(m_window->getInternal(XdevLInternalName("WIN32_HWND"))); if ( m_wnd == NULL) { XDEVL_MODULE_ERROR("Get WIN32_HWND failed.\n"); return ERR_ERROR; } if (initOpenGL() == ERR_ERROR) { XDEVL_MODULE_ERROR("Failed to initialize OpenGL.\n"); return ERR_ERROR; } // Set vertical syncronisation. setVSync(getVSync()); // TODO: This shouldn't be done maybe because it changes the initial state of the OpenGL context. glClearColor(1.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); SwapBuffers(m_DC); return ERR_OK; }
void init() { // Init GL before call this. Otherwise don't work. setVSync(true); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); float pos_light[4] = { 5.0f, 5.0f, 10.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_POSITION, pos_light); glEnable(GL_LIGHT0); #ifdef DEBUG glDisable(GL_CULL_FACE); #else glEnable(GL_CULL_FACE); #endif glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); #ifdef USE_BUFFERS glEnable(GL_LIGHTING); #else glDisable(GL_LIGHTING); #endif glClearColor(1.0f, 1.0f, 1.0f, 1.0f); load_resources(); game = new Game(); }
void igvInterfaz::crear_mundo(void) { /* Crear la escena */ cout << "Creando escena principal..." << endl; escena = new Escena(); cout << "\nCreando escena secundaria..." << endl; escena_secundaria = new Escena(); cout << "--------------------------------------\nMuseo creado correctamente" << endl; /* Crear cámaras */ float v[] = {5,1,2}; float v2[] = {5,1,1}; interfaz.camara.set(IGV_PERSPECTIVA, igvPunto3D(v2[0],v2[1],v2[2]),igvPunto3D(v[0],v[1],v[2]),igvPunto3D(0,1.0,0), 45, 1.78, 0.001, 200); interfaz.camara_secundaria.set(IGV_PARALELA, igvPunto3D(1,1,5),igvPunto3D(1,1,1),igvPunto3D(0,1.0,0), 2*-0.8, 2*0.8, 2*-0.45, 2*0.45, -3, 200); /* Calculo el ángulo de visión */ float vector[] = {v[0]-v2[0], v[1]-v2[1], v[2]-v2[2]}; float prodesc = vector[0]*-1 + vector[1]*0 + vector[2]*0; float modulos = sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]) * 1; float coseno = prodesc / modulos; angulo_vision = - acos(coseno) * 180/PI; glutSetCursor(GLUT_CURSOR_NONE); vsync = true; setVSync(vsync); }
int init_GL() { glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5); //glShadeModel(GL_SMOOTH); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, (double)screen_width/(double)screen_height, 1.0, 200.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (glGetError() != GL_NO_ERROR) return -1; setVSync(0); return 0; }
bool SDL2Window::setVSync(int vsync) { if(m_window && SDL_GL_SetSwapInterval(vsync) != 0) { if(vsync != 0 && vsync != 1) { return setVSync(1); } return false; } m_vsync = vsync; return true; }
void window::Window::open(const char *title, int width, int height, bool fullscreen, int msaa_level) { if (_fail) return; if (msaa_level > 0) { glfwWindowHint(GLFW_SAMPLES, msaa_level); _aa = msaa_level; } glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_STENCIL_BITS, 8); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // opengl 3.3 //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_STEREO, GL_TRUE); _primary_monitor = glfwGetPrimaryMonitor(); _glfw_vid_mode = glfwGetVideoMode(_primary_monitor); if (width == 0 && height == 0) { width = _glfw_vid_mode->width; height = _glfw_vid_mode->height; setRefreshRate(_glfw_vid_mode->refreshRate); } if (fullscreen) { _glfw_window = glfwCreateWindow(width, height, title, _primary_monitor, NULL); } else { _glfw_window = glfwCreateWindow(width, height, title, NULL, NULL); } if (!_glfw_window) { log("open(...) failed"); _fail = true; return; } glfwMakeContextCurrent(_glfw_window); _window_width = width; _window_height = height; hideMouseCursor(); setVSync(); }
void OpenGLDisplay::setOption( const char *option, int value ) { if( !_tcscmp( option, _T("vsync") ) ) { setVSync( value ); } if( !_tcscmp( option, _T("glFilter") ) ) { updateFiltering( value ); } if( !_tcscmp( option, _T("maxScale") ) ) { initializeMatrices( theApp.dest.right, theApp.dest.bottom ); } if( !_tcscmp( option, _T("fullScreenStretch") ) ) { initializeMatrices( theApp.dest.right, theApp.dest.bottom ); } }
int XdevLOpenGLContextGLX::create(XdevLWindow* window, XdevLOpenGLContext* shareContext) { XDEVL_ASSERT(m_display == nullptr, "XdevLOpenGLContextGLX already created."); if(nullptr != shareContext) { m_shareContext = static_cast<XdevLOpenGLContextGLX*>(shareContext); } window->getDescriptor().registerDependency(this); m_display = static_cast<Display*>(window->getInternal(XdevLInternalName("X11_DISPLAY"))); if(nullptr == m_display) { XDEVL_MODULE_ERROR("Could not get native X11 display information.\n"); return RET_FAILED; } m_window = (Window)(window->getInternal(XdevLInternalName("X11_WINDOW"))); if(None == m_window) { XDEVL_MODULE_ERROR("Could not get native X11 window information.\n"); return RET_FAILED; } if(glXQueryVersion(m_display, &m_glxMajorVersion, &m_glxMinorVersion) == False) { XDEVL_MODULE_ERROR("glXQueryVersion failed.\n"); return RET_FAILED; } if(initOpenGL(m_display, m_window) == RET_FAILED) { XDEVL_MODULE_ERROR("Failed to initialize OpenGL.\n"); return RET_FAILED; } if(glXIsDirect(m_display, m_glxContext)) { XDEVL_MODULE_INFO("Direct Rendering supported.\n"); } else { XDEVL_MODULE_WARNING("Direct Rendering not supported.\n"); } setVSync(getVSync()); return RET_SUCCESS; }
void SDLFrontend::update (uint32_t deltaTime) { #ifdef DEBUG const int sleepTime = abs(_debugSleep->getIntValue()) % 1000; if (0 < sleepTime) { SDL_Delay(sleepTime); } #endif ++_numFrames; _time += deltaTime; if (((_time - _timeBase) > 500 || _numFrames == 0) && Config.showFPS()) { setVSync(ConfigManager::get().isVSync()); const double fps = _numFrames * 1000.0f / (_time - _timeBase); setWindowTitle(Singleton<Application>::getInstance().getName() + " (" + string::toString((int) fps) + ")"); _timeBase = _time; _numFrames = 0; } _console->update(deltaTime); UI::get().update(deltaTime); SoundControl.update(deltaTime); ShaderManager::get().update(deltaTime); }
int main (int argc, const char * argv[]) { TwBar *myBar; float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f }; glm::mat4 mat; float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation float angle = 0.8f; double FT = 0; double FPS = 0; double starting = 0.0; double ending = 0.0; int rate = 0; int fr = 0; zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; // Current time double time = 0; // initialise GLFW int running = GL_TRUE; if (!glfwInit()) { exit(EXIT_FAILURE); } //only for OpenGL 2.1 #ifdef USE_OPENGL21 glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1); #endif //Only for OpenGL 3.2 #ifdef USE_OPENGL32 glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); #endif GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { glfwTerminate(); exit(EXIT_FAILURE); } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos(windowWidth/2, windowHeight/2); glfwSetWindowTitle("Chapter-11"); // Initialize AntTweakBar if ( !TwInit(TW_OPENGL_CORE, NULL)) { fprintf(stderr,"AntweakBar initialiazation failed: %s\n",TwGetLastError()); exit(1); } // Create a tweak bar myBar = TwNewBar("TweakBar"); //init GLEW and basic OpenGL information // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3 #ifdef USE_OPENGL32 glewExperimental = true; #endif glewInit(); std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl; if (GLEW_VERSION_2_1) { std::cout<<"\nYay! OpenGL 2.1 is supported and GLSL 1.2!\n"<<std::endl; } if (GLEW_VERSION_3_2) { std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl; } /* This extension defines an interface that allows various types of data (especially vertex array data) to be cached in high-performance graphics memory on the server, thereby increasing the rate of data transfers. Chunks of data are encapsulated within "buffer objects", which conceptually are nothing more than arrays of bytes, just like any chunk of memory. An API is provided whereby applications can read from or write to buffers, either via the GL itself (glBufferData, glBufferSubData, glGetBufferSubData) or via a pointer to the memory. */ if (glewIsSupported("GL_ARB_vertex_buffer_object")) std::cout<<"ARB VBO's are supported"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_buffer_object")) std::cout<<"APPLE VBO's are supported"<<std::endl; else std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; /* This extension introduces named vertex array objects which encapsulate vertex array state on the client side. The main purpose of these objects is to keep pointers to static vertex data and provide a name for different sets of static vertex data. By extending vertex array range functionality this extension allows multiple vertex array ranges to exist at one time, including their complete sets of state, in manner analogous to texture objects. GenVertexArraysAPPLE creates a list of n number of vertex array object names. After creating a name, BindVertexArrayAPPLE associates the name with a vertex array object and selects this vertex array and its associated state as current. To get back to the default vertex array and its associated state the client should bind to vertex array named 0. */ if (glewIsSupported("GL_ARB_vertex_array_object")) std::cout<<"ARB VAO's are supported\n"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX std::cout<<"APPLE VAO's are supported\n"<<std::endl; else std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl; std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::ostringstream stream1,stream2; stream1 << glGetString(GL_VENDOR); stream2 << glGetString(GL_RENDERER); std::string vendor ="Title : Chapter-11 Vendor : " + stream1.str() + " Renderer : " +stream2.str(); const char *tit = vendor.c_str(); glfwSetWindowTitle(tit); // Set GLFW event callbacks // - Redirect window size changes to the callback function WindowSizeCB glfwSetWindowSizeCallback(WindowSizeCB); // - Directly redirect GLFW mouse button events to AntTweakBar glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW); // - Directly redirect GLFW mouse position events to AntTweakBar glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW); // - Directly redirect GLFW mouse wheel events to AntTweakBar glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); // - Directly redirect GLFW key events to AntTweakBar glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW); // - Directly redirect GLFW char events to AntTweakBar glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); TwDefine("TweakBar label='Main TweakBar' alpha=0 help='Use this bar to control the objects of the scene.' "); // Add 'wire' to 'myBar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w]. TwAddVarRW(myBar, "wireframe mode", TW_TYPE_BOOL32, &wireFrame," label='Wireframe mode' key=w help='Toggle wireframe display mode.' "); // Add 'bgColor' to 'myBar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color) TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' "); // Add 'Rotation' to 'myBar': this is a variable of type TW_TYPE_QUAT4F which defines the scene's orientation TwAddVarRW(myBar, "SceneRotation", TW_TYPE_QUAT4F, &Rotation," label='Scene rotation' opened=true help='Change the scenes orientation.' "); TwAddButton(myBar, "Reset", ResetView,NULL," label='Reset View' "); TwAddVarRW(myBar, "Near Clip Plane", TW_TYPE_FLOAT, &zNear,"min=0.5 max=100 step=0.5 label='Near Clip' group='Projection Properties'"); TwAddVarRW(myBar, "Far Clip Plane", TW_TYPE_FLOAT, &zFar," min=0.5 max=1000 step=0.5 label='Far Clip' group='Projection Properties'"); TwAddVarRW(myBar, "Field of View", TW_TYPE_FLOAT, &FOV," label='FoV' readonly=true group='Projection Properties'"); TwAddVarRW(myBar, "MS per 1 Frame" , TW_TYPE_DOUBLE, &FPS, "label='MS per 1 Frame' readonly=true group='Frame Rate'"); TwAddVarRW(myBar, "Frames Per Second" , TW_TYPE_INT32, &rate, "label='FPS' readonly=true group='Frame Rate'"); TwAddVarRW(myBar, "vSYNC" , TW_TYPE_BOOL8, &SYNC, "label='vSync' readonly=true group='Frame Rate'"); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); initPlane(); //initialize Plane init3Dmodel(); // initialize 3D model create_Bump_bar(); GLfloat rat = 0.001f; if(SYNC == false) { rat = 0.001f; } else { rat = 0.01f; } // Initialize time time = glfwGetTime(); double currentTime; float lastTime = 0.0f; int Frames = 0; double LT = glfwGetTime(); starting = glfwGetTime(); setVSync(SYNC); while (running) { glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color FOV = initialFoV - 5 * glfwGetMouseWheel(); if(camera == true) { glfwGetMousePos(&xpos,&ypos); glfwSetMousePos(windowWidth/2, windowHeight/2); horizAngle += mouseSpeedo * float(windowWidth/2 - xpos ); verticAngle += mouseSpeedo * float( windowHeight/2 - ypos ); } glm::vec3 direction(cos(verticAngle) * sin(horizAngle),sin(verticAngle),cos(verticAngle) * cos(horizAngle)); glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f/2.0f),0,cos(horizAngle - 3.14f/2.0f)); glm::vec3 up = glm::cross( right, direction ); currentTime = glfwGetTime(); float dTime = float(currentTime - lastTime); lastTime = (float)currentTime; // Move forward if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS){ pos += direction * dTime* speedo; } // Move backward if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS){ pos -= direction * dTime * speedo; } // Strafe right if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS){ pos += right * dTime * speedo; } //Strafe left if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS){ pos -= right * dTime * speedo; } if (glfwGetKey(GLFW_KEY_SPACE) == GLFW_PRESS){ if(camera == false) { camera=true; glfwSetMousePos(windowWidth/2, windowHeight/2); glfwGetMousePos(&xpos,&ypos); } else { camera=false; glfwSetMousePos(windowWidth/2, windowHeight/2); glfwGetMousePos(&xpos,&ypos); } } mat = ConvertQuaternionToMatrix(Rotation, mat); glm::mat4 cube; glm::mat4 translateMat = glm::mat4(); translateMat = glm::translate(translateMat,glm::vec3(5.0,3.0,4.0)); cube = mat * translateMat; displayPlane(mat,pos,direction,up); display3Dmodel(cube,mat,pos,direction,up); // drawing the AntWeakBar if (wireFrame) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); TwDraw(); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); TwDraw(); } fr++; ending = glfwGetTime(); if(ending - starting >= 1) { rate = fr; fr = 0; starting = glfwGetTime(); } double CT = glfwGetTime(); Frames++; if(CT -LT >= 1.0) { FPS = 1000.0 / (double)Frames; Frames = 0; LT += 1.0f; } glfwSwapBuffers(); //check if ESC was pressed running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); } //close OpenGL window and terminate AntTweakBar and GLFW TwTerminate(); glfwTerminate(); exit(EXIT_SUCCESS); }
bool ApplicationWindow_WGL::createWindow( std::string title, Vector2 position, Vector2 size, bool fullscreen, const ParameterMap *parameters) { _renderer = Renderer::getSingletonPtr(); HWND parentWnd = nullptr; int bpp = 32; int PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; if(parameters != nullptr) { ParameterMap::const_iterator it; ParameterMap::const_iterator itEnd = parameters->end(); if ( (it = parameters->find("parent_window")) != itEnd ) { parentWnd = (HWND) atoi(it->second.c_str()); dwStyle = WS_CHILD; } } Vector2 sceneSize = _renderer->_sceneViewMax - _renderer->_sceneViewMin; _aspectRatio = sceneSize.x / sceneSize.y; _fullscreen = fullscreen; _hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = &ApplicationWindow_WGL::initialWndProc;// WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = _hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = SKETCHYDYNAMICS_WINDOW_CLASS_NAME; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Failed To Register The Window Class"); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = (long)size.x; // Selected Screen Width dmScreenSettings.dmPelsHeight = (long)size.y; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bpp; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Use Windowed Mode. fullscreen=FALSE; Logger::getSingletonPtr()->writeWarning("Fullscreen mode not supported"); } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style //ShowCursor(FALSE); // Hide Mouse Pointer } RECT WindowRect; WindowRect.left = (long)position.x; WindowRect.right = (long)(position.x + size.x); WindowRect.top = (long)position.y; WindowRect.bottom = (long)(position.y + size.y); AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(_hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window SKETCHYDYNAMICS_WINDOW_CLASS_NAME, // Class Name title.c_str(), // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style (int)position.x, (int)position.y, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height parentWnd, // Parent Window NULL, // No Menu _hInstance, // Instance this))) // Pass To WM_CREATE { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Window Creation Error"); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bpp, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(_hDC=GetDC(_hWnd))) // Did We Get A Device Context? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Create A GL Device Context"); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(_hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Find A Suitable PixelFormat"); return FALSE; // Return FALSE } if(!SetPixelFormat(_hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Set The PixelFormat"); return FALSE; // Return FALSE } if (!(_hRC=wglCreateContext(_hDC))) // Are We Able To Get A Rendering Context? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Create A GL Rendering Context"); return FALSE; // Return FALSE } if(!wglMakeCurrent(_hDC,_hRC)) // Try To Activate The Rendering Context { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Activate The GL Rendering Context"); return FALSE; // Return FALSE } ShowWindow(_hWnd, SW_SHOW); // Show The Window SetForegroundWindow(_hWnd); // Slightly Higher Priority SetFocus(_hWnd); // Sets Keyboard Focus To The Window resizeGLScene((int)size.x, (int)size.y); // Set Up Our Perspective GL Screen if(!_renderer->initGL()) { SKETCHYDYNAMICS_LOG_ERROR("OpenGL init failed"); destroyWindow(); return FALSE; } setVSync(false); return TRUE; // Success }
int SDLFrontend::init (int width, int height, bool fullscreen, EventHandler &eventHandler) { if (width == -1 && height == -1) fullscreen = true; info(LOG_CLIENT, String::format("initializing: %i:%i - fullscreen: %s", width, height, fullscreen ? "true" : "false")); INIT_Subsystem(SDL_INIT_VIDEO, true); INIT_Subsystem(SDL_INIT_JOYSTICK, false); INIT_Subsystem(SDL_INIT_GAMECONTROLLER, false); INIT_Subsystem(SDL_INIT_HAPTIC, false); initJoystickAndHaptic(); SDL_DisplayMode displayMode; SDL_GetDesktopDisplayMode(0, &displayMode); const char *name = SDL_GetPixelFormatName(displayMode.format); info(LOG_CLIENT, String::format("current desktop mode: %dx%d@%dHz (%s)", displayMode.w, displayMode.h, displayMode.refresh_rate, name)); if (width == -1) width = 800;//displayMode.w; if (height == -1) height = 480; //displayMode.h; setGLAttributes(); setHints(); int doubleBuffered = 0; SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffered); info(LOG_CLIENT, String::format("doublebuffer: %s", doubleBuffered ? "activated" : "disabled")); int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; #ifdef __IPHONEOS__ flags |= SDL_WINDOW_RESIZABLE; #endif #if 1 //defined __IPHONEOS__ || defined __ANDROID__ if (fullscreen) flags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS; #else if (fullscreen) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_BORDERLESS; #endif const int videoDrivers = SDL_GetNumVideoDrivers(); for (int i = 0; i < videoDrivers; ++i) { info(LOG_CLIENT, String::format("available driver: %s", SDL_GetVideoDriver(i))); } info(LOG_CLIENT, String::format("driver: %s", SDL_GetCurrentVideoDriver())); const int displays = SDL_GetNumVideoDisplays(); info(LOG_CLIENT, String::format("found %i display(s)", displays)); if (fullscreen && displays > 1) { width = displayMode.w; height = displayMode.h; info(LOG_CLIENT, String::format("use fake fullscreen for the first display: %i:%i", width, height)); } _window = SDL_CreateWindow(Singleton<Application>::getInstance().getName().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags); if (!_window) { sdlCheckError(); return -1; } SDL_DisableScreenSaver(); initRenderer(); resetColor(); GLContext::get().init(); if (SDL_SetWindowBrightness(_window, 1.0f) == -1) sdlCheckError(); if (Config.isGrabMouse() && (!fullscreen || displays > 1)) { SDL_SetWindowGrab(_window, SDL_TRUE); } int screen = 0; int modes = SDL_GetNumDisplayModes(screen); info(LOG_CLIENT, "possible display modes:"); for (int i = 0; i < modes; i++) { SDL_GetDisplayMode(screen, i, &displayMode); name = SDL_GetPixelFormatName(displayMode.format); info(LOG_CLIENT, String::format("%dx%d@%dHz %s", displayMode.w, displayMode.h, displayMode.refresh_rate, name)); } // some platforms may override or hardcode the resolution - so // we have to query it here to get the actual resolution SDL_GetWindowSize(_window, &width, &height); if (SDL_SetRelativeMouseMode(SDL_TRUE) == -1) error(LOG_CLIENT, "no relative mouse mode support"); SDL_ShowCursor(0); info(LOG_CLIENT, String::format("actual resolution: %dx%d", width, height)); setVSync(ConfigManager::get().isVSync()); const int initState = IMG_Init(IMG_INIT_PNG); if (!(initState & IMG_INIT_PNG)) { sdlCheckError(); System.exit("No png support", 1); } _width = width; _height = height; updateViewport(0, 0, getWidth(), getHeight()); onInit(); _eventHandler = &eventHandler; _eventHandler->registerObserver(_console.get()); _eventHandler->registerObserver(this); info(LOG_CLIENT, "init the shader manager"); ShaderManager::get().init(); if (!Config.isSoundEnabled()) { info(LOG_CLIENT, "sound disabled"); } else if (!SoundControl.init(true)) { error(LOG_CLIENT, "sound initialization failed"); } return 0; }
bool SDL2Window::initialize() { arx_assert(!m_displayModes.empty()); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); #if ARX_PLATFORM == ARX_PLATFORM_WIN32 // Used on Windows to prevent software opengl fallback. // The linux situation: // Causes SDL to require visuals without caveats. // On linux some drivers only supply multisample capable GLX Visuals // with a GLX_NON_CONFORMANT_VISUAL_EXT caveat. // see: https://www.opengl.org/registry/specs/EXT/visual_rating.txt SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); #endif // TODO EGL and core profile are not supported yet SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); if(gldebug::isEnabled()) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); } int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; Uint32 windowFlags = getSDLFlagsForMode(m_size, m_fullscreen); windowFlags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; for(int msaa = m_maxMSAALevel; msaa > 0; msaa--) { bool lastTry = (msaa == 1); // Cleanup context and window from previous tries if(m_glcontext) { SDL_GL_DeleteContext(m_glcontext); m_glcontext = NULL; } if(m_window) { SDL_DestroyWindow(m_window); m_window = NULL; } SDL_ClearError(); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, msaa > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, msaa > 1 ? msaa : 0); m_window = SDL_CreateWindow(m_title.c_str(), x, y, m_size.x, m_size.y, windowFlags); if(!m_window) { if(lastTry) { LogError << "Could not create window: " << SDL_GetError(); return false; } continue; } m_glcontext = SDL_GL_CreateContext(m_window); if(!m_glcontext) { if(lastTry) { LogError << "Could not create GL context: " << SDL_GetError(); return false; } continue; } // Verify that the MSAA setting matches what was requested int msaaEnabled, msaaValue; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &msaaEnabled); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &msaaValue); if(!lastTry) { if(!msaaEnabled || msaaValue < msaa) { continue; } } if(msaaEnabled) { m_MSAALevel = msaaValue; } else { m_MSAALevel = 0; } // Verify that we actually got an accelerated context (void)glGetError(); // clear error flags GLint texunits = 0; glGetIntegerv(GL_MAX_TEXTURE_UNITS, &texunits); if(glGetError() != GL_NO_ERROR || texunits < GLint(m_minTextureUnits)) { if(lastTry) { LogError << "Not enough GL texture units available: have " << texunits << ", need at least " << m_minTextureUnits; return false; } continue; } // All good const char * system = "(unknown)"; { ARX_SDL_SysWMinfo info; info.version.major = 2; info.version.minor = 0; info.version.patch = 4; if(SDL_GetWindowWMInfo(m_window, reinterpret_cast<SDL_SysWMinfo *>(&info))) { switch(info.subsystem) { case ARX_SDL_SYSWM_UNKNOWN: break; case ARX_SDL_SYSWM_WINDOWS: system = "Windows"; break; case ARX_SDL_SYSWM_X11: system = "X11"; break; #if SDL_VERSION_ATLEAST(2, 0, 3) case ARX_SDL_SYSWM_WINRT: system = "WinRT"; break; #endif case ARX_SDL_SYSWM_DIRECTFB: system = "DirectFB"; break; case ARX_SDL_SYSWM_COCOA: system = "Cocoa"; break; case ARX_SDL_SYSWM_UIKIT: system = "UIKit"; break; #if SDL_VERSION_ATLEAST(2, 0, 2) case ARX_SDL_SYSWM_WAYLAND: system = "Wayland"; break; case ARX_SDL_SYSWM_MIR: system = "Mir"; break; #endif #if SDL_VERSION_ATLEAST(2, 0, 4) case ARX_SDL_SYSWM_ANDROID: system = "Android"; break; #endif } } } int red = 0, green = 0, blue = 0, alpha = 0, depth = 0, doublebuffer = 0; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &red); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &green); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &blue); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alpha); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doublebuffer); LogInfo << "Window: " << system << " r:" << red << " g:" << green << " b:" << blue << " a:" << alpha << " depth:" << depth << " aa:" << msaa << "x" << " doublebuffer:" << doublebuffer; break; } // Use the executable icon for the window #if ARX_PLATFORM == ARX_PLATFORM_WIN32 { SDL_SysWMinfo info; SDL_VERSION(&info.version); if(SDL_GetWindowWMInfo(m_window, &info) && info.subsystem == SDL_SYSWM_WINDOWS) { platform::WideString filename; filename.allocate(filename.capacity()); while(true) { DWORD size = GetModuleFileNameW(NULL, filename.data(), filename.size()); if(size < filename.size()) { filename.resize(size); break; } filename.allocate(filename.size() * 2); } HICON largeIcon = 0; HICON smallIcon = 0; ExtractIconExW(filename, 0, &largeIcon, &smallIcon, 1); if(smallIcon) { SendMessage(info.info.win.window, WM_SETICON, ICON_SMALL, LPARAM(smallIcon)); } if(largeIcon) { SendMessage(info.info.win.window, WM_SETICON, ICON_BIG, LPARAM(largeIcon)); } } } #endif setVSync(m_vsync); SDL_ShowWindow(m_window); SDL_ShowCursor(SDL_DISABLE); m_renderer->initialize(); onCreate(); onToggleFullscreen(m_fullscreen); updateSize(true); onShow(true); onFocus(true); return true; }
void OpenGL2Common::initializeGL() { initGLProc(); #ifndef OPENGL_ES2 if (!glActiveTexture) //Be sure that "glActiveTexture" has valid pointer (don't check "supportsShaders" here)! { showOpenGLMissingFeaturesMessage(); isOK = false; return; } #endif delete shaderProgramVideo; delete shaderProgramOSD; shaderProgramVideo = new QOpenGLShaderProgram; shaderProgramOSD = new QOpenGLShaderProgram; /* YCbCr shader */ shaderProgramVideo->addShaderFromSourceCode(QOpenGLShader::Vertex, readShader(":/Video.vert")); QByteArray videoFrag; if (numPlanes == 1) { videoFrag = readShader(":/VideoRGB.frag"); if (canUseHueSharpness) { //Use sharpness only when OpenGL/OpenGL|ES version >= 3.0, because it can be slow on old hardware and/or buggy drivers and may increase CPU usage! videoFrag.prepend("#define Sharpness\n"); } } else { videoFrag = readShader(":/VideoYCbCr.frag"); if (canUseHueSharpness) { //Use hue and sharpness only when OpenGL/OpenGL|ES version >= 3.0, because it can be slow on old hardware and/or buggy drivers and may increase CPU usage! videoFrag.prepend("#define HueAndSharpness\n"); } if (numPlanes == 2) videoFrag.prepend("#define NV12\n"); } if (target == GL_TEXTURE_RECTANGLE_ARB) videoFrag.prepend("#define TEXTURE_RECTANGLE\n"); if (hqScaling) { constexpr const char *getTexelDefine = "#define getTexel texture\n"; Q_ASSERT(videoFrag.contains(getTexelDefine)); videoFrag.replace(getTexelDefine, readShader(":/Bicubic.frag", true)); } shaderProgramVideo->addShaderFromSourceCode(QOpenGLShader::Fragment, videoFrag); if (shaderProgramVideo->bind()) { texCoordYCbCrLoc = shaderProgramVideo->attributeLocation("aTexCoord"); positionYCbCrLoc = shaderProgramVideo->attributeLocation("aPosition"); shaderProgramVideo->setUniformValue((numPlanes == 1) ? "uRGB" : "uY" , 0); if (numPlanes == 2) shaderProgramVideo->setUniformValue("uCbCr", 1); else if (numPlanes == 3) { shaderProgramVideo->setUniformValue("uCb", 1); shaderProgramVideo->setUniformValue("uCr", 2); } shaderProgramVideo->release(); } else { QMPlay2Core.logError(tr("Shader compile/link error")); isOK = false; return; } /* OSD shader */ shaderProgramOSD->addShaderFromSourceCode(QOpenGLShader::Vertex, readShader(":/OSD.vert")); shaderProgramOSD->addShaderFromSourceCode(QOpenGLShader::Fragment, readShader(":/OSD.frag")); if (shaderProgramOSD->bind()) { texCoordOSDLoc = shaderProgramOSD->attributeLocation("aTexCoord"); positionOSDLoc = shaderProgramOSD->attributeLocation("aPosition"); shaderProgramOSD->setUniformValue("uTex", 3); shaderProgramOSD->release(); } else { QMPlay2Core.logError(tr("Shader compile/link error")); isOK = false; return; } /* Set OpenGL parameters */ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_STENCIL_TEST); glDisable(GL_DEPTH_TEST); glDisable(GL_DITHER); /* Prepare textures */ glGenTextures(numPlanes + 1, textures); for (int i = 0; i < numPlanes + 1; ++i) { const quint32 tmpTarget = (i == 0) ? GL_TEXTURE_2D : target; qint32 tmpParam = (i == 0) ? GL_NEAREST : GL_LINEAR; glBindTexture(tmpTarget, textures[i]); glTexParameteri(tmpTarget, GL_TEXTURE_MIN_FILTER, tmpParam); glTexParameteri(tmpTarget, GL_TEXTURE_MAG_FILTER, tmpParam); glTexParameteri(tmpTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(tmpTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } if (hasPbo) { glGenBuffers(1 + (hwAccellnterface ? 0 : numPlanes), pbo); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } setVSync(vSync); doReset = true; resetSphereVbo(); }
bool GL_Init(HWND window) { hWnd = window; GLuint PixelFormat; // Holds The Results After Searching For A Match hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(hWnd))) // Did We Get A Device Context? { MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; } if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; } setVSync(0); glewInit(); ResizeGLScene(); // Set Up Our Perspective GL Screen return true; // Success }
bool SDL2Window::initialize() { arx_assert(!m_displayModes.empty()); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // We need an accelerated OpenGL context or we'll likely fail later SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // TODO EGL and core profile are not supported yet SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, 0); if(gldebug::isEnabled()) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); } int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; Uint32 windowFlags = getSDLFlagsForMode(m_size, m_fullscreen); windowFlags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; for(int msaa = m_maxMSAALevel; msaa > 0; msaa--) { bool lastTry = (msaa == 1); // Cleanup context and window from previous tries if(m_glcontext) { SDL_GL_DeleteContext(m_glcontext); m_glcontext = NULL; } if(m_window) { SDL_DestroyWindow(m_window); m_window = NULL; } SDL_ClearError(); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, msaa > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, msaa > 1 ? msaa : 0); m_window = SDL_CreateWindow(m_title.c_str(), x, y, m_size.x, m_size.y, windowFlags); if(!m_window) { if(lastTry) { LogError << "Could not create window: " << SDL_GetError(); return false; } continue; } m_glcontext = SDL_GL_CreateContext(m_window); if(!m_glcontext) { if(lastTry) { LogError << "Could not create GL context: " << SDL_GetError(); return false; } continue; } // Verify that the MSAA setting matches what was requested int msaaEnabled, msaaValue; SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &msaaEnabled); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &msaaValue); if(!lastTry) { if(!msaaEnabled || msaaValue < msaa) { continue; } } if(msaaEnabled) { m_MSAALevel = msaaValue; } else { m_MSAALevel = 0; } // Verify that we actually got an accelerated context (void)glGetError(); // clear error flags GLint texunits = 0; glGetIntegerv(GL_MAX_TEXTURE_UNITS, &texunits); if(glGetError() != GL_NO_ERROR || texunits < GLint(m_minTextureUnits)) { if(lastTry) { LogError << "Not enough GL texture units available: have " << texunits << ", need at least " << m_minTextureUnits; return false; } continue; } // All good int red = 0, green = 0, blue = 0, alpha = 0, depth = 0, doublebuffer = 0; SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &red); SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &green); SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &blue); SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alpha); SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth); SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doublebuffer); LogInfo << "Window: r:" << red << " g:" << green << " b:" << blue << " a:" << alpha << " depth:" << depth << " aa:" << msaa << "x doublebuffer:" << doublebuffer; break; } setVSync(m_vsync); SDL_ShowWindow(m_window); SDL_ShowCursor(SDL_DISABLE); m_renderer->initialize(); onCreate(); onToggleFullscreen(m_fullscreen); updateSize(true); onShow(true); onFocus(true); return true; }
bool OpenGLDisplay::initialize() { switch( theApp.cartridgeType ) { case IMAGE_GBA: theApp.sizeX = 240; theApp.sizeY = 160; break; case IMAGE_GB: if ( gbBorderOn ) { theApp.sizeX = 256; theApp.sizeY = 224; } else { theApp.sizeX = 160; theApp.sizeY = 144; } break; } switch(theApp.videoOption) { case VIDEO_1X: theApp.surfaceSizeX = theApp.sizeX; theApp.surfaceSizeY = theApp.sizeY; break; case VIDEO_2X: theApp.surfaceSizeX = theApp.sizeX * 2; theApp.surfaceSizeY = theApp.sizeY * 2; break; case VIDEO_3X: theApp.surfaceSizeX = theApp.sizeX * 3; theApp.surfaceSizeY = theApp.sizeY * 3; break; case VIDEO_4X: theApp.surfaceSizeX = theApp.sizeX * 4; theApp.surfaceSizeY = theApp.sizeY * 4; break; case VIDEO_320x240: case VIDEO_640x480: case VIDEO_800x600: case VIDEO_OTHER: { if( theApp.fullScreenStretch ) { theApp.surfaceSizeX = theApp.fsWidth; theApp.surfaceSizeY = theApp.fsHeight; } else { float scaleX = (float)theApp.fsWidth / (float)theApp.sizeX; float scaleY = (float)theApp.fsHeight / (float)theApp.sizeY; float min = ( scaleX < scaleY ) ? scaleX : scaleY; if( theApp.fsMaxScale ) min = ( min > (float)theApp.fsMaxScale ) ? (float)theApp.fsMaxScale : min; theApp.surfaceSizeX = (int)((float)theApp.sizeX * min); theApp.surfaceSizeY = (int)((float)theApp.sizeY * min); } } break; } theApp.rect.left = 0; theApp.rect.top = 0; theApp.rect.right = theApp.sizeX; theApp.rect.bottom = theApp.sizeY; theApp.dest.left = 0; theApp.dest.top = 0; theApp.dest.right = theApp.surfaceSizeX; theApp.dest.bottom = theApp.surfaceSizeY; DWORD style = WS_POPUP | WS_VISIBLE; DWORD styleEx = 0; if( theApp.videoOption <= VIDEO_4X ) style |= WS_OVERLAPPEDWINDOW; else styleEx = 0; if( theApp.videoOption <= VIDEO_4X ) AdjustWindowRectEx( &theApp.dest, style, TRUE, styleEx ); else AdjustWindowRectEx( &theApp.dest, style, FALSE, styleEx ); int winSizeX = theApp.dest.right - theApp.dest.left; int winSizeY = theApp.dest.bottom - theApp.dest.top; int x = 0, y = 0; if( theApp.videoOption <= VIDEO_4X ) { x = theApp.windowPositionX; y = theApp.windowPositionY; } else { winSizeX = theApp.fsWidth; winSizeY = theApp.fsHeight; } // Create a window MainWnd *pWnd = new MainWnd; theApp.m_pMainWnd = pWnd; pWnd->CreateEx( styleEx, theApp.wndClass, "VisualBoyAdvance", style, x,y,winSizeX,winSizeY, NULL, 0 ); if (!(HWND)*pWnd) { winlog("Error creating Window %08x\n", GetLastError()); return FALSE; } theApp.updateMenuBar(); theApp.adjustDestRect(); theApp.mode320Available = FALSE; theApp.mode640Available = FALSE; theApp.mode800Available = FALSE; CDC *dc = pWnd->GetDC(); HDC hDC = dc->GetSafeHdc(); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 32, // 32-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; int iPixelFormat; if( !(iPixelFormat = ChoosePixelFormat( hDC, &pfd )) ) { winlog( "Failed ChoosePixelFormat\n" ); return false; } // obtain detailed information about // the device context's first pixel format if( !( DescribePixelFormat( hDC, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd ) ) ) { winlog( "Failed DescribePixelFormat\n" ); return false; } if( !SetPixelFormat( hDC, iPixelFormat, &pfd ) ) { winlog( "Failed SetPixelFormat\n" ); return false; } if( !( hglrc = wglCreateContext( hDC ) ) ) { winlog( "Failed wglCreateContext\n" ); return false; } if( !wglMakeCurrent(hDC, hglrc) ) { winlog( "Failed wglMakeCurrent\n" ); return false; } pWnd->ReleaseDC( dc ); // setup 2D gl environment glPushAttrib( GL_ENABLE_BIT ); glDisable( GL_DEPTH_TEST ); glDisable( GL_CULL_FACE ); glEnable( GL_TEXTURE_2D ); initializeMatrices( theApp.surfaceSizeX, theApp.surfaceSizeY ); setVSync( theApp.vsync ); #ifdef MMX if(!theApp.disableMMX) cpu_mmx = theApp.detectMMX(); else cpu_mmx = 0; #endif systemRedShift = 3; systemGreenShift = 11; systemBlueShift = 19; systemColorDepth = 32; theApp.fsColorDepth = 32; Init_2xSaI(32); utilUpdateSystemColorMaps(); theApp.updateFilter(); theApp.updateIFB(); if(failed) return false; pWnd->DragAcceptFiles(TRUE); return TRUE; }
void toggleVSync() { setVSync(!getVSync()); }
Window::Window(const std::string& title, int width, int height, bool vSync) : title(title), vSync(vSync) { handle = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); makeCurrent(); setVSync(vSync); }