void DGSystem::init() { if (!_isInitialized) { log->trace(DGModSystem, "%s", DGMsg040000); InitializeCriticalSection(&csSystemThread); // Prepare the string to set the window title WCHAR title[DGMaxPathLength]; MultiByteToWideChar(0, 0, config->script(), DGMaxFileLength, title, DGMaxFileLength); WNDCLASSEX winClass; winClass.lpszClassName = L"DG_WINDOWS_CLASS"; winClass.cbSize = sizeof(WNDCLASSEX); winClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; winClass.lpfnWndProc = _WindowProc; winClass.hInstance = NULL; winClass.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(100)); winClass.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(100), IMAGE_ICON, 16, 16, 0); winClass.hCursor = LoadCursor(NULL, IDC_ARROW); winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winClass.lpszMenuName = NULL; winClass.cbClsExtra = 0; winClass.cbWndExtra = 0; if (!RegisterClassEx(&winClass)) return; // Now we create the actual window g_hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, L"DG_WINDOWS_CLASS", title, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, config->displayWidth, config->displayHeight, NULL, NULL, NULL, NULL ); if (g_hWnd == NULL) return; ShowWindow(g_hWnd, SW_SHOWNORMAL); UpdateWindow(g_hWnd); // Setup the OpenGL pixel format GLuint PixelFormat; PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW |PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 16; pfd.cDepthBits = 16; g_hDC = GetDC(g_hWnd); PixelFormat = ChoosePixelFormat(g_hDC, &pfd); SetPixelFormat( g_hDC, PixelFormat, &pfd); g_hRC = wglCreateContext(g_hDC); wglMakeCurrent(g_hDC, g_hRC); // FIXME: This doesn't work if the CTRL key is pressed when launching GetKeyboardState(defKeyboardState); // Now we're ready to init the controller instance control = &DGControl::getInstance(); control->init(); control->update(); // Check if we must enable vertical sync if (config->verticalSync) { // Get the available extensions in the card char* extensions = (char*)glGetString(GL_EXTENSIONS); // Is vertical sync possible? if (strstr(extensions,"WGL_EXT_swap_control")) { // If so get the address of the functions we defined before wglSwapIntervalEXT = (PFNWGLEXTSWAPCONTROLPROC) wglGetProcAddress("wglSwapIntervalEXT"); wglGetSwapIntervalEXT = (PFNWGLEXTGETSWAPINTERVALPROC) wglGetProcAddress("wglGetSwapIntervalEXT"); // Go ahead and enable wglSwapIntervalEXT(1); } else log->error(DGModSystem, "%s", DGMsg240003); } ShowCursor(FALSE); _isInitialized = true; log->trace(DGModSystem, "%s", DGMsg040001); } else log->warning(DGModSystem, "%s", DGMsg140002); }
bool CWinAPIOpenGLWindow::Create(char* title, int width, int height, int bits, bool fullscreenflag, WNDPROC WndProc) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height m_Fullscreen = fullscreenflag; // Set The Global Fullscreen Flag m_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 = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = m_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 = "OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (m_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 = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // 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, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { m_Fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (m_Fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(m_hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu m_hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { Kill(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); 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 bits, // 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) 8, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(m_hDC=GetDC(m_hWnd))) // Did We Get A Device Context? { Kill(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(m_hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { Kill(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(m_hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { Kill(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } HGLRC TempContext; if (!(TempContext = wglCreateContext(m_hDC))) // Are We Able To Get A Rendering Context? { Kill(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(m_hDC,TempContext)) // Try To Activate The Rendering Context { Kill(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } GLenum err = glewInit(); if (GLEW_OK != err) { MessageBox(NULL, "GLEW is not initialized!", "ERROR", MB_OK|MB_ICONEXCLAMATION); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; if(wglewIsSupported("WGL_ARB_create_context") == 1) { m_hRC = wglCreateContextAttribsARB(m_hDC,0, attribs); wglMakeCurrent(NULL,NULL); wglDeleteContext(TempContext); wglMakeCurrent(m_hDC, m_hRC); } else { //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) m_hRC = TempContext; } ShowWindow(m_hWnd,SW_SHOW); // Show The Window SetForegroundWindow(m_hWnd); // Slightly Higher Priority SetFocus(m_hWnd); // Sets Keyboard Focus To The Window //ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen /*if (!InitGL()) // Initialize Our Newly Created GL Window { Kill(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE }*/ return true; // Success }
bool GLWindow::DisplayWindow(int _width, int _height) { GLuint PixelFormat; // Holds The Results After Searching For A Match DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT rcdesktop; GetWindowRect(GetDesktopWindow(), &rcdesktop); if (conf.fullscreen()) { nBackbufferWidth = rcdesktop.right - rcdesktop.left; nBackbufferHeight = rcdesktop.bottom - rcdesktop.top; dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; ShowCursor(false); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; } RECT rc; rc.left = 0; rc.top = 0; rc.right = nBackbufferWidth; rc.bottom = nBackbufferHeight; AdjustWindowRectEx(&rc, dwStyle, false, dwExStyle); int X = (rcdesktop.right - rcdesktop.left) / 2 - (rc.right - rc.left) / 2; int Y = (rcdesktop.bottom - rcdesktop.top) / 2 - (rc.bottom - rc.top) / 2; SetWindowLong(GShwnd, GWL_STYLE, dwStyle); SetWindowLong(GShwnd, GWL_EXSTYLE, dwExStyle); SetWindowPos(GShwnd, HWND_TOP, X, Y, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW); if (conf.fullscreen()) { DEVMODE dmScreenSettings; memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = nBackbufferWidth; dmScreenSettings.dmPelsHeight = nBackbufferHeight; dmScreenSettings.dmBitsPerPel = 32; 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 (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) conf.setFullscreen(false); else return false; } } else { // change to default resolution ChangeDisplaySettings(NULL, 0); } 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, // 8bit Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 8, // 8bit Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(GShwnd))) { MessageBox(NULL, "(1) Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { MessageBox(NULL, "(2) Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; } if (!SetPixelFormat(hDC, PixelFormat, &pfd)) { MessageBox(NULL, "(3) Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; } if (!(hRC = wglCreateContext(hDC))) { MessageBox(NULL, "(4) Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; } if (!wglMakeCurrent(hDC, hRC)) { MessageBox(NULL, "(5) Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return false; } UpdateWindow(GShwnd); return true; }
Renderer* Graphics::GetRenderer(Renderer_Desc& desc) { desc._hDC = GetDC(desc.hWnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(desc._hDC, &pfd); if (nPixelFormat == 0) return false; BOOL bResult = SetPixelFormat(desc._hDC, nPixelFormat, &pfd); if (!bResult) return false; HGLRC tempContext = wglCreateContext(desc._hDC); wglMakeCurrent(desc._hDC, tempContext); GLenum err = glewInit(); if (GLEW_OK != err) { //AfxMessageBox(_T("GLEW is not initialized!")); return NULL; } //int attribs[] = //{ // WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // WGL_CONTEXT_MINOR_VERSION_ARB, 1, // WGL_CONTEXT_FLAGS_ARB, 0, // 0 //}; //if (wglewIsSupported("WGL_ARB_create_context") == 1) //{ // desc._hrc = wglCreateContextAttribsARB(desc._hDC, 0, attribs); // wglMakeCurrent(NULL, NULL); // wglDeleteContext(tempContext); // wglMakeCurrent(desc._hDC, desc._hrc); //} //else //{ //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) desc._hrc = tempContext; //} //Checking GL version const GLubyte *GLVersionString = glGetString(GL_VERSION); //Or better yet, use the GL3 way to get the version number int OpenGLVersion[2]; glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); if (!desc._hrc) return NULL; Renderer* pRenderer = new Renderer(desc); return pRenderer; }
static int GLimp_InitGL( void ) { PIXELFORMATDESCRIPTOR pfd = { sizeof( PIXELFORMATDESCRIPTOR ), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 32, // 32-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 24, // 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 pixelformat; if( r_stencilbits->integer == 8 || r_stencilbits->integer == 16 ) pfd.cStencilBits = r_stencilbits->integer; /* ** set PFD_STEREO if necessary */ if( glConfig.stereoEnabled ) { ri.Com_DPrintf( "...attempting to use stereo\n" ); pfd.dwFlags |= PFD_STEREO; } /* ** Get a DC for the specified window */ if( glw_state.hDC != NULL ) ri.Com_Printf( "GLimp_Init() - non-NULL DC exists\n" ); if( ( glw_state.hDC = GetDC( glw_state.hWnd ) ) == NULL ) { ri.Com_Printf( "GLimp_Init() - GetDC failed\n" ); return false; } if( ( pixelformat = ChoosePixelFormat( glw_state.hDC, &pfd ) ) == 0 ) { ri.Com_Printf( "GLimp_Init() - ChoosePixelFormat failed\n" ); return false; } if( SetPixelFormat( glw_state.hDC, pixelformat, &pfd ) == FALSE ) { ri.Com_Printf( "GLimp_Init() - SetPixelFormat failed\n" ); return false; } DescribePixelFormat( glw_state.hDC, pixelformat, sizeof( pfd ), &pfd ); glConfig.stencilBits = pfd.cStencilBits; /* ** report if stereo is desired but unavailable */ if( !( pfd.dwFlags & PFD_STEREO ) && glConfig.stereoEnabled ) { ri.Com_Printf( "...failed to select stereo pixel format\n" ); glConfig.stereoEnabled = false; } /* ** startup the OpenGL subsystem by creating a context and making ** it current */ if( ( glw_state.hGLRC = qwglCreateContext( glw_state.hDC ) ) == 0 ) { ri.Com_Printf( "GLimp_Init() - qwglCreateContext failed\n" ); goto fail; } if( !qwglMakeCurrent( glw_state.hDC, glw_state.hGLRC ) ) { ri.Com_Printf( "GLimp_Init() - qwglMakeCurrent failed\n" ); goto fail; } /* ** print out PFD specifics */ ri.Com_Printf( "GL PFD: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", ( int ) pfd.cColorBits, ( int ) pfd.cDepthBits, ( int )pfd.cStencilBits ); return true; fail: if( glw_state.hGLRC ) { qwglDeleteContext( glw_state.hGLRC ); glw_state.hGLRC = NULL; } if( glw_state.hDC ) { ReleaseDC( glw_state.hWnd, glw_state.hDC ); glw_state.hDC = NULL; } return false; }
bool GL_Init(HWND window, std::string *error_message) { *error_message = "ok"; hWnd = window; GLuint PixelFormat; // TODO: Change to use WGL_ARB_pixel_format instead static const PIXELFORMATDESCRIPTOR pfd = { 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 24, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 8, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // At least a 16Bit Z-Buffer (Depth Buffer) 8, // 8-bit Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; hDC = GetDC(hWnd); if (!hDC) { *error_message = "Failed to get a device context."; return false; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { *error_message = "Can't find a suitable PixelFormat."; return false; } if (!SetPixelFormat(hDC, PixelFormat, &pfd)) { *error_message = "Can't set the PixelFormat."; return false; } if (!(hRC = wglCreateContext(hDC))) { *error_message = "Can't create a GL rendering context."; return false; } if (!wglMakeCurrent(hDC, hRC)) { *error_message = "Can't activate the GL rendering context."; return false; } // Check for really old OpenGL drivers and refuse to run really early in some cases. // TODO: Also either tell the user to give up or point the user to the right websites. Here's some collected // information about a system that will not work: // GL_VERSION GL_VENDOR GL_RENDERER // "1.4.0 - Build 8.14.10.2364" "intel" intel Pineview Platform I18NCategory *err = GetI18NCategory("Error"); std::string glVersion = (const char *)glGetString(GL_VERSION); std::string glRenderer = (const char *)glGetString(GL_RENDERER); const std::string openGL_1 = "1."; if (glRenderer == "GDI Generic" || glVersion.substr(0, openGL_1.size()) == openGL_1) { //The error may come from 16-bit colour mode //Check Colour depth HDC dc = GetDC(NULL); u32 colour_depth = GetDeviceCaps(dc, BITSPIXEL); ReleaseDC(NULL, dc); if (colour_depth != 32) { MessageBox(0, L"Please switch your display to 32-bit colour mode", L"OpenGL Error", MB_OK); ExitProcess(1); } const char *defaultError = "Insufficient OpenGL driver support detected!\n\n" "Your GPU reports that it does not support OpenGL 2.0. Would you like to try using DirectX 9 instead?\n\n" "DirectX is currently compatible with less games, but on your GPU it may be the only choice.\n\n" "Visit the forums at http://forums.ppsspp.org for more information.\n\n"; std::wstring versionDetected = ConvertUTF8ToWString(glVersion + "\n\n"); std::wstring error = ConvertUTF8ToWString(err->T("InsufficientOpenGLDriver", defaultError)); std::wstring title = ConvertUTF8ToWString(err->T("OpenGLDriverError", "OpenGL driver error")); std::wstring combined = versionDetected + error; bool yes = IDYES == MessageBox(hWnd, combined.c_str(), title.c_str(), MB_ICONERROR | MB_YESNO); if (yes) { // Change the config to D3D and restart. g_Config.iGPUBackend = GPU_BACKEND_DIRECT3D9; g_Config.Save(); W32Util::ExitAndRestart(); } // Avoid further error messages. Let's just bail, it's safe, and we can't continue. ExitProcess(1); } if (GLEW_OK != glewInit()) { *error_message = "Failed to initialize GLEW."; return false; } CheckGLExtensions(); int contextFlags = g_Config.bGfxDebugOutput ? WGL_CONTEXT_DEBUG_BIT_ARB : 0; // Alright, now for the modernity. First try a 4.4, then 4.3, context, if that fails try 3.3. // I can't seem to find a way that lets you simply request the newest version available. const int attribs44[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 4, WGL_CONTEXT_FLAGS_ARB, contextFlags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0 }; const int attribs43[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, contextFlags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0 }; const int attribs33[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, contextFlags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0 }; HGLRC m_hrc; if(wglewIsSupported("WGL_ARB_create_context") == 1) { m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs44); if (!m_hrc) m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs43); if (!m_hrc) m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs33); if (!m_hrc) { // Fall back m_hrc = hRC; } else { // Switch to the new ARB context. wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); wglMakeCurrent(hDC, m_hrc); } } else { // We can't make a GL 3.x context. Use an old style context (GL 2.1 and before) m_hrc = hRC; } if (GLEW_OK != glewInit()) { *error_message = "Failed to re-initialize GLEW."; return false; } if (!m_hrc) { *error_message = "No m_hrc"; return false; } hRC = m_hrc; GL_SwapInterval(0); // TODO: Also support GL_KHR_debug which might be more widely supported? if (g_Config.bGfxDebugOutput && glewIsSupported("GL_ARB_debug_output")) { glGetError(); glDebugMessageCallbackARB((GLDEBUGPROCARB)&DebugCallbackARB, 0); // print debug output to stderr if (glGetError()) { ERROR_LOG(G3D, "Failed to register a debug log callback"); } glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); if (glGetError()) { ERROR_LOG(G3D, "Failed to enable synchronous debug output"); } // For extra verbosity uncomment this (MEDIUM and HIGH are on by default): // glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, nullptr, GL_TRUE); } pauseRequested = false; resumeRequested = false; // These are auto-reset events. pauseEvent = CreateEvent(NULL, FALSE, FALSE, NULL); resumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL); return true; // Success }
//*************************************************************************// long Graphics::Initialize(HWND hWindow, unsigned long ulWidth, unsigned long ulHeight) { //-----------------------------------------------------------------------// // Create a data member to hold the result of this method. In this method's // case it will hold any error codes. By default set to 1 to signal no error. long lResultCode = 1; //-----------------------------------------------------------------------// smhWindow = hWindow; 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 }; GLuint PixelFormat; if(!(smhDeviceContext = GetDC(hWindow))) { lResultCode = -1; smhDeviceContext = NULL; } if(lResultCode > 0 && !(PixelFormat = ChoosePixelFormat(smhDeviceContext, &pfd))) // Did Windows Find A Matching Pixel Format? { lResultCode = -1; } if(lResultCode > 0 && !SetPixelFormat(smhDeviceContext, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { lResultCode = -1; } if(lResultCode > 0 && !(smhRenderingContext = wglCreateContext(smhDeviceContext))) // Are We Able To Get A Rendering Context? { lResultCode = -1; } if(lResultCode > 0 && !wglMakeCurrent(smhDeviceContext, smhRenderingContext)) // Try To Activate The Rendering Context { lResultCode = -1; } if(lResultCode > 0) { // Check Required Extensions GLenum err = glewInit(); if(err == GLEW_OK) { glewGetString(GLEW_VERSION); /// \TODO DO something with version. if(GLEW_ARB_vertex_buffer_object) { glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glEnable ( GL_LIGHTING ) ; float global_ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); GLfloat specular[] = {1.0f, 1.0f, 1.0f , 1.0f}; glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glShadeModel(GL_SMOOTH); glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glEnable(GL_TEXTURE_2D); glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, reinterpret_cast<GLint*>(&(smuiMaxNumberOfVertexElements))); glGetIntegerv(GL_MAX_ELEMENTS_INDICES, reinterpret_cast<GLint*>(&(smuiMaxNumberOfIndexElements))); } else { lResultCode = -1; } } else { glewGetErrorString(err); lResultCode = -1; /// \TODO do something with error. } } //-----------------------------------------------------------------------// // Return result/error code return lResultCode; //-----------------------------------------------------------------------// } // End of long Graphics::Initialize(HWND hWindow)
void TScene::Init(HDC hDC) { bool err=0; LogText("Start create Scene"); fps_time = 0; fps_counter = 0; fps_show = 0; last_time = GetTickCount(); // расчет FPS int m_GLPixelIndex; PIXELFORMATDESCRIPTOR pfd; ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cRedBits = 0; pfd.cRedShift = 0; pfd.cGreenBits = 0; pfd.cGreenShift = 0; pfd.cBlueBits = 0; pfd.cBlueShift = 0; pfd.cAlphaBits = 0; pfd.cAlphaShift = 0; pfd.cAccumBits = 0; pfd.cAccumRedBits = 0; pfd.cAccumGreenBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumAlphaBits = 0; pfd.cDepthBits = 32; pfd.cStencilBits = 0; pfd.cAuxBuffers = 0; pfd.iLayerType = PFD_MAIN_PLANE; pfd.bReserved = 0; pfd.dwLayerMask = 0; pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; m_GLPixelIndex = ChoosePixelFormat( hDC, &pfd); if(m_GLPixelIndex==0) // Let's choose a default index. { m_GLPixelIndex = 1; if(DescribePixelFormat(hDC,m_GLPixelIndex,sizeof(PIXELFORMATDESCRIPTOR),&pfd)==0) { LogText("err: DescribePixelFormat"); err = 0; } } if (SetPixelFormat( hDC, m_GLPixelIndex, &pfd)==FALSE) { LogText("err: SetPixelFormat"); err = 1; } hGLRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hGLRC); if (err==0) LogText("End sucsesful create Scene"); else LogText("err: create Scene!"); SetDefaultOpenGL(); }
/** * This function initializes a native window surface and caches the window * bounds in the given OGLSDOps. Returns JNI_TRUE if the operation was * successful; JNI_FALSE otherwise. */ jboolean OGLSD_InitOGLWindow(JNIEnv *env, OGLSDOps *oglsdo) { PIXELFORMATDESCRIPTOR pfd; WGLSDOps *wglsdo; WGLGraphicsConfigInfo *wglInfo; HWND window; RECT wbounds; HDC hdc; J2dTraceLn(J2D_TRACE_INFO, "OGLSD_InitOGLWindow"); if (oglsdo == NULL) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: ops are null"); return JNI_FALSE; } wglsdo = (WGLSDOps *)oglsdo->privOps; if (wglsdo == NULL) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: wgl ops are null"); return JNI_FALSE; } wglInfo = wglsdo->configInfo; if (wglInfo == NULL) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: graphics config info is null"); return JNI_FALSE; } window = wglsdo->window; if (!IsWindow(window)) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: disposed component"); return JNI_FALSE; } GetWindowRect(window, &wbounds); hdc = GetDC(window); if (hdc == 0) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: invalid hdc"); return JNI_FALSE; } if (!SetPixelFormat(hdc, wglInfo->pixfmt, &pfd)) { J2dRlsTraceLn(J2D_TRACE_ERROR, "OGLSD_InitOGLWindow: error setting pixel format"); ReleaseDC(window, hdc); return JNI_FALSE; } ReleaseDC(window, hdc); oglsdo->drawableType = OGLSD_WINDOW; oglsdo->isOpaque = JNI_TRUE; oglsdo->width = wbounds.right - wbounds.left; oglsdo->height = wbounds.bottom - wbounds.top; wglsdo->pbufferDC = 0; J2dTraceLn2(J2D_TRACE_VERBOSE, " created window: w=%d h=%d", oglsdo->width, oglsdo->height); return JNI_TRUE; }
bool CWGLManager::generateSurface() { HDC HDc = (HDC)CurrentContext.OpenGLWin32.HDc; // search for pixel format the simple way if (PixelFormat==0 || (!SetPixelFormat(HDc, PixelFormat, &pfd))) { for (u32 i=0; i<5; ++i) { if (i == 1) { if (Params.Stencilbuffer) { os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = false; pfd.cStencilBits = 0; } else continue; } else if (i == 2) { pfd.cDepthBits = 24; } if (i == 3) { if (Params.Bits!=16) pfd.cDepthBits = 16; else continue; } else if (i == 4) { os::Printer::log("Cannot create a GL device context", "No suitable format.", ELL_ERROR); return false; } // choose pixelformat PixelFormat = ChoosePixelFormat(HDc, &pfd); if (PixelFormat) break; } } // set pixel format if (!SetPixelFormat(HDc, PixelFormat, &pfd)) { os::Printer::log("Cannot set the pixel format.", ELL_ERROR); return false; } if (pfd.cAlphaBits != 0) { if (pfd.cRedBits == 8) ColorFormat = ECF_A8R8G8B8; else ColorFormat = ECF_A1R5G5B5; } else { if (pfd.cRedBits == 8) ColorFormat = ECF_R8G8B8; else ColorFormat = ECF_R5G6B5; } os::Printer::log("Pixel Format", core::stringc(PixelFormat).c_str(), ELL_DEBUG); return true; }
bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata) { // store params, videoData is set later as it would be overwritten else Params=params; // Create a window to test antialiasing support const fschar_t* ClassName = __TEXT("CWGLManager"); HINSTANCE lhInstance = GetModuleHandle(0); // Register Class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)DefWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = lhInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = 0; wcex.lpszClassName = ClassName; wcex.hIconSm = 0; wcex.hIcon = 0; RegisterClassEx(&wcex); RECT clientSize; clientSize.top = 0; clientSize.left = 0; clientSize.right = Params.WindowSize.Width; clientSize.bottom = Params.WindowSize.Height; DWORD style = WS_POPUP; if (!Params.Fullscreen) style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; AdjustWindowRect(&clientSize, style, FALSE); const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2; const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2; HWND temporary_wnd=CreateWindow(ClassName, __TEXT(""), style, windowLeft, windowTop, realWidth, realHeight, NULL, NULL, lhInstance, NULL); if (!temporary_wnd) { os::Printer::log("Cannot create a temporary window.", ELL_ERROR); UnregisterClass(ClassName, lhInstance); return false; } HDC HDc = GetDC(temporary_wnd); // Set up pixel format descriptor with desired parameters PIXELFORMATDESCRIPTOR tmp_pfd = { 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 (Params.Doublebuffer?PFD_DOUBLEBUFFER:0) | // Must Support Double Buffering (Params.Stereobuffer?PFD_STEREO:0), // Must Support Stereo Buffer PFD_TYPE_RGBA, // Request An RGBA Format Params.Bits, // 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 Params.ZBufferBits, // Z-Buffer (Depth Buffer) BYTE(Params.Stencilbuffer ? 1 : 0), // Stencil Buffer Depth 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; pfd=tmp_pfd; for (u32 i=0; i<6; ++i) { if (i == 1) { if (Params.Stencilbuffer) { os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = false; pfd.cStencilBits = 0; } else continue; } else if (i == 2) { pfd.cDepthBits = 24; } else if (i == 3) { if (Params.Bits!=16) pfd.cDepthBits = 16; else continue; } else if (i == 4) { // try single buffer if (Params.Doublebuffer) pfd.dwFlags &= ~PFD_DOUBLEBUFFER; else continue; } else if (i == 5) { os::Printer::log("Cannot create a GL device context", "No suitable format for temporary window.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } // choose pixelformat PixelFormat = ChoosePixelFormat(HDc, &pfd); if (PixelFormat) break; } SetPixelFormat(HDc, PixelFormat, &pfd); os::Printer::log("Temporary context"); HGLRC hrc=wglCreateContext(HDc); if (!hrc) { os::Printer::log("Cannot create a temporary GL rendering context.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } CurrentContext.OpenGLWin32.HDc = HDc; CurrentContext.OpenGLWin32.HRc = hrc; CurrentContext.OpenGLWin32.HWnd = temporary_wnd; if (!activateContext(CurrentContext)) { os::Printer::log("Cannot activate a temporary GL rendering context.", ELL_ERROR); wglDeleteContext(hrc); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } core::stringc wglExtensions; #ifdef WGL_ARB_extensions_string PFNWGLGETEXTENSIONSSTRINGARBPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); if (irrGetExtensionsString) wglExtensions = irrGetExtensionsString(HDc); #elif defined(WGL_EXT_extensions_string) PFNWGLGETEXTENSIONSSTRINGEXTPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT"); if (irrGetExtensionsString) wglExtensions = irrGetExtensionsString(HDc); #endif const bool pixel_format_supported = (wglExtensions.find("WGL_ARB_pixel_format") != -1); const bool multi_sample_supported = ((wglExtensions.find("WGL_ARB_multisample") != -1) || (wglExtensions.find("WGL_EXT_multisample") != -1) || (wglExtensions.find("WGL_3DFX_multisample") != -1) ); #ifdef _DEBUG os::Printer::log("WGL_extensions", wglExtensions); #endif #ifdef WGL_ARB_pixel_format PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormat_ARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if (pixel_format_supported && wglChoosePixelFormat_ARB) { // This value determines the number of samples used for antialiasing // My experience is that 8 does not show a big // improvement over 4, but 4 shows a big improvement // over 2. if (Params.AntiAlias > 32) Params.AntiAlias = 32; f32 fAttributes[] = {0.0, 0.0}; s32 iAttributes[] = { WGL_DRAW_TO_WINDOW_ARB,1, WGL_SUPPORT_OPENGL_ARB,1, WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, WGL_COLOR_BITS_ARB,(Params.Bits==32) ? 24 : 15, WGL_ALPHA_BITS_ARB,(Params.Bits==32) ? 8 : 1, WGL_DEPTH_BITS_ARB,Params.ZBufferBits, // 10,11 WGL_STENCIL_BITS_ARB,Params.Stencilbuffer ? 1 : 0, WGL_DOUBLE_BUFFER_ARB,Params.Doublebuffer ? 1 : 0, WGL_STEREO_ARB,Params.Stereobuffer ? 1 : 0, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, #ifdef WGL_ARB_multisample WGL_SAMPLES_ARB,Params.AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_ARB, 1, #elif defined(WGL_EXT_multisample) WGL_SAMPLES_EXT,AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_EXT, 1, #elif defined(WGL_3DFX_multisample) WGL_SAMPLES_3DFX,AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_3DFX, 1, #endif #ifdef WGL_ARB_framebuffer_sRGB WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, Params.HandleSRGB ? 1:0, #elif defined(WGL_EXT_framebuffer_sRGB) WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT, Params.HandleSRGB ? 1:0, #endif // WGL_DEPTH_FLOAT_EXT, 1, 0,0,0,0 }; int iAttrSize = sizeof(iAttributes)/sizeof(int); const bool framebuffer_srgb_supported = ((wglExtensions.find("WGL_ARB_framebuffer_sRGB") != -1) || (wglExtensions.find("WGL_EXT_framebuffer_sRGB") != -1)); if (!framebuffer_srgb_supported) { memmove(&iAttributes[24],&iAttributes[26],sizeof(int)*(iAttrSize-26)); iAttrSize -= 2; } if (!multi_sample_supported) { memmove(&iAttributes[20],&iAttributes[24],sizeof(int)*(iAttrSize-24)); iAttrSize -= 4; } s32 rv=0; // Try to get an acceptable pixel format do { int pixelFormat=0; UINT numFormats=0; const BOOL valid = wglChoosePixelFormat_ARB(HDc,iAttributes,fAttributes,1,&pixelFormat,&numFormats); if (valid && numFormats) rv = pixelFormat; else iAttributes[21] -= 1; } while(rv==0 && iAttributes[21]>1); if (rv) { PixelFormat=rv; Params.AntiAlias=iAttributes[21]; } } else #endif Params.AntiAlias=0; // this only terminates the temporary HRc destroyContext(); destroySurface(); terminate(); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); // now get new window CurrentContext.OpenGLWin32.HWnd=videodata.OpenGLWin32.HWnd; // get hdc if (!(CurrentContext.OpenGLWin32.HDc=GetDC((HWND)videodata.OpenGLWin32.HWnd))) { os::Printer::log("Cannot create a GL device context.", ELL_ERROR); return false; } if (!PrimaryContext.OpenGLWin32.HWnd) { PrimaryContext.OpenGLWin32.HWnd=CurrentContext.OpenGLWin32.HWnd; PrimaryContext.OpenGLWin32.HDc=CurrentContext.OpenGLWin32.HDc; } return true; }
void OpenGLRenderer::Initialize() { // Initialize Internal Window PIXELFORMATDESCRIPTOR pfd; RECT rect = { 0, 0, 10, 10 }; WNDCLASSEX wcex; wcex.cbSize = sizeof ( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcex.lpfnWndProc = ( WNDPROC ) DefWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = GetModuleHandle ( nullptr ); wcex.hIcon = LoadIcon ( nullptr, IDI_WINLOGO ); wcex.hCursor = LoadCursor ( nullptr, IDC_ARROW ); wcex.hbrBackground = nullptr; wcex.lpszMenuName = nullptr; wcex.lpszClassName = "glUnitTest"; wcex.hIconSm = nullptr; ATOM atom = RegisterClassEx ( &wcex ); mWindowId = CreateWindowEx ( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, MAKEINTATOM ( atom ), "OpenGL Unit Testing Window", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, // Location rect.right - rect.left, rect.bottom - rect.top, // dimensions nullptr, nullptr, GetModuleHandle ( nullptr ), nullptr ); HDC hdc = GetDC ( static_cast<HWND> ( mWindowId ) ); pfd.nSize = sizeof ( PIXELFORMATDESCRIPTOR ); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cRedBits = 0; pfd.cRedShift = 0; pfd.cGreenBits = 0; pfd.cGreenShift = 0; pfd.cBlueBits = 0; pfd.cBlueShift = 0; pfd.cAlphaBits = 0; pfd.cAlphaShift = 0; pfd.cAccumBits = 0; pfd.cAccumRedBits = 0; pfd.cAccumGreenBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumAlphaBits = 0; pfd.cDepthBits = 32; pfd.cStencilBits = 0; pfd.cAuxBuffers = 0; pfd.iLayerType = PFD_MAIN_PLANE; pfd.bReserved = 0; pfd.dwLayerMask = 0; pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; int pf = ChoosePixelFormat ( hdc, &pfd ); SetPixelFormat ( hdc, pf, &pfd ); // Create OpenGL Context mOpenGLContext = wglCreateContext ( hdc ); wglMakeCurrent ( hdc, static_cast<HGLRC> ( mOpenGLContext ) ); // Get newer functions if needed if ( !wglGetExtensionsString ) { if ( ! ( wglGetExtensionsString = ( PFNWGLGETEXTENSIONSSTRINGARBPROC ) wglGetProcAddress ( "wglGetExtensionsStringARB" ) ) ) { wglMakeCurrent ( hdc, nullptr ); wglDeleteContext ( static_cast<HGLRC> ( mOpenGLContext ) ); mOpenGLContext = nullptr; ReleaseDC ( static_cast<HWND> ( mWindowId ), hdc ); DestroyWindow ( static_cast<HWND> ( mWindowId ) ); throw std::runtime_error ( "Failed retrieving a pointer to wglGetExtensionsString" ); } } if ( !wglCreateContextAttribs ) { if ( ! ( wglCreateContextAttribs = ( PFNWGLCREATECONTEXTATTRIBSARBPROC ) wglGetProcAddress ( "wglCreateContextAttribsARB" ) ) ) { wglMakeCurrent ( hdc, nullptr ); wglDeleteContext ( static_cast<HGLRC> ( mOpenGLContext ) ); mOpenGLContext = nullptr; ReleaseDC ( static_cast<HWND> ( mWindowId ), hdc ); DestroyWindow ( static_cast<HWND> ( mWindowId ) ); throw std::runtime_error ( "Failed retrieving a pointer to wglCreateContextAttribsARB" ); } } if ( strstr ( wglGetExtensionsString ( hdc ), "WGL_ARB_create_context" ) != nullptr ) { wglMakeCurrent ( hdc, nullptr ); wglDeleteContext ( static_cast<HGLRC> ( mOpenGLContext ) ); if ( ! ( mOpenGLContext = wglCreateContextAttribs ( hdc, nullptr /* change to use local context */, ContextAttribs ) ) ) { ReleaseDC ( static_cast<HWND> ( mWindowId ), hdc ); DestroyWindow ( static_cast<HWND> ( mWindowId ) ); throw std::runtime_error ( "wglCreateContextAttribs Failed" ); } } else { wglMakeCurrent ( hdc, nullptr ); wglDeleteContext ( static_cast<HGLRC> ( mOpenGLContext ) ); mOpenGLContext = nullptr; ReleaseDC ( static_cast<HWND> ( mWindowId ), hdc ); DestroyWindow ( static_cast<HWND> ( mWindowId ) ); throw std::runtime_error ( "WGL_ARB_create_context is not available" ); } // Get New OpenGL API if ( !wglMakeCurrent ( hdc, reinterpret_cast<HGLRC> ( mOpenGLContext ) ) ) { std::cout << "wglMakeCurrent Failed. Error: " << GetLastError() << std::endl; } if ( !LoadOpenGLAPI() ) { std::cout << "Unable to Load OpenGL functions." << std::endl; } glClearColor ( 0.5f, 0.5f, 0.5f, 0.0f ); OPENGL_CHECK_ERROR_NO_THROW; glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); OPENGL_CHECK_ERROR_NO_THROW; glEnable ( GL_BLEND ); OPENGL_CHECK_ERROR_NO_THROW; glDepthFunc ( GL_LESS ); OPENGL_CHECK_ERROR_NO_THROW; glEnable ( GL_DEPTH_TEST ); OPENGL_CHECK_ERROR_NO_THROW; glCullFace ( GL_BACK ); OPENGL_CHECK_ERROR_NO_THROW; glEnable ( GL_CULL_FACE ); OPENGL_CHECK_ERROR_NO_THROW; glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); OPENGL_CHECK_ERROR_NO_THROW; }
void GlContext::create(uint32_t /*_width*/, uint32_t /*_height*/) { m_opengl32dll = bx::dlopen("opengl32.dll"); BGFX_FATAL(NULL != m_opengl32dll, Fatal::UnableToInitialize, "Failed to load opengl32.dll."); wglGetProcAddress = (PFNWGLGETPROCADDRESSPROC)bx::dlsym(m_opengl32dll, "wglGetProcAddress"); BGFX_FATAL(NULL != wglGetProcAddress, Fatal::UnableToInitialize, "Failed get wglGetProcAddress."); // If g_bgfxHwnd is NULL, the assumption is that GL context was created // by user (for example, using SDL, GLFW, etc.) BX_WARN(NULL != g_bgfxHwnd , "bgfx::winSetHwnd with valid window is not called. This might " "be intentional when GL context is created by the user." ); if (NULL != g_bgfxHwnd) { wglMakeCurrent = (PFNWGLMAKECURRENTPROC)bx::dlsym(m_opengl32dll, "wglMakeCurrent"); BGFX_FATAL(NULL != wglMakeCurrent, Fatal::UnableToInitialize, "Failed get wglMakeCurrent."); wglCreateContext = (PFNWGLCREATECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglCreateContext"); BGFX_FATAL(NULL != wglCreateContext, Fatal::UnableToInitialize, "Failed get wglCreateContext."); wglDeleteContext = (PFNWGLDELETECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglDeleteContext"); BGFX_FATAL(NULL != wglDeleteContext, Fatal::UnableToInitialize, "Failed get wglDeleteContext."); m_hdc = GetDC(g_bgfxHwnd); BGFX_FATAL(NULL != m_hdc, Fatal::UnableToInitialize, "GetDC failed!"); // Dummy window to peek into WGL functionality. // // An application can only set the pixel format of a window one time. // Once a window's pixel format is set, it cannot be changed. // MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/dd369049%28v=vs.85%29.aspx HWND hwnd = CreateWindowA("STATIC" , "" , WS_POPUP|WS_DISABLED , -32000 , -32000 , 0 , 0 , NULL , NULL , GetModuleHandle(NULL) , 0 ); HDC hdc = GetDC(hwnd); BGFX_FATAL(NULL != hdc, Fatal::UnableToInitialize, "GetDC failed!"); HGLRC context = createContext(hdc); wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (NULL != wglGetExtensionsStringARB) { const char* extensions = (const char*)wglGetExtensionsStringARB(hdc); BX_TRACE("WGL extensions:"); dumpExtensions(extensions); } if (NULL != wglChoosePixelFormatARB && NULL != wglCreateContextAttribsARB) { int32_t attrs[] = { WGL_SAMPLE_BUFFERS_ARB, 0, WGL_SAMPLES_ARB, 0, WGL_SUPPORT_OPENGL_ARB, true, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_DRAW_TO_WINDOW_ARB, true, WGL_DOUBLE_BUFFER_ARB, true, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0 }; int result; uint32_t numFormats = 0; do { result = wglChoosePixelFormatARB(m_hdc, attrs, NULL, 1, &m_pixelFormat, &numFormats); if (0 == result || 0 == numFormats) { attrs[3] >>= 1; attrs[1] = attrs[3] == 0 ? 0 : 1; } } while (0 == numFormats); DescribePixelFormat(m_hdc, m_pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &m_pfd); BX_TRACE("Pixel format:\n" "\tiPixelType %d\n" "\tcColorBits %d\n" "\tcAlphaBits %d\n" "\tcDepthBits %d\n" "\tcStencilBits %d\n" , m_pfd.iPixelType , m_pfd.cColorBits , m_pfd.cAlphaBits , m_pfd.cDepthBits , m_pfd.cStencilBits ); result = SetPixelFormat(m_hdc, m_pixelFormat, &m_pfd); // When window is created by SDL and SDL_WINDOW_OPENGL is set SetPixelFormat // will fail. Just warn and continue. In case it failed for some other reason // create context will fail and it will error out there. BX_WARN(result, "SetPixelFormat failed (last err: 0x%08x)!", GetLastError() ); uint32_t flags = BGFX_CONFIG_DEBUG ? WGL_CONTEXT_DEBUG_BIT_ARB : 0; BX_UNUSED(flags); int32_t contextAttrs[9] = { #if BGFX_CONFIG_RENDERER_OPENGL >= 31 WGL_CONTEXT_MAJOR_VERSION_ARB, BGFX_CONFIG_RENDERER_OPENGL / 10, WGL_CONTEXT_MINOR_VERSION_ARB, BGFX_CONFIG_RENDERER_OPENGL % 10, WGL_CONTEXT_FLAGS_ARB, flags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, #else WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 1, 0, 0, 0, 0, #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31 0 }; m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs); if (NULL == m_context) { // nVidia doesn't like context profile mask for contexts below 3.2? contextAttrs[6] = WGL_CONTEXT_PROFILE_MASK_ARB == contextAttrs[6] ? 0 : contextAttrs[6]; m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs); } BGFX_FATAL(NULL != m_context, Fatal::UnableToInitialize, "Failed to create context 0x%08x.", GetLastError() ); BX_STATIC_ASSERT(sizeof(contextAttrs) == sizeof(m_contextAttrs) ); memcpy(m_contextAttrs, contextAttrs, sizeof(contextAttrs) ); }
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { RECT Screen; // используется позднее для размеров окна GLuint PixelFormat; static PIXELFORMATDESCRIPTOR pfd= { sizeof(PIXELFORMATDESCRIPTOR), // Размер этой структуры 1, // Номер версии (?) PFD_DRAW_TO_WINDOW |// Формат для Окна PFD_SUPPORT_OPENGL |// Формат для OpenGL PFD_DOUBLEBUFFER,// Формат для двойного буфера PFD_TYPE_RGBA, // Требуется RGBA формат 16, // Выбор 16 бит глубины цвета 0, 0, 0, 0, 0, 0,// Игнорирование цветовых битов (?) 0, // нет буфера прозрачности 0, // Сдвиговый бит игнорируется (?) 0, // Нет буфера аккумуляции 0, 0, 0, 0, // Биты аккумуляции игнорируются (?) 16, // 16 битный Z-буфер (буфер глубины) 0, // Нет буфера траффарета 0, // Нет вспомогательных буферов (?) PFD_MAIN_PLANE, // Главный слой рисования 0, // Резерв (?) 0, 0, 0 // Маски слоя игнорируются (?) }; switch (message) // Тип сообщения { case WM_CREATE: hDC = GetDC(hWnd); // Получить контекст устройства для окна PixelFormat = ChoosePixelFormat(hDC, &pfd); // Найти ближайшее совпадение для нашего формата пикселов if (!PixelFormat) { MessageBox(0,"Can't Find A Suitable PixelFormat.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); // Это сообщение говорит, что программа должна завершится break; // Предтовращение повтора кода } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) { MessageBox(0,"Can't Set The PixelFormat.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } hRC = wglCreateContext(hDC); if(!hRC) { MessageBox(0,"Can't Create A GL Rendering Context.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } if(!wglMakeCurrent(hDC, hRC)) { MessageBox(0,"Can't activate GLRC.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } GetClientRect(hWnd, &Screen); InitGL(Screen.right, Screen.bottom); break; case WM_DESTROY: case WM_CLOSE: ChangeDisplaySettings(NULL, 0); wglMakeCurrent(hDC,NULL); wglDeleteContext(hRC); ReleaseDC(hWnd,hDC); PostQuitMessage(0); break; case WM_KEYDOWN: keys[wParam] = TRUE; break; case WM_KEYUP: keys[wParam] = FALSE; break; case WM_SIZE: ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); break; default: return (DefWindowProc(hWnd, message, wParam, lParam)); } return (0); }
static bool select_pixel_format(ALLEGRO_DISPLAY_WGL *d, HDC dc) { ALLEGRO_EXTRA_DISPLAY_SETTINGS **eds = NULL; ALLEGRO_SYSTEM *system = (void *)al_get_system_driver(); int eds_count = 0; int i; bool force_old = false; if (system->config) { const char *selection_mode; selection_mode = al_get_config_value(system->config, "graphics", "config_selection"); if (selection_mode && selection_mode[0] != '\0') { if (!_al_stricmp(selection_mode, "old")) { ALLEGRO_INFO("Forcing OLD visual selection method.\n"); force_old = true; } else if (!_al_stricmp(selection_mode, "new")) force_old = false; } } if (!force_old) eds = get_available_pixel_formats_ext(&eds_count); if (!eds) eds = get_available_pixel_formats_old(&eds_count, dc); if (!eds || !eds_count) { ALLEGRO_ERROR("Didn't find any suitable pixel format!\n"); return false; } qsort(eds, eds_count, sizeof(eds[0]), _al_display_settings_sorter); for (i = 0; i < eds_count ; i++) { if (SetPixelFormat(d->dc, eds[i]->index, NULL)) { ALLEGRO_INFO("Chose visual no. %i\n\n", eds[i]->index); display_pixel_format(eds[i]); break; } else { ALLEGRO_WARN("Unable to set pixel format! %s\n", get_error_desc(GetLastError())); ALLEGRO_WARN("Trying next one.\n"); } } if (i == eds_count) { ALLEGRO_ERROR("Unable to set any pixel format! %s\n", get_error_desc(GetLastError())); for (i = 0; i < eds_count; i++) al_free(eds[i]); al_free(eds); return false; } memcpy(&d->win_display.display.extra_settings, eds[i], sizeof(ALLEGRO_EXTRA_DISPLAY_SETTINGS)); for (i = 0; i < eds_count; i++) al_free(eds[i]); if (eds) al_free(eds); return true; }
bool CreateGLWindow(char* title, int width, int height) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height 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 = (WNDPROC) WndProc; // 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 = "OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 900, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); 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 24, // 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 24, // 24Bit 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? { KillGLWindow(); // Reset The Display 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? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return false; // Return FALSE } ShowWindow(hWnd,SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window reshape(width, height); // Set Up Our Perspective GL Screen init(); return true; // Success }
void InitWindow(HINSTANCE hInstance) { // TODO: make it search all available configs and ask what to load from or something if(!cfg.LoadFromFile("default.cfg")) LogToFile("debug.log", "Failed to load config"); window_rect.left = 0; window_rect.right = cfg.scr_width; window_rect.top = 0; window_rect.bottom = cfg.scr_height; window_class.hInstance = hInstance; window_class.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC; window_class.lpfnWndProc = WndProc; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hbrBackground = NULL; window_class.hIcon = LoadIcon(NULL, IDI_WINLOGO); window_class.hCursor = LoadCursor(NULL, IDC_ARROW); window_class.lpszMenuName = NULL; window_class.lpszClassName = "OpenOrionClass"; fullscreenflag = cfg.fullscreen; if(!RegisterClass(&window_class)) { MessageBox(NULL, "Failed to register window class", "RegisterClass() Error", MB_OK | MB_ICONEXCLAMATION); LogToFile("debug.log", "Failed to register window class"); PostQuitMessage(-1); } if(cfg.fullscreen) { memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Очистка для хранения установок dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Размер структуры Devmode dmScreenSettings.dmPelsWidth = cfg.scr_width; // Ширина экрана dmScreenSettings.dmPelsHeight = cfg.scr_height; // Высота экрана dmScreenSettings.dmBitsPerPel = cfg.scr_bpp; // Глубина цвета dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Режим Пикселя DWORD disp; disp = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); switch(disp) { case DISP_CHANGE_SUCCESSFUL: { fullscreenflag = true; ShowCursor(true); break; } case DISP_CHANGE_BADDUALVIEW: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADDUALVIEW)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADDUALVIEW", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADFLAGS: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADFLAGS)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADFLAGS", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADMODE: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADMODE)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADMODE", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADPARAM: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADPARAM)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADPARAM", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_FAILED: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_FAILED)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_FAILED", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_NOTUPDATED: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_NOTUPDATED)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_NOTUPDATED", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_RESTART: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_RESTART)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_RESTART", MB_OK | MB_ICONEXCLAMATION); break; } } } if(fullscreenflag) { dwExStyle = WS_EX_APPWINDOW; //dwStyle = WS_OVERLAPPED; dwStyle = WS_POPUP; } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPED; } AdjustWindowRectEx(&window_rect, dwStyle, false, dwExStyle); game_window = CreateWindowEx(dwExStyle, window_class.lpszClassName, GAMENAME, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | dwStyle, GetSystemMetrics(0) - GetSystemMetrics(0)/2 - window_rect.right / 2, GetSystemMetrics(1) - GetSystemMetrics(1)/2 - window_rect.bottom / 2, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, NULL, NULL, hInstance, NULL); if(!game_window) { LogToFile("debug.log","Failed to create game window"); MessageBox(NULL, "Failed to create game window", "CreateWindowEx() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cDepthBits = 24; pfd.iLayerType = PFD_MAIN_PLANE; pfd.cColorBits = cfg.scr_bpp; hDC = GetDC(game_window); if(!hDC) { LogToFile("debug.log","Failed to create device context"); MessageBox(NULL, "Failed to create device context", "GetDC() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } pf = ChoosePixelFormat(hDC, &pfd); if(!pf) { LogToFile("debug.log","Failed to choose pixel format"); MessageBox(NULL, "Failed to set pixel format", "ChoosePixelFormat() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } if(!SetPixelFormat(hDC, pf, &pfd)) { LogToFile("debug.log","Failed to set pixel format"); MessageBox(NULL, "Failed to set pixel format", "SetPixelFormat() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } hRC = wglCreateContext(hDC); if(!hRC) { LogToFile("debug.log","Failed to create rendering context"); MessageBox(NULL, "Failed to create rendering context", "wglCreateContext() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } if(!wglMakeCurrent(hDC, hRC)) { LogToFile("debug.log","Failed to make current context"); MessageBox(NULL, "Failed to make current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } ShowWindow(game_window, SW_SHOW); SetForegroundWindow(game_window); SetFocus(game_window); }
//-------------------------------------------------------------------------------------- // Initialize drawing API //-------------------------------------------------------------------------------------- HRESULT InitBackend(HWND hWnd) { if (!(g_hDC = GetDC(hWnd))) { printf("Error: Device fail.\n"); return E_FAIL; } int format; static PIXELFORMATDESCRIPTOR pfd = { 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 }; if (!(format = ChoosePixelFormat(g_hDC, &pfd))) { printf("Error: PixelFormat fail.\n"); return E_FAIL; } if (!SetPixelFormat(g_hDC, format, &pfd)) { printf("Error: PixelFormat not set.\n"); return E_FAIL; } if (!(g_hRC = wglCreateContext(g_hDC))) { printf("Error: Context not creted.\n"); return E_FAIL; } if (!wglMakeCurrent(g_hDC, g_hRC)) { printf("Error: Context not set.\n"); return E_FAIL; } // initialize glew GLenum res = glewInit(); if (res != GLEW_OK) { printf("Error: GLEW fail.\n"); return E_FAIL; } return S_OK; }
BOOL CreateWindowGL (GL_Window* window) // This Code Creates Our OpenGL Window { DWORD windowStyle = WS_OVERLAPPEDWINDOW; // Define Our Window Style DWORD windowExtendedStyle = WS_EX_APPWINDOW; // Define The Window's Extended Style 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 window->init.bitsPerPixel, // 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 }; RECT windowRect = {0, 0, window->init.width, window->init.height}; // Define Our Window Coordinates GLuint PixelFormat; // Will Hold The Selected Pixel Format if (window->init.isFullScreen == TRUE) // Fullscreen Requested, Try Changing Video Modes { if (ChangeScreenResolution (window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE) { // Fullscreen Mode Failed. Run In Windowed Mode Instead MessageBox (HWND_DESKTOP, "Mode Switch Failed.\nRunning In Windowed Mode.", "Error", MB_OK | MB_ICONEXCLAMATION); window->init.isFullScreen = FALSE; // Set isFullscreen To False (Windowed Mode) } else // Otherwise (If Fullscreen Mode Was Successful) { ShowCursor (FALSE); // Turn Off The Cursor windowStyle = WS_POPUP; // Set The WindowStyle To WS_POPUP (Popup Window) windowExtendedStyle |= WS_EX_TOPMOST; // Set The Extended Window Style To WS_EX_TOPMOST } // (Top Window Covering Everything Else) } else // If Fullscreen Was Not Selected { // Adjust Window, Account For Window Borders AdjustWindowRectEx (&windowRect, windowStyle, 0, windowExtendedStyle); } // Create The OpenGL Window window->hWnd = CreateWindowEx (windowExtendedStyle, // Extended Style window->init.application->className, // Class Name window->init.title, // Window Title windowStyle, // Window Style 0, 0, // Window X,Y Position windowRect.right - windowRect.left, // Window Width windowRect.bottom - windowRect.top, // Window Height HWND_DESKTOP, // Desktop Is Window's Parent 0, // No Menu window->init.application->hInstance, // Pass The Window Instance window); if (window->hWnd == 0) // Was Window Creation A Success? { return FALSE; // If Not Return False } window->hDC = GetDC (window->hWnd); // Grab A Device Context For This Window if (window->hDC == 0) // Did We Get A Device Context? { // Failed DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } PixelFormat = ChoosePixelFormat (window->hDC, &pfd); // Find A Compatible Pixel Format if (PixelFormat == 0) // Did We Find A Compatible Format? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } if (SetPixelFormat (window->hDC, PixelFormat, &pfd) == FALSE) // Try To Set The Pixel Format { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } window->hRC = wglCreateContext (window->hDC); // Try To Get A Rendering Context if (window->hRC == 0) // Did We Get A Rendering Context? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent (window->hDC, window->hRC) == FALSE) { // Failed wglDeleteContext (window->hRC); // Delete The Rendering Context window->hRC = 0; // Zero The Rendering Context ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } ShowWindow (window->hWnd, SW_NORMAL); // Make The Window Visible window->isVisible = TRUE; // Set isVisible To True ReshapeGL (window->init.width, window->init.height); // Reshape Our GL Window ZeroMemory (window->keys, sizeof (Keys)); // Clear All Keys window->lastTickCount = GetTickCount (); // Get Tick Count return TRUE; // Window Creating Was A Success // Initialization Will Be Done In WM_CREATE }
BOOL CreateGLWindow(HWND hWnd, HDC *phDC, HGLRC *phRC) { GLuint nPixelFormat; // Holds The Results After Searching For A Match RECT rect; 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 0, // 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 0, // 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 (!(*phDC = GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Create A GL Device Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(nPixelFormat = ChoosePixelFormat(*phDC, &pfd)))// Did Windows Find A Matching Pixel Format? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Find A Suitable PixelFormat."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!SetPixelFormat(*phDC, nPixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Set The PixelFormat."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(*phRC = wglCreateContext(*phDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Create A GL Rendering Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!wglMakeCurrent(*phDC, *phRC)) // Try To Activate The Rendering Context { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Activate The GL Rendering Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } GetClientRect(hWnd, &rect); ReSizeGLScene(rect.right, rect.bottom); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Initialization Failed."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
/* ** GLW_MakeContext */ static int GLW_MakeContext( PIXELFORMATDESCRIPTOR *pPFD ) { int pixelformat; // // don't putz around with pixelformat if it's already set (e.g. this is a soft // reset of the graphics system) // if ( !glw_state.pixelFormatSet ) { // // choose, set, and describe our desired pixel format. If we're // using a minidriver then we need to bypass the GDI functions, // otherwise use the GDI functions. // if ( ( pixelformat = GLW_ChoosePFD( glw_state.hDC, pPFD ) ) == 0 ) { ri.Printf( PRINT_ALL, "...GLW_ChoosePFD failed\n" ); return TRY_PFD_FAIL_SOFT; } ri.Printf( PRINT_ALL, "...PIXELFORMAT %d selected\n", pixelformat ); if ( glConfig.driverType > GLDRV_ICD ) { qwglDescribePixelFormat( glw_state.hDC, pixelformat, sizeof( *pPFD ), pPFD ); if ( qwglSetPixelFormat( glw_state.hDC, pixelformat, pPFD ) == FALSE ) { ri.Printf( PRINT_ALL, "...qwglSetPixelFormat failed\n" ); return TRY_PFD_FAIL_SOFT; } } else { DescribePixelFormat( glw_state.hDC, pixelformat, sizeof( *pPFD ), pPFD ); if ( SetPixelFormat( glw_state.hDC, pixelformat, pPFD ) == FALSE ) { ri.Printf( PRINT_ALL, "...SetPixelFormat failed\n", glw_state.hDC ); return TRY_PFD_FAIL_SOFT; } } glw_state.pixelFormatSet = qtrue; } // // startup the OpenGL subsystem by creating a context and making it current // if ( !glw_state.hGLRC ) { ri.Printf( PRINT_ALL, "...creating GL context: " ); if ( ( glw_state.hGLRC = qwglCreateContext( glw_state.hDC ) ) == 0 ) { ri.Printf( PRINT_ALL, "failed\n" ); return TRY_PFD_FAIL_HARD; } ri.Printf( PRINT_ALL, "succeeded\n" ); ri.Printf( PRINT_ALL, "...making context current: " ); if ( !qwglMakeCurrent( glw_state.hDC, glw_state.hGLRC ) ) { qwglDeleteContext( glw_state.hGLRC ); glw_state.hGLRC = NULL; ri.Printf( PRINT_ALL, "failed\n" ); return TRY_PFD_FAIL_HARD; } ri.Printf( PRINT_ALL, "succeeded\n" ); } return TRY_PFD_SUCCESS; }
const GrGLInterface* SkNativeGLContext::createGLContext() { HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL); if (!gWC) { WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hInstance = hInstance; wc.lpfnWndProc = (WNDPROC) DefWindowProc; wc.lpszClassName = TEXT("Griffin"); wc.lpszMenuName = NULL; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; gWC = RegisterClass(&wc); if (!gWC) { SkDebugf("Could not register window class.\n"); return NULL; } } if (!(fWindow = CreateWindow(TEXT("Griffin"), TEXT("The Invisible Man"), WS_OVERLAPPEDWINDOW, 0, 0, 1, 1, NULL, NULL, hInstance, NULL))) { SkDebugf("Could not create window.\n"); return NULL; } if (!(fDeviceContext = GetDC(fWindow))) { SkDebugf("Could not get device context.\n"); this->destroyGLContext(); return NULL; } PIXELFORMATDESCRIPTOR pfd; ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_SUPPORT_OPENGL; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 0; pfd.cStencilBits = 0; pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormat = 0; if (!(pixelFormat = ChoosePixelFormat(fDeviceContext, &pfd))) { SkDebugf("No matching pixel format descriptor.\n"); this->destroyGLContext(); return NULL; } if (!SetPixelFormat(fDeviceContext, pixelFormat, &pfd)) { SkDebugf("Could not set the pixel format %d.\n", pixelFormat); this->destroyGLContext(); return NULL; } if (!(fGlRenderContext = wglCreateContext(fDeviceContext))) { SkDebugf("Could not create rendering context.\n"); this->destroyGLContext(); return NULL; } if (!(wglMakeCurrent(fDeviceContext, fGlRenderContext))) { SkDebugf("Could not set the context.\n"); this->destroyGLContext(); return NULL; } const GrGLInterface* interface = GrGLCreateNativeInterface(); if (NULL == interface) { SkDebugf("Could not create GL interface.\n"); this->destroyGLContext(); return NULL; } return interface; }
/** * Sets the window to use an OpenGL drawing context. * @return Returns an error if something goes wrong when setting the drawing state. */ int Window::setWindowDrawingStateGL() { // Create a variable for storing the pixel format of the window. int pixelFormat; // Setup the pixel format descriptor. static PIXELFORMATDESCRIPTOR pixelFormatDesc = { // Set the size of the descriptor. sizeof(PIXELFORMATDESCRIPTOR), 1, // Set the properties to draw to a window, support OpenGL, and be double buffered. PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Set the window to have the normal RGB spectrum, as well as an alpha value. PFD_TYPE_RGBA, // Set the bits per pixel to the desired value. this->bitsPerPixel, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; // Attempt to get a device context from the window handle. if (!(deviceContext = GetDC(windowHandle))) { // If getting device context from the window fails, destroy the OpenGL system and the window. this->destroyGLSystem(); this->destroy(); #ifdef _DEBUG // If debugging, display an error indicating that the device context couldn't be gotten. MessageBox(NULL, (LPCWSTR)L"Error getting device context!", (LPCWSTR)L"Create GL Context ERROR", MB_OK | MB_ICONERROR); #else // If not debugging, a clean error is displayed to the user so they can report the issue. MessageBox(NULL, (LPCWSTR)L"Error starting application!\nError code: WCGL" + WCGL_GET_CONTEXT_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR); #endif // Return an error indicating that the device context couldn't be gotten. return WCGL_GET_CONTEXT_ERROR; } // Attempt to get the pixel format. if (!(pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDesc))) { // If this failed, destroy the OpenGL system. this->destroyGLSystem(); // Also destroy the window. this->destroy(); #ifdef _DEBUG // If debugging, display that there was an error finding a usable pixel format. MessageBox(NULL, (LPCWSTR)L"Error finding a usable pixel format!", (LPCWSTR)L"Create GL Context ERROR", MB_OK | MB_ICONERROR); #else // If not debugging, a clean error is displayed to the user so they can report the issue. MessageBox(NULL, (LPCWSTR)L"Error starting application!\nError code: WCGL" + WCGL_GET_PF_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR); #endif // Return an error indicating that the pixel format couldn't be gotten. return WCGL_GET_PF_ERROR; } // Try to set the pixel format for the device context. if (!SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDesc)) { // If this failed, destroy the OpenGL system. this->destroyGLSystem(); // Also destroy the window. this->destroy(); #ifdef _DEBUG // If debugging, display an error indicating that the pixel format couldn't be set. MessageBox(NULL, (LPCWSTR)L"Error setting pixel format!", (LPCWSTR)L"Create GL Context ERROR", MB_OK | MB_ICONERROR); #else // If not debugging, a clean error is displayed to the user so they can report the issue. MessageBox(NULL, (LPCWSTR)L"Error starting application!\nError code: WCGL" + WCGL_SET_PF_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR); #endif // Return an error indicating that the pixel format couldn't be set. return WCGL_SET_PF_ERROR; } // Attempt to create an OpenGL context and store it. if (!(renderingContext = wglCreateContext(deviceContext))) { // If this failed, destroy the OpenGL system. this->destroyGLSystem(); // Also destroy the window. this->destroy(); #ifdef _DEBUG // Display an error indicating what happened if debuging. MessageBox(NULL, (LPCWSTR)L"Error creating rendering context!", (LPCWSTR)L"Create GL Context ERROR", MB_OK | MB_ICONERROR); #else // If not debugging, a clean error is displayed to the user so they can report the issue. MessageBox(NULL, (LPCWSTR)L"Error starting application!\nError code: WCGL" + WCGL_CREATE_CONTEXT_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR); #endif // Return an error indicating that the OpenGL context couldn't be created. return WCGL_CREATE_CONTEXT_ERROR; } // Try to set the current OpenGL context. if (!wglMakeCurrent(deviceContext, renderingContext)) { // If this failed, destroy the OpenGL system. this->destroyGLSystem(); // Also destroy the window. this->destroy(); #ifdef _DEBUG // If debugging, display an error indicating that the current context couldn't be set. MessageBox(NULL, (LPCWSTR)L"Error making rendering context the current one!", (LPCWSTR)L"Create GL Context ERROR", MB_OK | MB_ICONERROR); #else // If not debugging, a clean error is displayed to the user so they can report the issue. MessageBox(NULL, (LPCWSTR)L"Error starting application!\nError code: WCGL" + WCGL_SET_CONTEXT_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR); #endif /** * Return an error indicating that the OpenGL context couldn't be set. */ return WCGL_SET_CONTEXT_ERROR; } return OK; }
//------------------------------------------------------------------------------ // Static bool GLContextImpl::setPixelFormat(HWND hwnd, GLContextSettings & settings) { ensureGLExtensions(); HDC hdc = GetDC(hwnd); //HGLRC hrc = nullptr; u32 bitsPerPixel = 32; // Let's find a suitable pixel format -- first try with antialiasing int bestFormat = 0; if (settings.multiSampleLevel > 0) { // Get the wglChoosePixelFormatARB function (it is an extension) //PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB")); if (wglChoosePixelFormatARB) { // Define the basic attributes we want for our window int intAttributes[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_SAMPLE_BUFFERS_ARB, (settings.multiSampleLevel ? GL_TRUE : GL_FALSE), WGL_SAMPLES_ARB, settings.multiSampleLevel, 0, 0 }; // Let's check how many formats are supporting our requirements int formats[128]; UINT nbFormats; float floatAttributes[] = { 0, 0 }; bool isValid = wglChoosePixelFormatARB(hdc, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0; while ((!isValid || (nbFormats == 0)) && settings.multiSampleLevel > 0) { // Decrease the antialiasing level until we find a valid one --settings.multiSampleLevel; intAttributes[11] = settings.multiSampleLevel; isValid = wglChoosePixelFormatARB(hdc, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0; } // Get the best format among the returned ones if (isValid && (nbFormats > 0)) { int bestScore = 0xFFFF; for (UINT i = 0; i < nbFormats; ++i) { // Get the current format's attributes PIXELFORMATDESCRIPTOR attributes; attributes.nSize = sizeof(attributes); attributes.nVersion = 1; DescribePixelFormat(hdc, formats[i], sizeof(attributes), &attributes); // Evaluate the current configuration int color = attributes.cRedBits + attributes.cGreenBits + attributes.cBlueBits + attributes.cAlphaBits; int score = settings.evaluate(bitsPerPixel, color, attributes.cDepthBits, attributes.cStencilBits, settings.multiSampleLevel); // Keep it if it's better than the current best if (score < bestScore) { bestScore = score; bestFormat = formats[i]; } } } } else { // wglChoosePixelFormatARB not supported ; disabling antialiasing SN_WARNING("Antialiasing is not supported ; it will be disabled"); settings.multiSampleLevel = 0; } } // Find a pixel format with no antialiasing, if not needed or not supported if (bestFormat == 0) { // Setup a pixel format descriptor from the rendering settings PIXELFORMATDESCRIPTOR descriptor; ZeroMemory(&descriptor, sizeof(descriptor)); descriptor.nSize = sizeof(descriptor); descriptor.nVersion = 1; descriptor.iLayerType = PFD_MAIN_PLANE; descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; descriptor.iPixelType = PFD_TYPE_RGBA; descriptor.cColorBits = static_cast<BYTE>(bitsPerPixel); descriptor.cDepthBits = static_cast<BYTE>(settings.depthBits); descriptor.cStencilBits = static_cast<BYTE>(settings.stencilBits); descriptor.cAlphaBits = bitsPerPixel == 32 ? 8 : 0; // Get the pixel format that best matches our requirements bestFormat = ChoosePixelFormat(hdc, &descriptor); if (bestFormat == 0) { SN_ERROR("Failed to find a suitable pixel format for device context -- cannot create OpenGL context"); ReleaseDC(hwnd, hdc); return false; } } // Extract the depth and stencil bits from the chosen format PIXELFORMATDESCRIPTOR actualFormat; actualFormat.nSize = sizeof(actualFormat); actualFormat.nVersion = 1; DescribePixelFormat(hdc, bestFormat, sizeof(actualFormat), &actualFormat); settings.depthBits = actualFormat.cDepthBits; settings.stencilBits = actualFormat.cStencilBits; // Set the chosen pixel format if (!SetPixelFormat(hdc, bestFormat, &actualFormat)) { SN_ERROR("Failed to set pixel format for device context -- cannot create OpenGL context"); return false; } ReleaseDC(hwnd, hdc); return true; }
/* This Code Creates Our OpenGL Window. Parameters Are: * * title - Title To Appear At The Top Of The Window * * width - Width Of The GL Window Or Full screen Mode * * height - Height Of The GL Window Or Full screen Mode * * bits - Number Of Bits To Use For Color (8/16/24/32) * * fullscreenflag - Use Full screen Mode (TRUE) Or Windowed Mode (FALSE) */ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullScreenFlag) { GLuint PixelFormat; // Holds the results after searching for a match WNDCLASS wc; // Windows class structure DWORD dwExStyle; // Window extended style DWORD dwStyle; // Window style RECT WindowRect; // Grabs rectangle upper left/lower right values WindowRect.left = (long)0; // Set left value to 0 WindowRect.right = (long)width; // Set right value to requested width WindowRect.top = (long)0; // Set top value to 0 WindowRect.bottom = (long)height; // Set bottom value to requested height g_bFullscreen = fullScreenFlag; // Set the global full screen flag hInstance = GetModuleHandle(NULL); // Grab an instance for out window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw on size, and own DC for window wc.lpfnWndProc = (WNDPROC)WndProc; // 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 = CLASSNAME; // Set the class name if (!RegisterClass(&wc)) // Attempt to register the window class { MessageBox(NULL, MSG_REGISTERCLASSFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (g_bFullscreen) { 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 = width; // Selected screen width dmScreenSettings.dmPelsHeight = height; // Selected screen height dmScreenSettings.dmBitsPerPel = bits; // 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 failed, offer two options. Quit or use windowed mode. if (MessageBox(NULL, MSG_FULLSCREENNOTSUPPORT, ARTIST_NAME, MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { g_bFullscreen = FALSE; // Windowed mode selected. Fullscreen = FALSE } else { // Pop up a message box letting user know the program is closing. MessageBox(NULL, MSG_PROGRAMNOTCLOSE, ERR_ERROR, MB_OK | MB_ICONSTOP); return FALSE; // Return FALSE } } } if (g_bFullscreen) // Are we still in fullscreen mode? { dwExStyle = WS_EX_APPWINDOW; // Window extended style dwStyle = WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide mouse pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Windows Extended style dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust window to true requested size // Create the window if (!(hWnd = CreateWindowEx(dwExStyle, // Extended style for the window CLASSNAME, // Class name title, // Window title dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // Defined window style 0, 0, // Window position WindowRect.right - WindowRect.left, // Calculate window width WindowRect.bottom - WindowRect.top, // Calculate window height NULL, // No parent window NULL, // No menu hInstance, // Instance NULL))) // Don't pass anything to WM_CREATE { KillGLWindow(); // Reset the display MessageBox(NULL, MSG_CREATEWINDOWFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd = // pfd tells widows how we want things to be { sizeof(PIXELFORMATDESCRIPTOR), // Size of this pixel format descriptor 1, // Version number PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Format must support window/opengl/double buffering PFD_TYPE_RGBA, // Request an RGBA format bits, // 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 DEPTHBUFFER, // 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 { KillGLWindow(); // Reset the display MessageBox(NULL, MSG_CREATEGLDCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_FINDPIXELFORMATFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_SETPIXELFORMATFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_CREATEGLRCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_ACTIVEGLRCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); 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(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_INITFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
/** 创建windows窗口 */ bool GLWindow::Create(const char * window_title,const char * class_name, HINSTANCE h_instance, LPVOID lpParam) { int nX=0; int nY=0; PIXELFORMATDESCRIPTOR pfd = /**< 设置像素描述结构 */ { sizeof(PIXELFORMATDESCRIPTOR), /**< 像素描述结构的大小 */ 1, /**< 版本号 */ PFD_DRAW_TO_WINDOW | /**< 缓存区的输出显示在一个窗口中 */ PFD_SUPPORT_OPENGL | /**< 缓存区支持OpenGL绘图 */ PFD_STEREO | /**< 颜色缓存区是立体缓存 */ PFD_DOUBLEBUFFER, /**< 颜色缓存区是双缓存 */ PFD_TYPE_RGBA, /**< 使用RGBA颜色格式 */ m_BitsPerPixel, /**< 颜色缓存区中颜色值所占的位深 */ 0, 0, 0, 0, 0, 0, /**< 使用默认的颜色设置 */ 0, /**< 无Alpha缓存 */ 0, /**< 颜色缓存区中alpha成分的移位计数 */ 0, /**< 无累计缓存区 */ 0, 0, 0, 0, /**< 累计缓存区无移位 */ 32, /**< 32位深度缓存 */ 0, /**< 无蒙版缓存 */ 0, /**< 无辅助缓存区 */ PFD_MAIN_PLANE, /**< 必须为PFD_MAIN_PLANE,设置为主绘图层 */ 0, /**< 表示OpenGL实现所支持的上层或下层平面的数量 */ 0, 0, 0 /**< 过时,已不再使用 */ }; DWORD windowStyle = WS_TILEDWINDOW ; /**< 定义我们窗口类型,使用常规设定 */ DWORD windowExtendedStyle = WS_EX_APPWINDOW; if (m_IsFullScreen == true) /**< 如果为全屏模式,尝试转化为全屏模式 */ { if (ChangeScreenSetting() == false) { /**< 全屏模式转换失败,弹出对话框提示,并尝试窗口模式 */ MessageBox(HWND_DESKTOP, "模式转换失败.\n在窗口模式下运行.", "Error", MB_OK | MB_ICONEXCLAMATION); m_IsFullScreen = false; /**< 设置为窗口模式 */ } else /**< 如果为窗口模式 */ { ShowCursor(false); /**< 隐藏鼠标 */ windowStyle = WS_POPUP; /**< 设置窗口模式为顶层窗口 */ windowExtendedStyle |= WS_EX_TOPMOST; } } /// 调整我们窗口的大小,使其客户区的大小为我们设置的大小 RECT windowRect = {GetPosX(), GetPosY(), GetPosX() + GetWidth(), GetPosY() + GetHeight()}; if (m_IsFullScreen == false) /**< 在窗口模式下使用 */ { windowExtendedStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; /**< 使窗口具有3D外观 */ int wid = GetSystemMetrics(SM_CXSCREEN); /**< 获取当前屏幕宽 */ int hei = GetSystemMetrics(SM_CYSCREEN); /**< 获取当前屏幕高 */ nX = (wid - GetWidth()) / 2; /**< 计算窗口居中用 */ nY = (hei - GetHeight()) / 2; /// 调整我们窗口的大小,使其客户区的大小为我们设置的大小 AdjustWindowRectEx(&windowRect, windowStyle, 0, windowExtendedStyle); /// 判断窗口的左上角是否隐藏在桌面外 if (windowRect.left < 0) /**< 如果窗口X坐标为负,移动坐标到0处,并调整窗口的位置 */ { windowRect.right -= windowRect.left; windowRect.left = 0; } if (windowRect.top < 0) /**< 如果窗口Y坐标为负,移动坐标到0处,并调整窗口的位置 */ { windowRect.bottom -= windowRect.top; windowRect.top = 0; } } /// 创建窗口 m_hWnd = CreateWindowEx(windowExtendedStyle, /**< 窗口的扩展风格 */ class_name, /**< 窗口的类名 */ window_title, /**< 窗口标题 */ windowStyle, /**< 窗口的风格 */ nX,nY, /**< 窗口的左上角位置 */ windowRect.right - windowRect.left, /**< 窗口的宽度 */ windowRect.bottom - windowRect.top, /**< 窗口的高度 */ HWND_DESKTOP, /**< 窗口的父窗口为桌面 */ 0, /**< 无菜单 */ h_instance, /**< 传入窗口的实例句柄 */ lpParam); /**< 传入程序类参数 */ while (m_hWnd != 0) /**< 窗口是否创建成功 */ { m_hDC = GetDC(m_hWnd); /**< 返回窗口的设备描述表 */ if (m_hDC == 0) /**< 如果为空 */ { /**< 失败 */ break; } GLuint PixelFormat = ChoosePixelFormat(m_hDC, &pfd); /**< 查找一个兼容的像素格式 */ if (PixelFormat == 0) /**< 如果没找到 */ { /**< 失败 */ break; } if (SetPixelFormat(m_hDC, PixelFormat, &pfd) == false) /**< 设置像素格式 */ { /**< 失败 */ break; } m_hRC = wglCreateContext(m_hDC); /**< 创建OpenGL的渲染描述表 */ if (m_hRC == 0) /**< 如果为空 */ { /**< 失败 */ break; } if (wglMakeCurrent(m_hDC, m_hRC) == false) /**< 设置当前的OpenGL的渲染对象为当前的窗口 */ { /**< 失败 */ break; } ShowWindow(m_hWnd, SW_NORMAL); /**< 显示窗口 */ ReshapeGL(); /**< 告诉OpenGL调整窗口大小 */ return true; /**< 成功返回 */ } Destroy(); /**< 释放资源 */ return false; /**< 返回失败 */ }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // console for debugging //AllocConsole(); //freopen("CONOUT$","wb",stdout); WNDCLASSEX wc; HWND hwnd; MSG msg; // register window class wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = g_windowClass; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); unsigned int winWidth = WINDOW_WIDTH; unsigned int winHeight = WINDOW_HEIGHT; if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed", "Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // create window hwnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, g_windowClass, "Title Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, winWidth, winHeight, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(NULL, "Window Creation Failed", "Error", MB_ICONEXCLAMATION | MB_OK); return 0; } HDC hdc; if(!(hdc = GetDC(hwnd))) printf("GetDC failed\n"); //* old set pixel format // set pixel format PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // flags PFD_TYPE_RGBA, // rgba framebuffer 32, // 32 bit color depth 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 8, // 24 bit depth, 8 bit stencil 0, // # of aux buffers PFD_MAIN_PLANE, 0, 0, 0, 0 }; // get available matching pixel format int iPixelFormat; if(!(iPixelFormat = ChoosePixelFormat(hdc, &pfd))) printf("ChoosePixelFormat failed\n"); //*/ // assign pixel format to device context if(!(SetPixelFormat(hdc, iPixelFormat, &pfd))) printf("SetPixelFormat failed\n"); // create opengl context HGLRC context; if(!(context = wglCreateContext(hdc))) printf("wglCreateContext failed\n"); if(!(wglMakeCurrent(hdc, context))) printf("wglMakeCurrent failed\n"); // Now we want an updated pixel format and context //* PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if(!wglChoosePixelFormatARB) { printf("wgl choose pixel format not supported?\n"); } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if(!wglCreateContextAttribsARB) printf("wglCreateContextAttribsARB undefined\n"); // using wglchoosepixelformat const int attribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0, }; int ePixelFormat; unsigned int numFormats; int valid = wglChoosePixelFormatARB(hdc, attribList, NULL, 1, &ePixelFormat, &numFormats); if (valid && numFormats >= 1) { // we have a valid format printf("we have a valid format\n"); } else { printf("wglchoosepixel format didn't find a valid format\n"); } // if we found a valid format, it is stored in ePixelFormat // delete old rendering context int delc = wglDeleteContext(context); if (!delc) printf("failed to delete old context\n"); // release device context ReleaseDC(hwnd, hdc); // destroy the window DestroyWindow(hwnd); while(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // get rid of the first destroy message so it doesn't screw up later int temp = GetMessage(&msg, NULL, 0, 0); if (temp != 0) { printf("whoops, something other than destroy was in message queue after destroywindow: (%i)\n", temp); } else { printf("disposed of the first destory message\n"); } } // now, make it all again hwnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, g_windowClass, "Title Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, winWidth, winHeight, NULL, NULL, hInstance, NULL); // get the new device context if(!(hdc = GetDC(hwnd))) printf("second GetDC failed\n"); // set the pixel format the the extended one we got earlier if (!SetPixelFormat(hdc, ePixelFormat, &pfd)) { // failed to set pixel format printf("failed to set extended pixel format\n"); } // create extended opengl rendering context int contextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if(!(context = wglCreateContextAttribsARB(hdc, NULL, contextAttribs))) printf("second wglCreateContext failed\n"); if(!(wglMakeCurrent(hdc, context))) printf("second wglMakeCurrent failed\n"); //*/ ShowWindow(hwnd, nCmdShow); SetForegroundWindow(hwnd); SetFocus(hwnd); UpdateWindow(hwnd); // set initial mouse position POINT p; if(GetCursorPos(&p)) { if (ScreenToClient(hwnd, &p)) { g_mouse_x = p.x; g_mouse_y = p.y; } else { printf("ScreenToClient failed\n"); } } else { printf("GetCursorPos failed\n"); } initGL(winWidth, winHeight); printf("finished init, starting main loop\n"); g_hwnd = hwnd; g_current_millis = currentMillis(); // main loop while(g_running) { while(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { int temp = GetMessage(&msg, NULL, 0, 0); if(temp > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } else { printf("getmessage returned nonpositive: (%i)\n", temp); g_running = false; break; } } long long current_millis = currentMillis(); //printf("current_millis is %i\n", current_millis); // wouldn't current_millis be bigger? float dt = g_current_millis - current_millis; g_current_millis = current_millis; // draw stuff renderGL(); update(dt); g_running &= !keys[frontKeyBuffer][VK_ESCAPE]; swapKeyBuffers(); SwapBuffers(hdc); } printf("quitting\n"); //FreeConsole(); // delete the rendering context wglMakeCurrent(NULL, NULL); wglDeleteContext(context); return msg.wParam; }
void initPtrToWglFunctions(){ HWND hwnd = createDummyWindow(); HDC dpy = GetDC(hwnd); if(!hwnd || !dpy){ fprintf(stderr,"error while getting DC\n"); return; } EGLNativeContextType ctx = NULL; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 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,err; iPixelFormat = ChoosePixelFormat(dpy, &pfd); if(iPixelFormat < 0){ fprintf(stderr,"error while choosing pixel format\n"); return; } if(!SetPixelFormat(dpy,iPixelFormat,&pfd)){ int err = GetLastError(); fprintf(stderr,"error while setting pixel format 0x%x\n",err); return; } ctx = wglCreateContext(dpy); if(!ctx){ err = GetLastError(); fprintf(stderr,"error while creating dummy context %d\n",err); } if(!wglMakeCurrent(dpy,ctx)){ err = GetLastError(); fprintf(stderr,"error while making dummy context current %d\n",err); } if(!s_wglExtProcs){ s_wglExtProcs = new WglExtProcs(); s_wglExtProcs->wglGetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pixel_format","wglGetPixelFormatAttribivARB"); s_wglExtProcs->wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pixel_format","wglChoosePixelFormatARB"); s_wglExtProcs->wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pbuffer","wglCreatePbufferARB"); s_wglExtProcs->wglReleasePbufferDCARB = (PFNWGLRELEASEPBUFFERDCARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pbuffer","wglReleasePbufferDCARB"); s_wglExtProcs->wglDestroyPbufferARB = (PFNWGLDESTROYPBUFFERARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pbuffer","wglDestroyPbufferARB"); s_wglExtProcs->wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_pbuffer","wglGetPbufferDCARB"); s_wglExtProcs->wglMakeContextCurrentARB = (PFNWGLMAKECONTEXTCURRENTARBPROC)wglGetExtentionsProcAddress(dpy,"WGL_ARB_make_current_read","wglMakeContextCurrentARB"); s_wglExtProcs->wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetExtentionsProcAddress(dpy,"WGL_EXT_swap_control","wglSwapIntervalEXT"); } wglMakeCurrent(dpy,NULL); DestroyWindow(hwnd); DeleteDC(dpy); }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW |CS_OWNDC; wc.lpfnWndProc = (WNDPROC)WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(PINGIEL_ICON)); wc.hCursor = 0; wc.hbrBackground = 0; wc.lpszMenuName = MAKEINTRESOURCE(PINGIEL_MENU); wc.lpszClassName = "PingielClass"; if (!RegisterClass(&wc)) return false; MessageBox(0, "hejo", "okienko", MB_OK); int horizontal=GetSystemMetrics(16); int vertical = GetSystemMetrics(17); HWND hWnd = CreateWindow(wc.lpszClassName, "Okno", WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU, 0, 0,horizontal, vertical, NULL, NULL, hInstance, NULL); if (hWnd == NULL) return false; static PIXELFORMATDESCRIPTOR pfd= //struktura formatu pixeli { sizeof(PIXELFORMATDESCRIPTOR), 1,//numerwersji PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 16,//tryb koloru 0,0,0,0,0,0,//ignorowane bity koloru 0,//brak kanalu alpha 0,//ignorowanie rpzesuniecia 0,//brak akumulatora 0,0,0,0,//ignorowane przesuniecie akumulatora 16,//16bitowy bufor glebokosci 0,//no stencil buffer 0,//no auxiliary buffer PFD_MAIN_PLANE,//glowna warstwa rysowania 0,//zarezerwowane 0,0,0//ignorowanie warstwy maski }; HDC hDC = NULL;//kontekst urzadzenia HGLRC hRC = NULL;//kontekst renderowania GLuint PixelFormat;//styl pixeli if (!(hDC = GetDC(hWnd))) return 0;//pobranie kontekstu if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))return 0;//wyszukiwanie formatu pixeli if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return 0;//ust. formatu pixeli if (!(hRC = wglCreateContext(hDC)))return 0;//pobvranie kontekstu renderowania if (!wglMakeCurrent(hDC, hRC))return 0; //uruchomienie kontekstu renderowania ShowWindow(hWnd, iCmdShow); SetForegroundWindow(hWnd); SetFocus(hWnd); if (!InitGL()) // Initialize Our Newly Created GL Window { // Reset The Display MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } BOOL done = false; MSG msg; while (!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))//czy jest zdarzenie do obslugi? { if (msg.message == WM_QUIT) done = TRUE; else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { DrawGLScene(); SwapBuffers(hDC); } } if (hRC) { wglMakeCurrent(NULL, NULL);//usuw. kontekstu rend. wglDeleteContext(hRC);//usuw. kontekstu rend. hRC = NULL;//wyzerowanie kontekstu rend. } if (hDC && !ReleaseDC(hWnd, hDC)) { hDC = NULL; }//wyzerowanie kontekstu if (hWnd&& !DestroyWindow(hWnd)){ hWnd = NULL; }//wyzerowanie uchwytu okienka return 0; }
EF_Drawable ef_video_new_drawable(int width, int height, int full_screen, EF_Display display) { struct drawable *drawable = malloc(sizeof(struct drawable)); DWORD window_style = WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE; RECT window_rect; window_rect.top = 0; window_rect.left = 0; window_rect.bottom = height; window_rect.right = width; AdjustWindowRect(&window_rect, window_style, 0); int adjusted_width = window_rect.right - window_rect.left; int adjusted_height = window_rect.bottom - window_rect.top; utf16 *title16 = utf8_to_utf16(ef_internal_application_name()); drawable->window = CreateWindowW(L"Emerald Frame", title16, window_style, CW_USEDEFAULT, CW_USEDEFAULT, adjusted_width, adjusted_height, NULL, NULL, hInstance, NULL); free(title16); TRACKMOUSEEVENT trackmouseevent; trackmouseevent.cbSize = sizeof(trackmouseevent); trackmouseevent.dwFlags = TME_LEAVE; trackmouseevent.hwndTrack = drawable->window; trackmouseevent.dwHoverTime = 0; TrackMouseEvent(&trackmouseevent); drawable->device_context = GetDC(drawable->window); PIXELFORMATDESCRIPTOR pixel_format; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.nSize = sizeof(pixel_format); pixel_format.nVersion = 1; pixel_format.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixel_format.iPixelType = PFD_TYPE_RGBA; pixel_format.cColorBits = 24; pixel_format.cDepthBits = 16; pixel_format.iLayerType = PFD_MAIN_PLANE; int internal_pixel_format = ChoosePixelFormat(drawable->device_context, &pixel_format); SetPixelFormat(drawable->device_context, internal_pixel_format, &pixel_format); drawable->rendering_context = wglCreateContext(drawable->device_context); n_drawables++; all_drawables = realloc(all_drawables, sizeof(struct drawable *) * n_drawables); all_drawables[n_drawables-1] = drawable; drawable->draw_callback = NULL; drawable->draw_callback_context = NULL; drawable->key_down_callback = NULL; drawable->key_down_callback_context = NULL; drawable->key_up_callback = NULL; drawable->key_up_callback_context = NULL; drawable->mouse_down_callback = NULL; drawable->mouse_down_callback_context = NULL; drawable->mouse_up_callback = NULL; drawable->mouse_up_callback_context = NULL; drawable->mouse_move_callback = NULL; drawable->mouse_move_callback_context = NULL; drawable->mouse_enter_callback = NULL; drawable->mouse_enter_callback_context = NULL; drawable->mouse_exit_callback = NULL; drawable->mouse_exit_callback_context = NULL; return (EF_Drawable) drawable; }