void CreateWindowGL (gl_window_t *win) // This Code Creates Our OpenGL Window { __int64 timer; // Holds High Resolution Timer Information 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 win->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, win->init.width, win->init.height}; // Define Our Window Coordinates GLuint PixelFormat; // Will Hold The Selected Pixel Format if (win->init.isFullScreen == TRUE) // Fullscreen Requested, Try Changing Video Modes { if (ChangeScreenResolution (win->init.width, win->init.height, win->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); win->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 win->hWnd = CreateWindowExA (windowExtendedStyle, // Extended Style win->init.application->className, // Class Name win->init.title, // Window Title windowStyle, // Window Style win->init.left, win->init.top, // 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 win->init.application->hInstance, // Pass The Window Instance win); if (win->hWnd == 0) // Was Window Creation A Success? { win->isCreated = FALSE; return; } win->hDC = GetDC (win->hWnd); // Grab A Device Context For This Window if (win->hDC == 0) // Did We Get A Device Context? { // Failed DestroyWindow (win->hWnd); // Destroy The Window win->hWnd = 0; // Zero The Window Handle win->isCreated = FALSE; return; // Return False } PixelFormat = ChoosePixelFormat (win->hDC, &pfd); // Find A Compatible Pixel Format if (PixelFormat == 0) // Did We Find A Compatible Format? { // Failed ReleaseDC (win->hWnd, win->hDC); // Release Our Device Context win->hDC = 0; // Zero The Device Context DestroyWindow (win->hWnd); // Destroy The Window win->hWnd = 0; // Zero The Window Handle win->isCreated = FALSE; return; // Return False } if (SetPixelFormat (win->hDC, PixelFormat, &pfd) == FALSE) // Try To Set The Pixel Format { // Failed ReleaseDC (win->hWnd, win->hDC); // Release Our Device Context win->hDC = 0; // Zero The Device Context DestroyWindow (win->hWnd); // Destroy The Window win->hWnd = 0; // Zero The Window Handle win->isCreated = FALSE; return; // Return False } win->hRC = wglCreateContext (win->hDC); // Try To Get A Rendering Context if (win->hRC == 0) // Did We Get A Rendering Context? { // Failed ReleaseDC (win->hWnd, win->hDC); // Release Our Device Context win->hDC = 0; // Zero The Device Context DestroyWindow (win->hWnd); // Destroy The Window win->hWnd = 0; // Zero The Window Handle win->isCreated = FALSE; return; // Return False } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent (win->hDC, win->hRC) == FALSE) { // Failed wglDeleteContext (win->hRC); // Delete The Rendering Context win->hRC = 0; // Zero The Rendering Context ReleaseDC (win->hWnd, win->hDC); // Release Our Device Context win->hDC = 0; // Zero The Device Context DestroyWindow (win->hWnd); // Destroy The Window win->hWnd = 0; // Zero The Window Handle win->isCreated = FALSE; return; // Return False } ShowWindow (win->hWnd, SW_NORMAL); // Make The Window Visible win->isVisible = TRUE; // Set isVisible To True ReshapeGL (win, win->init.width, win->init.height); // Reshape Our GL Window ZeroMemory (&(win->keys), sizeof (keys_t)); // Clear All Keys if (QueryPerformanceFrequency((LARGE_INTEGER *) &timer)) // Check To See If We Can Use Peformance Counter { win->hrTimer=TRUE; // High Resolution Is Available // Grab The Starting Tick Value win->lastTickCount = QueryPerformanceCounter((LARGE_INTEGER *) &timer); // Grab The Counter Frequency QueryPerformanceFrequency((LARGE_INTEGER *) &timer); // Set The Timer Resolution 1.0f / Timer Frequency win->timerResolution = (float) (((double)1.0f)/((double)timer)); } else { win->lastTickCount = GetTickCount (); // Get Tick Count The Old Fashioned Way win->timerResolution = 1.0f/1000.0f; // Set Our Timer Resolution To .001f } win->isCreated = TRUE; return; // Initialization Will Be Done In WM_CREATE }
djvWglContext::djvWglContext(djvCoreContext * context) throw (djvError) : djvOpenGlContext(context), _p(new djvWglContextPrivate) { # if defined(DJV_WINDOWS) //DJV_DEBUG("djvWglContext::djvWglContext"); // Create a dummy window and OpenGL context for glewInit. // According to the docs, glewInit can be called just once per-process? DJV_LOG(context->debugLog(), "djvWglContext", "Creating dummy window..."); HINSTANCE hinstance = GetModuleHandle(0); if (! hinstance) { throw djvError( "djvWglContext", errorLabels()[ERROR_MODULE_HANDLE].arg(int(GetLastError()))); } static const char name [] = "djv"; WNDCLASS wc; if (! GetClassInfo(hinstance, name, &wc)) { wc.style = CS_OWNDC; //wc.lpfnWndProc = (WNDPROC)MainWndProc; wc.lpfnWndProc = DefWindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = 0; wc.lpszMenuName = 0; wc.lpszClassName = name; if (! RegisterClass(&wc)) { throw djvError( "djvWglContext", errorLabels()[ERROR_REGISTER_CLASS].arg(int(GetLastError()))); } } _p->id = CreateWindow(name, 0, 0, 0, 0, 0, 0, 0, 0, hinstance, 0); if (! _p->id) { throw djvError( "djvWglContext", errorLabels()[ERROR_CREATE_WINDOW].arg(int(GetLastError()))); } _p->device = GetDC(_p->id); if (! _p->device) { throw djvError( "djvWglContext", errorLabels()[ERROR_GET_DC].arg(int(GetLastError()))); } PIXELFORMATDESCRIPTOR pixelFormatInfo; const int pixelFormatCount = DescribePixelFormat(_p->device, 0, 0, 0); //DJV_DEBUG_PRINT("pixel format count = " << pixelFormatCount); DJV_LOG(context->debugLog(), "djvWglContext", QString("Pixel format count: %1").arg(pixelFormatCount)); for (int i = 1; i < pixelFormatCount; ++i) { DescribePixelFormat( _p->device, i, sizeof(PIXELFORMATDESCRIPTOR), &pixelFormatInfo); //DJV_DEBUG_PRINT(" id " << i << ": " << // ((PFD_SUPPORT_OPENGL & pixelFormatInfo.dwFlags) ? "gl " : "") << // ((PFD_GENERIC_FORMAT & pixelFormatInfo.dwFlags) ? "" : "accel ") << // ((PFD_TYPE_RGBA == pixelFormatInfo.iPixelType) ? "rgba " : "") << // "depth = " << pixelFormatInfo.cColorBits << "/" << // pixelFormatInfo.cRedBits << "/" << // pixelFormatInfo.cGreenBits << "/" << // pixelFormatInfo.cBlueBits << "/" << // pixelFormatInfo.cAlphaBits << " "); QStringList tmp; if (PFD_SUPPORT_OPENGL & pixelFormatInfo.dwFlags) tmp += "gl"; if (! (PFD_GENERIC_FORMAT & pixelFormatInfo.dwFlags)) tmp += "accel"; if (PFD_TYPE_RGBA == pixelFormatInfo.iPixelType) tmp += "rgba"; DJV_LOG(context->debugLog(), "djvWglContext", QString("Pixel format %1: %2 %3/%4/%5/%6/%7"). arg(i). arg(tmp.join(" ")). arg(pixelFormatInfo.cColorBits). arg(pixelFormatInfo.cRedBits). arg(pixelFormatInfo.cGreenBits). arg(pixelFormatInfo.cBlueBits). arg(pixelFormatInfo.cAlphaBits)); } PIXELFORMATDESCRIPTOR pixelFormat = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pixelFormatId = ChoosePixelFormat(_p->device, &pixelFormat); //DJV_DEBUG_PRINT("pixel format = " << pixelFormatId); DJV_LOG(context->debugLog(), "djvWglContext", QString("Chosen pixel format: %1").arg(pixelFormatId)); if (! pixelFormatId) { throw djvError( "djvWglContext", errorLabels()[ERROR_GET_PIXEL_FORMAT].arg(int(GetLastError()))); } if (! SetPixelFormat(_p->device, pixelFormatId, &pixelFormat)) { throw djvError( "djvWglContext", errorLabels()[ERROR_SET_PIXEL_FORMAT].arg(int(GetLastError()))); } // Create OpengGL context. DJV_LOG(context->debugLog(), "djvWglContext", "Creating OpenGL context..."); _p->context = wglCreateContext(_p->device); if (! _p->context) { throw djvError( "djvWglContext", errorLabels()[ERROR_CREATE_CONTEXT].arg(int(GetLastError()))); } if (! wglMakeCurrent(_p->device, _p->context)) { throw djvError( "djvWglContext", errorLabels()[ERROR_BIND_CONTEXT].arg(int(GetLastError()))); } // Initialize GLEW. DJV_LOG(context->debugLog(), "djvWglContext", "Initializing GLEW..."); GLenum err = glewInit(); if (err != GLEW_OK) { throw djvError( "djvWglContext", errorLabels()[ERROR_INIT_GLEW].arg((char *)glewGetErrorString(err))); } setVendor(QString((const char *)glGetString(GL_VENDOR))); setRenderer(QString((const char *)glGetString(GL_RENDERER))); setVersion(QString((const char *)glGetString(GL_VERSION))); //DJV_DEBUG_PRINT("OpenGL vendor string = " << vendor()); //DJV_DEBUG_PRINT("OpenGL renderer string = " << renderer()); //DJV_DEBUG_PRINT("OpenGL version string = " << version()); //DJV_DEBUG_PRINT("OpenGL extensions = " << // (const char *)glGetString(GL_EXTENSIONS)); //DJV_DEBUG_PRINT("glu version = " << // (const char *)gluGetString(GLU_VERSION)); //DJV_DEBUG_PRINT("glu extensions = " << // (const char *)gluGetString(GLU_EXTENSIONS)); DJV_LOG(context->debugLog(), "djvWglContext", QString("GL vendor: \"%1\"").arg(vendor())); DJV_LOG(context->debugLog(), "djvWglContext", QString("GL renderer: \"%1\"").arg(renderer())); DJV_LOG(context->debugLog(), "djvWglContext", QString("GL version: \"%1\"").arg(version())); # endif // DJV_WINDOWS }
int WIN_GL_SetupWindow(_THIS) { int retval; #if SDL_VIDEO_OPENGL int i; int iAttribs[64]; int *iAttr; float fAttribs[1] = { 0 }; const GLubyte *(WINAPI *glGetStringFunc)(GLenum); const char *wglext; /* load the gl driver from a default path */ if ( ! this->gl_config.driver_loaded ) { /* no driver has been loaded, use default (ourselves) */ if ( WIN_GL_LoadLibrary(this, NULL) < 0 ) { return(-1); } } /* Set up the pixel format descriptor with our needed format */ SDL_memset(&GL_pfd, 0, sizeof(GL_pfd)); GL_pfd.nSize = sizeof(GL_pfd); GL_pfd.nVersion = 1; GL_pfd.dwFlags = (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL); if ( this->gl_config.double_buffer ) { GL_pfd.dwFlags |= PFD_DOUBLEBUFFER; } if ( this->gl_config.stereo ) { GL_pfd.dwFlags |= PFD_STEREO; } GL_pfd.iPixelType = PFD_TYPE_RGBA; GL_pfd.cColorBits = this->gl_config.buffer_size; GL_pfd.cRedBits = this->gl_config.red_size; GL_pfd.cGreenBits = this->gl_config.green_size; GL_pfd.cBlueBits = this->gl_config.blue_size; GL_pfd.cAlphaBits = this->gl_config.alpha_size; GL_pfd.cAccumRedBits = this->gl_config.accum_red_size; GL_pfd.cAccumGreenBits = this->gl_config.accum_green_size; GL_pfd.cAccumBlueBits = this->gl_config.accum_blue_size; GL_pfd.cAccumAlphaBits = this->gl_config.accum_alpha_size; GL_pfd.cAccumBits = (GL_pfd.cAccumRedBits + GL_pfd.cAccumGreenBits + GL_pfd.cAccumBlueBits + GL_pfd.cAccumAlphaBits); GL_pfd.cDepthBits = this->gl_config.depth_size; GL_pfd.cStencilBits = this->gl_config.stencil_size; /* setup WGL_ARB_pixel_format attribs */ iAttr = &iAttribs[0]; *iAttr++ = WGL_DRAW_TO_WINDOW_ARB; *iAttr++ = GL_TRUE; *iAttr++ = WGL_ACCELERATION_ARB; *iAttr++ = WGL_FULL_ACCELERATION_ARB; *iAttr++ = WGL_RED_BITS_ARB; *iAttr++ = this->gl_config.red_size; *iAttr++ = WGL_GREEN_BITS_ARB; *iAttr++ = this->gl_config.green_size; *iAttr++ = WGL_BLUE_BITS_ARB; *iAttr++ = this->gl_config.blue_size; if ( this->gl_config.alpha_size ) { *iAttr++ = WGL_ALPHA_BITS_ARB; *iAttr++ = this->gl_config.alpha_size; } *iAttr++ = WGL_DOUBLE_BUFFER_ARB; *iAttr++ = this->gl_config.double_buffer; *iAttr++ = WGL_DEPTH_BITS_ARB; *iAttr++ = this->gl_config.depth_size; if ( this->gl_config.stencil_size ) { *iAttr++ = WGL_STENCIL_BITS_ARB; *iAttr++ = this->gl_config.stencil_size; } if ( this->gl_config.accum_red_size ) { *iAttr++ = WGL_ACCUM_RED_BITS_ARB; *iAttr++ = this->gl_config.accum_red_size; } if ( this->gl_config.accum_green_size ) { *iAttr++ = WGL_ACCUM_GREEN_BITS_ARB; *iAttr++ = this->gl_config.accum_green_size; } if ( this->gl_config.accum_blue_size ) { *iAttr++ = WGL_ACCUM_BLUE_BITS_ARB; *iAttr++ = this->gl_config.accum_blue_size; } if ( this->gl_config.accum_alpha_size ) { *iAttr++ = WGL_ACCUM_ALPHA_BITS_ARB; *iAttr++ = this->gl_config.accum_alpha_size; } if ( this->gl_config.stereo ) { *iAttr++ = WGL_STEREO_ARB; *iAttr++ = GL_TRUE; } if ( this->gl_config.multisamplebuffers ) { *iAttr++ = WGL_SAMPLE_BUFFERS_ARB; *iAttr++ = this->gl_config.multisamplebuffers; } if ( this->gl_config.multisamplesamples ) { *iAttr++ = WGL_SAMPLES_ARB; *iAttr++ = this->gl_config.multisamplesamples; } if ( this->gl_config.accelerated >= 0 ) { *iAttr++ = WGL_ACCELERATION_ARB; *iAttr++ = (this->gl_config.accelerated ? WGL_GENERIC_ACCELERATION_ARB : WGL_NO_ACCELERATION_ARB); } *iAttr = 0; for ( i=0; ; ++i ) { /* Get the window device context for our OpenGL drawing */ GL_hdc = GetDC(SDL_Window); if ( GL_hdc == NULL ) { SDL_SetError("Unable to get DC for SDL_Window"); return(-1); } /* Choose and set the closest available pixel format */ pixel_format = ChoosePixelFormatARB(this, iAttribs, fAttribs); if ( !pixel_format ) { pixel_format = ChoosePixelFormat(GL_hdc, &GL_pfd); } if ( !pixel_format ) { SDL_SetError("No matching GL pixel format available"); return(-1); } if ( !SetPixelFormat(GL_hdc, pixel_format, &GL_pfd) ) { if ( i == 0 ) { /* First time through, try resetting the window */ if ( WIN_GL_ResetWindow(this) < 0 ) { return(-1); } continue; } SDL_SetError("Unable to set HDC pixel format"); return(-1); } /* We either succeeded or failed by this point */ break; } DescribePixelFormat(GL_hdc, pixel_format, sizeof(GL_pfd), &GL_pfd); GL_hrc = this->gl_data->wglCreateContext(GL_hdc); if ( GL_hrc == NULL ) { SDL_SetError("Unable to create GL context"); return(-1); } if ( WIN_GL_MakeCurrent(this) < 0 ) { return(-1); } gl_active = 1; /* Get the wglGetPixelFormatAttribivARB pointer for the context */ if ( this->gl_data->WGL_ARB_pixel_format ) { this->gl_data->wglGetPixelFormatAttribivARB = (BOOL (WINAPI *)(HDC, int, int, UINT, const int *, int *)) this->gl_data->wglGetProcAddress("wglGetPixelFormatAttribivARB"); } else { this->gl_data->wglGetPixelFormatAttribivARB = NULL; } /* Vsync control under Windows. Checking glGetString here is * somewhat a documented and reliable hack - it was originally * as a feature added by mistake, but since so many people rely * on it, it will not be removed. strstr should be safe here.*/ glGetStringFunc = WIN_GL_GetProcAddress(this, "glGetString"); if ( glGetStringFunc ) { wglext = (const char *)glGetStringFunc(GL_EXTENSIONS); } else { /* Uh oh, something is seriously wrong here... */ wglext = NULL; } if ( wglext && SDL_strstr(wglext, "WGL_EXT_swap_control") ) { this->gl_data->wglSwapIntervalEXT = WIN_GL_GetProcAddress(this, "wglSwapIntervalEXT"); this->gl_data->wglGetSwapIntervalEXT = WIN_GL_GetProcAddress(this, "wglGetSwapIntervalEXT"); } else { this->gl_data->wglSwapIntervalEXT = NULL; this->gl_data->wglGetSwapIntervalEXT = NULL; } if ( this->gl_config.swap_control >= 0 ) { if ( this->gl_data->wglSwapIntervalEXT ) { this->gl_data->wglSwapIntervalEXT(this->gl_config.swap_control); } } #else SDL_SetError("WIN driver not configured with OpenGL"); #endif if ( gl_active ) { retval = 0; } else { retval = -1; } return(retval); }
int CGraphics::InitAll() { GLuint PixelFormat; //Contiene el formato de pixel static PIXELFORMATDESCRIPTOR pfd= //Contiene la informacion del formato del pixel { sizeof(PIXELFORMATDESCRIPTOR), //Tamaño de este descriptor 1, PFD_DRAW_TO_WINDOW | //Formato que soporte Windows PFD_SUPPORT_OPENGL | //Formato que soporte OpenGL PFD_DOUBLEBUFFER, //Soporta doble buffering PFD_TYPE_RGBA, //Peticion de un formato RGBA 16, // Selecciona el color de la profundidad 0, 0, 0, 0, 0, 0, //Bits de Color Ignorado 0, // No Alpha Buffer 0, // Shift Bit Ignorado 0, // Buffer de no acumulacion 0, 0, 0, 0, //Bits de acumulacion ignorados 16, //16bit Z Buffer (Buffer de profundidad) 0, //No Stencil Buffer 0, //No Auxiliary Buffer PFD_MAIN_PLANE, //Capa principal de dibujo 0, //Reservado 0,0,0 //Mascaras de capa ignoradas }; if (!(hDC=GetDC(GetHWND()))) { //Se obtuvo un contexto de dispositivo? MessageBox(NULL, L"It couldn't get window Context", L"ERROR",MB_OK|MB_ICONEXCLAMATION); return -1; } if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) {//Windows encontro un formato de pixel similar? MessageBox(NULL, L"Non suitable pixel format found", L"ERROR",MB_OK|MB_ICONEXCLAMATION); return -1; } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) {//Se pudo iniciar el formato de pixel? MessageBox(NULL, L"It couldn't set pixel format", L"ERROR",MB_OK|MB_ICONEXCLAMATION); return -1; } if(!(hRC=wglCreateContext(hDC))) {//Conseguimos el contexto para renderear? MessageBox(NULL, L"It was not possible to create GL Context", L"ERROR",MB_OK|MB_ICONEXCLAMATION); return -1; } if(!wglMakeCurrent(hDC,hRC)) {//Intento de activar el contexto de rendering MessageBox(NULL, L"It was not possible to set current GL Context", L"ERROR",MB_OK|MB_ICONEXCLAMATION); return -1; } GLfloat blanco[]= {1.0f,1.0f,1.0f,1.0f}; //GLfloat LightPosition[]={220.0f,-200.0f,220.0f,1.0f}; glEnable(GL_LINE_SMOOTH); glEnable (GL_LIGHTING); glEnable (GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); // Buffer de profundidad glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); //Habilida la prueba de profundidad glDepthFunc(GL_LEQUAL); // Tipo de prueba glEnable(GL_NORMALIZE); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Mejora la perspectiva glClearColor(1.0f, 1.0f, 1.0f, 0); //Pone el color del fondo a gris glLightfv(GL_LIGHT0, GL_DIFFUSE, blanco); glEnable (GL_LIGHT0); Size(); return 0; }
void OSGL_createOpenGLWindow(uintf width, uintf height) { // Create a temporary window so we can query some values from the video driver int nPF; HDC tmphDC; // Temporary device context HGLRC tmphRC; // Temporary Renderring Context WNDCLASS tmpWc; // Temporary Windows class structure HWND tmphWnd; // Temporary Window Handle uintf iMode; // Register Window style tmpWc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; tmpWc.lpfnWndProc = (WNDPROC) wgl_tmpWndProc; tmpWc.cbClsExtra = 0; tmpWc.cbWndExtra = 0; tmpWc.hInstance = winVars.hinst; tmpWc.hIcon = NULL; tmpWc.hCursor = LoadCursor(NULL, IDC_ARROW); tmpWc.hbrBackground = NULL; // No need for background brush for OpenGL window tmpWc.lpszMenuName = NULL; tmpWc.lpszClassName = "Windows GL Temp Window"; if(RegisterClass(&tmpWc) == 0) wglError(wgltxt_regClass1); tmphWnd = CreateWindowEx(WS_EX_TOPMOST, tmpWc.lpszClassName, tmpWc.lpszClassName, WS_POPUP, 0, 0, 400, 400, NULL, NULL, winVars.hinst, NULL); if(tmphWnd == NULL) wglError(wgltxt_noWindow1); ShowWindow(tmphWnd,SW_SHOW); UpdateWindow(tmphWnd); PIXELFORMATDESCRIPTOR pfd = // Not going to be too picky { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, // Full color 32, // Color depth 0,0,0,0,0,0,0, // Ignored 0,0,0,0, // Accumulation buffer 24, // Depth bits 8, // Stencil bits 0,0,0,0,0,0 }; // Some used, some not // Create a "temporary" OpenGL rendering context tmphDC = GetDC(tmphWnd); // Set pixel format one time.... nPF = ChoosePixelFormat(tmphDC, &pfd); SetPixelFormat(tmphDC, nPF, &pfd); DescribePixelFormat(tmphDC, nPF, sizeof(PIXELFORMATDESCRIPTOR), &pfd); // Create the GL context tmphRC = wglCreateContext(tmphDC); wglMakeCurrent(tmphDC, tmphRC); // Find a multisampled and non-multisampled pixel format wgl_FindBestPF(tmphDC, &wgl_PixelFormatSTD, &wgl_PixelFormatFSAA); iMode = 0; int bestMode = 0; int bestScore = 0x7FFFFFFF; while (EnumDisplaySettings(NULL, iMode, &wgl_devMode)) { int score = 1; if (wgl_devMode.dmBitsPerPel!=32) score *= 256; int xDif = abs((int)(wgl_devMode.dmPelsWidth - width))+1; int yDif = abs((int)(wgl_devMode.dmPelsHeight - height))+1; score *= xDif * yDif; if (score<bestScore) { bestScore = score; bestMode = iMode; } iMode++; } EnumDisplaySettings(NULL, bestMode, &wgl_devMode); wgl_PrefFSWidth = wgl_devMode.dmPelsWidth; // Preferred fullscreen width, height wgl_PrefFSHeight = wgl_devMode.dmPelsHeight; // ###!!!### The system is picking it's own window width and height! This HACK code fixed that wgl_PrefFSWidth = wgl_devMode.dmPelsWidth = width; // Preferred fullscreen width, height wgl_PrefFSHeight = wgl_devMode.dmPelsHeight = height; // Done with GL context wglMakeCurrent(tmphDC, NULL); wglDeleteContext(tmphRC); DestroyWindow(tmphWnd); // ***************** Now create the real OGL window wgl_createMyWindow(OSGL_isFullScreen, &winVars.mainWin); // If window was not created, quit if(winVars.mainWin == NULL) wglError(wgltxt_noWindow2); MSG msg; // Windows message structure while (applicationState!=AppState_running) { GetMessage(&msg, NULL, 0, 0); TranslateMessage(&msg); DispatchMessage(&msg); } OSGL_onWinCreate(winVars.mainWin); }
int createGLWindow(HINSTANCE hInstance, LPCTSTR className) { hWindow = CreateWindow( className, "GraphicsGame", WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, windowWidth, windowHeight, NULL, NULL, hInstance, NULL ); if(!hWindow) { killWindow(className); MessageBox(hWindow, "Couldnt Create Window", "Error", MB_OK); return false; } hDeviceContext = GetDC(hWindow); if(!hDeviceContext) { killWindow(className); MessageBox(hWindow, "Could Create Device Context", "Error", MB_OK); return false; } PIXELFORMATDESCRIPTOR pfd = {}; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_SUPPORT_OPENGL|PFD_DRAW_TO_WINDOW|PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 24; pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormat = ChoosePixelFormat(hDeviceContext, &pfd); if(!pixelFormat) { killWindow(className); MessageBox(hWindow, "Couldnt Select Good Pixel Format", "Error", MB_OK); return false; } if(!SetPixelFormat(hDeviceContext, pixelFormat, &pfd)) { killWindow(className); MessageBox(hWindow, "Couldnt Select Good Pixel Format", "Error", MB_OK); return false; } GLRenderContext = wglCreateContext(hDeviceContext); if(!GLRenderContext) { killWindow(className); MessageBox(hWindow, "Couldnt make opengl context", "Error", MB_OK); return false; } if(!wglMakeCurrent(hDeviceContext, GLRenderContext)) { killWindow(className); MessageBox(hWindow, "Couldnt make gl context current", "Error", MB_OK); return false; } return true; }
// Implement static initializer function to create this class. Render::RenderDevice* RenderDevice::CreateDevice(const RendererParams& rp, void* oswnd) { HWND hwnd = (HWND)oswnd; HDC dc = GetDC(hwnd); if (!DwmEnableComposition) { HINSTANCE hInst = LoadLibrary( L"dwmapi.dll" ); OVR_ASSERT(hInst); DwmEnableComposition = (PFNDWMENABLECOMPOSITIONPROC)GetProcAddress( hInst, "DwmEnableComposition" ); OVR_ASSERT(DwmEnableComposition); } DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); { PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.iPixelType = PFD_TYPE_RGBA; pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; pfd.cColorBits = 32; pfd.cDepthBits = 16; int pf = ChoosePixelFormat(dc, &pfd); if (!pf) { ReleaseDC(hwnd, dc); return NULL; } if (!SetPixelFormat(dc, pf, &pfd)) { ReleaseDC(hwnd, dc); return NULL; } HGLRC context = wglCreateContext(dc); if (!wglMakeCurrent(dc, context)) { wglDeleteContext(context); ReleaseDC(hwnd, dc); return NULL; } wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); wglDeleteContext(context); } int iAttributes[] = { //WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 16, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE, 0, 0}; float fAttributes[] = {0,0}; int pf = 0; UINT numFormats = 0; if (!wglChoosePixelFormatARB(dc, iAttributes, fAttributes, 1, &pf, &numFormats)) { ReleaseDC(hwnd, dc); return NULL; } PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); if (!SetPixelFormat(dc, pf, &pfd)) { ReleaseDC(hwnd, dc); return NULL; } GLint attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; HGLRC context = wglCreateContextAttribsARB(dc, 0, attribs); if (!wglMakeCurrent(dc, context)) { wglDeleteContext(context); ReleaseDC(hwnd, dc); return NULL; } InitGLExtensions(); return new RenderDevice(rp, hwnd, context); }
GLUTwindow * __glutCreateWindow(GLUTwindow * parent, int x, int y, int width, int height) { GLUTwindow *window; XSetWindowAttributes wa; unsigned long attribMask; int winnum; int i; #if defined(WIN32) WNDCLASS wc; if (!GetClassInfo(GetModuleHandle(NULL), "GLUT", &wc)) __glutOpenWin32Connection(NULL); #else if (!__glutDisplay) __glutOpenXConnection(NULL); #endif winnum = getUnusedWindowSlot(); window = (GLUTwindow *) malloc(sizeof(GLUTwindow)); if (!window) __glutFatalError("out of memory."); window->num = winnum; #if !defined(WIN32) window->vis = __glutDetermineWindowVisual(&window->treatAsSingle, &window->visAlloced); if (!window->vis) { __glutFatalError( "visual with necessary capabilities not found."); } __glutSetupColormap(window->vis, &window->colormap, &window->cmap); #endif window->eventMask = StructureNotifyMask | ExposureMask; attribMask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask; wa.background_pixmap = None; wa.border_pixel = 0; wa.colormap = window->cmap; wa.event_mask = window->eventMask; if (parent) { if (parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK) wa.event_mask |= GLUT_HACK_STOP_PROPAGATE_MASK; attribMask |= CWDontPropagate; wa.do_not_propagate_mask = parent->eventMask & GLUT_DONT_PROPAGATE_FILTER_MASK; } else { wa.do_not_propagate_mask = 0; } /* Stash width and height before Win32's __glutAdjustCoords possibly overwrites the values. */ window->width = width; window->height = height; window->forceReshape = True; #if defined(WIN32) __glutAdjustCoords(parent ? parent->win : NULL, &x, &y, &width, &height); window->win = XCreateWindow(__glutDisplay, parent == NULL ? __glutRoot : parent->win, x, y, width, height, 0, 0, InputOutput, 0, attribMask, &wa); window->hdc = GetDC(window->win); /* Must set the XHDC for fake glXChooseVisual & fake glXCreateContext & fake XAllocColorCells. */ XHDC = window->hdc; window->vis = __glutDetermineWindowVisual(&window->treatAsSingle, &window->visAlloced); if (!window->vis) { __glutFatalError( "visual with necessary capabilities not found."); } if (!SetPixelFormat(window->hdc, ChoosePixelFormat(window->hdc, window->vis), window->vis)) __glutFatalError("SetPixelFormat() failed in glutCreateWindow()."); __glutSetupColormap(window->vis, &window->colormap, &window->cmap); /* Make sure subwindows get a windowStatus callback. */ if (parent) PostMessage(parent->win, WM_ACTIVATE, 0, 0); #else window->win = XCreateWindow(__glutDisplay, parent == NULL ? __glutRoot : parent->win, x, y, width, height, 0, window->vis->depth, InputOutput, window->vis->visual, attribMask, &wa); #endif window->renderWin = window->win; window->ctx = glXCreateContext(__glutDisplay, window->vis, None, __glutTryDirect); if (!window->ctx) { __glutFatalError( "failed to create OpenGL rendering context."); } window->renderCtx = window->ctx; #if !defined(WIN32) window->isDirect = glXIsDirect(__glutDisplay, window->ctx); if (__glutForceDirect) { if (!window->isDirect) __glutFatalError("direct rendering not possible."); } #endif window->parent = parent; if (parent) { window->siblings = parent->children; parent->children = window; } else { window->siblings = NULL; } window->overlay = NULL; window->children = NULL; window->display = __glutDefaultDisplay; window->reshape = __glutDefaultReshape; window->mouse = NULL; window->motion = NULL; window->windowStatus = NULL; window->visibility = NULL; window->passive = NULL; window->entry = NULL; window->special = NULL; window->buttonBox = NULL; window->dials = NULL; window->spaceMotion = NULL; window->spaceRotate = NULL; window->spaceButton = NULL; window->tabletMotion = NULL; window->tabletButton = NULL; window->tabletPos[0] = -1; window->tabletPos[1] = -1; window->keyboard = NULL; window->shownState = 0; window->visState = -1; /* not VisibilityUnobscured, VisibilityPartiallyObscured, or VisibilityFullyObscured */ window->entryState = -1; /* not EnterNotify or LeaveNotify */ window->workMask = GLUT_MAP_WORK; window->desiredMapState = NormalState; window->desiredConfMask = 0; window->buttonUses = 0; window->cursor = GLUT_CURSOR_INHERIT; window->prevWorkWin = __glutWindowWorkList; __glutWindowWorkList = window; for (i = 0; i < GLUT_MAX_MENUS; i++) { window->menu[i] = 0; } __glutWindowList[winnum] = window; __glutSetWindow(window); __glutDetermineMesaSwapHackSupport(); if (window->treatAsSingle) { /* We do this because either the window really is single buffered (in which case this is redundant, but harmless, because this is the initial single-buffered context state); or we are treating a double buffered window as a single-buffered window because the system does not appear to export any suitable single- buffered visuals (in which the following are necessary). */ glDrawBuffer(GL_FRONT); glReadBuffer(GL_FRONT); } return window; }
BOOL CreateGLWindow(LPCTSTR title, int width, int height, int bits, BOOL fullscreenflag) { GLuint PixelFormat; DWORD dwExStyle; DWORD dwStyle; RECT wndRect; WNDCLASSEX wndclassex = {0}; g_hInst = GetModuleHandle(NULL); wndclassex.cbSize = sizeof(WNDCLASSEX); wndclassex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclassex.lpfnWndProc = WndProc; wndclassex.cbClsExtra = 0; wndclassex.cbWndExtra = 0; wndclassex.hInstance = g_hInst; wndclassex.hIcon = LoadIcon (NULL, IDI_APPLICATION); wndclassex.hCursor = LoadCursor (NULL, IDC_ARROW); wndclassex.hbrBackground = NULL; wndclassex.lpszMenuName = NULL; wndclassex.lpszClassName = g_strClassName; wndclassex.hIconSm = wndclassex.hIcon; wndRect.left = 0; wndRect.top = 0; wndRect.right = width; wndRect.bottom = height; g_bFullscreen = fullscreenflag; if (!RegisterClassEx (&wndclassex)) { MessageBox (NULL, TEXT ("RegisterClassEx failed!"), title, MB_ICONERROR); return FALSE; } if (g_bFullscreen) { DEVMODE dv; ZeroMemory(&dv,sizeof(dv)); dv.dmSize = sizeof(DEVMODE); dv.dmPelsWidth = width; dv.dmPelsHeight = height; dv.dmBitsPerPel = bits; dv.dmDisplayFrequency = 60; dv.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQUENCY; if (ChangeDisplaySettings(&dv,CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { if (::MessageBox(NULL,TEXT("È«ÆÁÉèÖÃʧ°Ü,ÊÇ·ñʹÓô°¿Úģʽ"), TEXT("OpenGL"),MB_YESNO | MB_ICONEXCLAMATION)==IDYES) { g_bFullscreen = FALSE; } else { ::MessageBox(NULL,TEXT("³ÌÐò¹Ø±Õ"),TEXT("Error"),MB_OK); return FALSE; } } } if (g_bFullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; ShowCursor(FALSE); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; } AdjustWindowRectEx(&wndRect,dwStyle,FALSE,dwExStyle); g_hMainWnd = CreateWindowEx (dwExStyle, g_strClassName, title, WS_CLIPCHILDREN| WS_CLIPSIBLINGS| dwStyle, 0, 0, wndRect.right - wndRect.left, wndRect.bottom- wndRect.top, NULL, NULL, g_hInst, NULL); if (!g_hMainWnd) { MessageBox(NULL,TEXT("´´½¨´°¿Úʧ°Ü"),TEXT("Error"),MB_OK | MB_ICONERROR); KillWindow(); return FALSE; } static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // ÉÏÊö¸ñʽÃèÊö·ûµÄ´óС 1, // °æ±¾ºÅ PFD_DRAW_TO_WINDOW | // ¸ñʽ֧³Ö´°¿Ú PFD_SUPPORT_OPENGL | // ¸ñʽ±ØÐëÖ§³ÖOpenGL PFD_DOUBLEBUFFER, // ±ØÐëÖ§³ÖË«»º³å PFD_TYPE_RGBA, // ÉêÇë RGBA ¸ñʽ bits, // Ñ¡¶¨É«²ÊÉî¶È 0, 0, 0, 0, 0, 0, // ºöÂÔµÄÉ«²Êλ 0, // ÎÞAlpha»º´æ 0, // ºöÂÔShift Bit 0, // ÎÞÀÛ¼Ó»º´æ 0, 0, 0, 0, // ºöÂÔ¾Û¼¯Î» 16, // 16λ Z-»º´æ (Éî¶È»º´æ) 0, // ÎÞÃɰ建´æ 0, // ÎÞ¸¨Öú»º´æ PFD_MAIN_PLANE, // Ö÷»æͼ²ã 0, // Reserved 0, 0, 0 // ºöÂÔ²ãÕÚÕÖ }; if ((g_hdc = GetDC(g_hMainWnd)) == NULL) { MessageBox(NULL,TEXT("GetDC ´íÎó"),TEXT("Error"),MB_OK | MB_ICONERROR); KillWindow(); return FALSE; } if (!(PixelFormat =ChoosePixelFormat(g_hdc,&pfd))) { MessageBox(NULL,TEXT("ChoosePixelFormat ´íÎó"),TEXT("Error"),MB_OK | MB_ICONERROR ); KillWindow(); return FALSE; } if (! SetPixelFormat(g_hdc,PixelFormat,&pfd)) { MessageBox(NULL,TEXT("SetPixelFormat ´íÎó"),TEXT("Error"),MB_OK | MB_ICONERROR ); KillWindow(); return FALSE; } if (!(g_hGlrc = wglCreateContext(g_hdc))) { MessageBox(NULL,TEXT("´´½¨OpenGLÉÏÏÂÎÄ´íÎó"),TEXT("Error"),MB_OK | MB_ICONERROR ); KillWindow(); return FALSE; } if(! wglMakeCurrent(g_hdc,g_hGlrc)) { MessageBox(NULL,TEXT("wglMakeCurrent´íÎó"),TEXT("Error"),MB_OK | MB_ICONERROR ); KillWindow(); return FALSE; } SetForegroundWindow(g_hMainWnd); SetFocus(g_hMainWnd); ShowWindow (g_hMainWnd, SW_SHOW); ResizeFunc(width,height); return InitOpenGL(); //UpdateWindow (g_hMainWnd); }
bool Window::PlatformInit() { hInstance = (HINSTANCE)&__ImageBase; WNDCLASS winClass = {}; winClass.hInstance = hInstance; // GetModuleHandle(0); winClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; winClass.lpfnWndProc = (WNDPROC)WndProc; winClass.lpszClassName = "Sparky Win32 Window"; winClass.hCursor = LoadCursor(NULL, IDC_ARROW); winClass.hIcon = LoadIcon(NULL, IDI_WINLOGO); if (!RegisterClassA(&winClass)) { // TODO: Handle error SPARKY_ERROR("Could not register Win32 class!"); return false; } RECT size = { 0, 0, m_Width, m_Height }; AdjustWindowRectEx(&size, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, false, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); hWnd = CreateWindowExA(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, winClass.lpszClassName, m_Title, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, GetSystemMetrics(SM_CXSCREEN) / 2 - m_Width / 2, GetSystemMetrics(SM_CYSCREEN) / 2 - m_Height / 2, // TODO: This requires some... attention size.right + (-size.left), size.bottom + (-size.top), NULL, NULL, hInstance, NULL); if (!hWnd) { SPARKY_ERROR("Could not create window!"); return false; } RegisterWindowClass(hWnd, this); hDc = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd = get_pixel_format(); int pixelFormat = ChoosePixelFormat(hDc, &pfd); if (pixelFormat) { if (!SetPixelFormat(hDc, pixelFormat, &pfd)) { SPARKY_ERROR("Failed setting pixel format!"); return false; } } else { SPARKY_ERROR("Failed choosing pixel format!"); return false; } HGLRC hrc = wglCreateContext(hDc); if (hrc) { if (!wglMakeCurrent(hDc, hrc)) { SPARKY_ERROR("Failed setting OpenGL context!"); return false; } } else { SPARKY_ERROR("Failed creating OpenGL context!"); return false; } if (glewInit() != GLEW_OK) { SPARKY_FATAL("Could not initialize GLEW!"); return false; } ShowWindow(hWnd, SW_SHOW); SetFocus(hWnd); // resize return true; }
// Entering this function, the following values must be valid // GLPREF_width,GLPREF_height: preferred width and height // GLPREF_windowed: do we want windowed or full screen mode // g_hWnd: handle to the window created for OpenGL // On exit from this function (if returned true) the following values will be set // GLSTATE_width,GLSTATE_height: real width and height of screen // hDC: device context of the window // GL_ResourceContext: OpenGL resource context // Saved_gammaValues: Initial gamma values bool OpenGL_Initialize(void) { char *errstr=""; int width,height; int pf; PIXELFORMATDESCRIPTOR pfd;//, pfd_copy; GLPREF_windowed=!gameStates.ogl.bFullScreen; if (FindArg("-gl_test1")){ GLSTATE_width = GLPREF_width; GLSTATE_height = GLPREF_height; }else{ if(!GLPREF_windowed) { // First set our display mode // Create direct draw surface int retval; devmode.dmSize=sizeof(devmode); devmode.dmBitsPerPel=16; devmode.dmPelsWidth=GLPREF_width; devmode.dmPelsHeight=GLPREF_height; devmode.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; if ((retval=FindArg("-gl_refresh"))){ devmode.dmDisplayFrequency=atoi(Args[retval+1]); if (devmode.dmDisplayFrequency>=60)//uhh, I hope no one actually wants a refresh lower than 60.. gag. devmode.dmFields|=DM_DISPLAYFREQUENCY; //printf("trying refresh %i hz\n",devmode.dmDisplayFrequency); } retval=ChangeDisplaySettings(&devmode,CDS_FULLSCREEN); if (retval!=DISP_CHANGE_SUCCESSFUL) { // we couldn't switch to the desired screen mode // fall back to 640x480 retval=-1; devmode.dmBitsPerPel=16; devmode.dmPelsWidth=640; devmode.dmPelsHeight=480; devmode.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; retval=ChangeDisplaySettings(&devmode,CDS_FULLSCREEN); if (retval!=DISP_CHANGE_SUCCESSFUL) { errstr="ChangeDisplaySettings"; // we couldn't even switch to 640x480, we're out of here // restore screen mode to default ChangeDisplaySettings(NULL,0); goto OpenGLError; }else { // successful, change our global settings to reflect what // mode we are at GLPREF_width=640; GLPREF_height=480; } }else { // success at changing the video mode } } if(GLPREF_windowed) { // we want windowed mode, figure out how big the window is RECT rect; GetWindowRect(g_hWnd,&rect); width=abs(rect.right-rect.left); height=abs(rect.bottom-rect.top); }else { RECT rect; // full screen mode, we want the window to be on top of everything SetWindowPos(g_hWnd,HWND_TOPMOST,0,0,GLPREF_width,GLPREF_height,SWP_FRAMECHANGED); width=GLPREF_width; height=GLPREF_height; GetWindowRect(g_hWnd,&rect); } GLSTATE_width = width; GLSTATE_height = height; } hDC = GetDC(g_hWnd); // Now we finally setup OpenGL // If OpenGL is to be dynamically loaded, do this now (if the DLL isn't already // loaded) // remove the following error when you figure out what you want to do // it's put here to make sure you notice this #ifdef OGL_RUNTIME_LOAD OglInitLoadLibrary(); #endif // Setup our pixel format memset(&pfd,0,sizeof(pfd); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; // pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_GENERIC_ACCELERATED; pfd.iPixelType = PFD_TYPE_RGBA; //let the ogl driver decide. (fixes no hw accel in 16bit mode in w2k with tnt2) // pfd.cColorBits = 16; // pfd.cAlphaBits = 8; // pfd.cDepthBits = 0; // pfd.cAccumBits = 0; // pfd.cStencilBits = 0; pfd.iLayerType = PFD_MAIN_PLANE; pfd.dwLayerMask = PFD_MAIN_PLANE; // Find the user's "best match" PFD pf = ChoosePixelFormat(hDC,&pfd); if(pf == 0) { errstr="ChoosePixelFormat"; // no pixel format closely matches goto OpenGLError; } // Set the new PFD if(SetPixelFormat(hDC,pf,&pfd)==FALSE) { errstr="SetPixelFormat"; // unable to set the pixel format goto OpenGLError; } // Now retrieve the PFD, we need to check some things /* if(DescribePixelFormat(hDC,pf,sizeof(PIXELFORMATDESCRIPTOR),&pfd_copy)==0) { errstr="DescribePixelFormat"; // unable to get the PFD goto OpenGLError; } // Make sure we are hardware accelerated if((pfd_copy.dwFlags&PFD_GENERIC_ACCELERATED)==0&&(pfd_copy.dwFlags&PFD_GENERIC_FORMAT)!=0) { // we are not hardware accelerated! goto OpenGLError; }*/ // Finally, create our OpenGL context and make it current GL_ResourceContext = wglCreateContext(hDC); if(GL_ResourceContext==NULL) { errstr="wglCreateContext"; // we couldn't create a context! goto OpenGLError; } // Make the context current wglMakeCurrent(hDC,GL_ResourceContext); // Save our gamma values because we'll probably be changing them, // this way we can restore them on exit // GetDeviceGammaRamp(hDC,(LPVOID)Saved_gammaValues); return true; OpenGLError: // Shutdown OpenGL OpenGL_Shutdown(); Error("opengl init error: %s\n",errstr); return false; }
Error ContextGL_Win::initialize() { static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 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 }; hDC = GetDC(hWnd); if (!hDC) { MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } pixel_format = ChoosePixelFormat(hDC, &pfd); if (!pixel_format) // Did Windows Find A Matching Pixel Format? { MessageBox(NULL, "Can't Find A Suitable pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } BOOL ret = SetPixelFormat(hDC, pixel_format, &pfd); if (!ret) // Are We Able To Set The Pixel Format? { MessageBox(NULL, "Can't Set The pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } hRC = wglCreateContext(hDC); if (!hRC) // Are We Able To Get A Rendering Context? { MessageBox(NULL, "Can't Create A Temporary GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } wglMakeCurrent(hDC, hRC); if (opengl_3_context) { int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, //we want a 3.3 context WGL_CONTEXT_MINOR_VERSION_ARB, 3, //and it shall be forward compatible so that we can only use up to date functionality WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | _WGL_CONTEXT_DEBUG_BIT_ARB, 0 }; //zero indicates the end of the array PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; //pointer to the method wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARB == NULL) //OpenGL 3.0 is not supported { MessageBox(NULL, "Cannot get Proc Address for CreateContextAttribs", "ERROR", MB_OK | MB_ICONEXCLAMATION); wglDeleteContext(hRC); return ERR_CANT_CREATE; } HGLRC new_hRC = wglCreateContextAttribsARB(hDC, 0, attribs); if (!new_hRC) { wglDeleteContext(hRC); MessageBox(NULL, "Can't Create An OpenGL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return false } wglMakeCurrent(hDC, NULL); wglDeleteContext(hRC); hRC = new_hRC; if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { MessageBox(NULL, "Can't Activate The GL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return ERR_CANT_CREATE; // Return FALSE } printf("Activated GL 3.3 context"); } wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); //glWrapperInit(wrapper_get_proc_address); return OK; }
bool COpenGLControl::InitOpenGL(HINSTANCE hInstance, HWND* a_hWnd, int iMajorVersion, int iMinorVersion, void (*a_InitScene)(LPVOID), void (*a_RenderScene)(LPVOID), void(*a_ReleaseScene)(LPVOID), LPVOID lpParam) { if(!InitGLEW(hInstance))return false; hWnd = a_hWnd; hDC = GetDC(*hWnd); bool bError = false; PIXELFORMATDESCRIPTOR pfd; if(iMajorVersion <= 2) { 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 iPixelFormat = ChoosePixelFormat(hDC, &pfd); if (iPixelFormat == 0)return false; if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false; // Create the old style context (OpenGL 2.1 and before) hRC = wglCreateContext(hDC); if(hRC)wglMakeCurrent(hDC, hRC); else bError = true; } else if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format) { const int iPixelFormatAttribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0 // End of attributes list }; int iContextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 // End of attributes list }; int iPixelFormat, iNumFormats; wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats); // PFD seems to be only redundant parameter now if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false; hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs); // If everything went OK if(hRC) wglMakeCurrent(hDC, hRC); else bError = true; } else bError = true; if(bError) { // Generate error messages char sErrorMessage[255], sErrorTitle[255]; sprintf(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion); sprintf(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion); MessageBox(*hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION); return false; } RenderScene = a_RenderScene; InitScene = a_InitScene; ReleaseScene = a_ReleaseScene; if(InitScene != NULL)InitScene(lpParam); return true; }
GLUSboolean GLUSAPIENTRY glusCreateWindow(const char* title, GLUSuint width, GLUSuint height, GLUSboolean fullscreen) { GLUSint attribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; 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 }; GLUSuint 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_fullscreen=fullscreen; // Set The Global Fullscreen Flag g_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 = g_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 = "GLUS"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { return GLUS_FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = 32; // 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) { glusDestroyWindow(); return GLUS_FALSE; } } if (fullscreen) { 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 (!(g_hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window "GLUS", // 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 g_hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { glusDestroyWindow(); return GLUS_FALSE; } if (!(g_hDC = GetDC(g_hWnd))) // Did We Get A Device Context? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(g_hDC, &pfd))) // Did Windows Find A Matching Pixel Format? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if(!SetPixelFormat(g_hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(g_hRC=wglCreateContext(g_hDC))) // Are We Able To Get A Rendering Context? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if(!wglMakeCurrent(g_hDC, g_hRC)) // Try To Activate The Rendering Context { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (g_major >= 3) { PFNWGLCREATECONTEXTATTRIBSARBPROCTEMP wglCreateContextAttribsARBTemp = NULL; HGLRC hRCTemp = NULL; GLUSint attribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 1, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB, 0, 0, 0 }; attribList[1] = g_major; attribList[3] = g_minor; //attribList[5] = g_flags; if (!(wglCreateContextAttribsARBTemp = (PFNWGLCREATECONTEXTATTRIBSARBPROCTEMP)wglGetProcAddress("wglCreateContextAttribsARB"))) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(hRCTemp = wglCreateContextAttribsARBTemp(g_hDC, 0, attribList))) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if(!wglMakeCurrent(NULL, NULL)) { wglDeleteContext(hRCTemp); glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!wglDeleteContext(g_hRC)) { wglDeleteContext(hRCTemp); glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } g_hRC = hRCTemp; if(!wglMakeCurrent(g_hDC, g_hRC)) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } } ShowWindow(g_hWnd, SW_SHOW); // Show The Window SetForegroundWindow(g_hWnd); // Slightly Higher Priority SetFocus(g_hWnd); // Sets Keyboard Focus To The Window g_width = width; g_height = height; return GLUS_TRUE; // Success }
xdl_int XdevLOpenGLWGL::initOpenGL() { m_DC = GetDC(m_wnd); if(m_DC == NULL) { XDEVL_MODULE_ERROR("GetDC() failed."); return ERR_ERROR; } 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 = m_attributes.color_buffer_size; pfd.cDepthBits = m_attributes.depth_size; pfd.cStencilBits = m_attributes.stencil_size; pfd.cRedBits = m_attributes.red_size; pfd.cGreenBits = m_attributes.green_size; pfd.cBlueBits = m_attributes.blue_size; pfd.cAlphaBits = m_attributes.alpha_size; pfd.iLayerType = PFD_MAIN_PLANE; int iPixelFormat = ChoosePixelFormat(m_DC, &pfd); if (FALSE == iPixelFormat) { XDEVL_MODULE_ERROR("ChoosePixelFormat failed.\n"); return ERR_ERROR; } if (SetPixelFormat(m_DC, iPixelFormat, &pfd) != TRUE) { XDEVL_MODULE_ERROR("SetPixelFormat failed.\n"); return ERR_ERROR; } // Create the old style context (OpenGL 2.1 and before) HGLRC hRC = wglCreateContext(m_DC); wglMakeCurrent(m_DC, hRC); wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); wglMakeCurrent(nullptr, nullptr); wglDeleteContext(hRC); if (wglCreateContextAttribsARB) { const int iPixelFormatAttribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, WGL_ACCUM_BITS_ARB, 0, WGL_RED_BITS_ARB, m_attributes.red_size, WGL_GREEN_BITS_ARB, m_attributes.green_size, WGL_BLUE_BITS_ARB, m_attributes.blue_size, WGL_ALPHA_BITS_ARB, m_attributes.alpha_size, 0 // End of attributes list }; int iPixelFormat, iNumFormats; if (wglChoosePixelFormatARB(m_DC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats) != TRUE) { XDEVL_MODULE_ERROR("wglChoosePixelFormatARB failed.\n"); return ERR_ERROR; } // PFD seems to be only redundant parameter now if (SetPixelFormat(m_DC, iPixelFormat, &pfd) != TRUE) { XDEVL_MODULE_ERROR("SetPixelFormat failed.\n"); return ERR_ERROR; } // // Set the core profile attributes. // std::vector<xdl_int> contextAttributes; contextAttributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); contextAttributes.push_back(m_attributes.context_major_version); contextAttributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); contextAttributes.push_back(m_attributes.context_minor_version); contextAttributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); if (m_attributes.context_profile_mask == XDEVL_OPENGL_CONTEXT_CORE_PROFILE) { contextAttributes.push_back(WGL_CONTEXT_CORE_PROFILE_BIT_ARB); } else if (m_attributes.context_profile_mask == XDEVL_OPENGL_CONTEXT_COMPATIBILITY) { contextAttributes.push_back(WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB); } else if (m_attributes.context_profile_mask == XDEVL_OPENGL_CONTEXT_ES1) { XDEVL_MODULE_ERROR("Not supported WGL_CONTEXT_PROFILE_MASK_ARB .\n"); return ERR_ERROR; } else if (m_attributes.context_profile_mask == XDEVL_OPENGL_CONTEXT_ES2) { XDEVL_MODULE_ERROR("Not supported WGL_CONTEXT_PROFILE_MASK_ARB .\n"); return ERR_ERROR; } else { XDEVL_MODULE_ERROR("Not supported WGL_CONTEXT_PROFILE_MASK_ARB .\n"); return ERR_ERROR; } // // Set the WGL_CONTEXT_FLAGS_ARB // if (m_attributes.context_flags != XDEVL_OPENGL_CONTEXT_FLAGS_NONE || (m_debugMode == xdl_true)) { contextAttributes.push_back(WGL_CONTEXT_FLAGS_ARB); if (m_debugMode == xdl_true) { contextAttributes.push_back(WGL_CONTEXT_DEBUG_BIT_ARB); } if (m_attributes.context_flags == XDEVL_OPENGL_CONTEXT_FLAGS_FORWARD_COMPATIBLE_BIT) { contextAttributes.push_back(WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB); } } contextAttributes.push_back(0); m_RC = wglCreateContextAttribsARB(m_DC, 0, contextAttributes.data()); if (nullptr == m_RC) { XDEVL_MODULE_ERROR("wglCreateContextAttribsARB failed.\n"); return ERR_ERROR; } // If everything went OK if (wglMakeCurrent(m_DC, m_RC) != TRUE) { XDEVL_MODULE_ERROR("wglMakeCurrent failed.\n"); return ERR_ERROR; } } else { // Are We Able To Get A Rendering Context? m_RC = wglCreateContext(m_DC); if (nullptr == m_RC) { XDEVL_MODULE_ERROR("Could not create GL context.\n"); return ERR_ERROR; } } return ERR_OK; }
/* ** OS Specific windowing context creation - essential for creating the OpenGL drawing context */ AESDK_OpenGL_Err AESDK_OpenGL_Startup(AESDK_OpenGL_EffectCommonData& inData) { AESDK_OpenGL_Err result = AESDK_OpenGL_OK; inData.mUsingShaderB = false; //default value try { #ifdef AE_OS_WIN WNDCLASSEX winClass; MSG uMsg; ::memset(&uMsg,0,sizeof(uMsg)); winClass.lpszClassName = "AESDK_OpenGL_Win_Class"; winClass.cbSize = sizeof(WNDCLASSEX); winClass.style = CS_HREDRAW | CS_VREDRAW; winClass.lpfnWndProc = ::DefWindowProc; winClass.hInstance = NULL; winClass.hIcon = NULL; winClass.hIconSm = NULL; winClass.hCursor = ::LoadCursor(NULL, IDC_ARROW); winClass.hbrBackground = (HBRUSH)::GetStockObject(BLACK_BRUSH); winClass.lpszMenuName = NULL; winClass.cbClsExtra = 0; winClass.cbWndExtra = 0; if( !(::RegisterClassEx(&winClass)) ) GL_CHECK(AESDK_OpenGL_OS_Load_Err); inData.mHWnd = ::CreateWindowEx( NULL, "AESDK_OpenGL_Win_Class", "OpenGL-using FBOs in AE", 0,0, 0, 50, 50, NULL, NULL, NULL, NULL ); if( inData.mHWnd == NULL ) GL_CHECK(AESDK_OpenGL_OS_Load_Err); GLuint PixelFormat; PIXELFORMATDESCRIPTOR pfd; ::ZeroMemory( &pfd, sizeof( pfd ) ); 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.cDepthBits = 8; inData.mHDC = ::GetDC( inData.mHWnd ); PixelFormat = ChoosePixelFormat( inData.mHDC, &pfd ); SetPixelFormat( inData.mHDC, PixelFormat, &pfd); inData.mHRC = wglCreateContext( inData.mHDC ); wglMakeCurrent( inData.mHDC, inData.mHRC ); //check for the appropriate extensions - EXT_framebuffer_object char *ext = (char*)glGetString( GL_EXTENSIONS ); if( ::strstr( ext, "EXT_framebuffer_object" ) == NULL ) { GL_CHECK(AESDK_OpenGL_Extensions_Err); } else { glIsRenderbufferEXT = (PFNGLISRENDERBUFFEREXTPROC)GetProcAddress("glIsRenderbufferEXT"); glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)GetProcAddress("glBindRenderbufferEXT"); glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)GetProcAddress("glDeleteRenderbuffersEXT"); glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)GetProcAddress("glGenRenderbuffersEXT"); glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)GetProcAddress("glRenderbufferStorageEXT"); glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)GetProcAddress("glGetRenderbufferParameterivEXT"); glIsFramebufferEXT = (PFNGLISFRAMEBUFFEREXTPROC)GetProcAddress("glIsFramebufferEXT"); glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)GetProcAddress("glBindFramebufferEXT"); glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)GetProcAddress("glDeleteFramebuffersEXT"); glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)GetProcAddress("glGenFramebuffersEXT"); glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)GetProcAddress("glCheckFramebufferStatusEXT"); glFramebufferTexture1DEXT = (PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)GetProcAddress("glFramebufferTexture1DEXT"); glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)GetProcAddress("glFramebufferTexture2DEXT"); glFramebufferTexture3DEXT = (PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)GetProcAddress("glFramebufferTexture3DEXT"); glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)GetProcAddress("glFramebufferRenderbufferEXT"); glGetFramebufferAttachmentParameterivEXT = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)GetProcAddress("glGetFramebufferAttachmentParameterivEXT"); glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)GetProcAddress("glGenerateMipmapEXT"); glActiveTexture = (PFNGLACTIVETEXTUREPROC)GetProcAddress("glActiveTexture"); if( !glIsRenderbufferEXT || !glBindRenderbufferEXT || !glDeleteRenderbuffersEXT || !glGenRenderbuffersEXT || !glRenderbufferStorageEXT || !glGetRenderbufferParameterivEXT || !glIsFramebufferEXT || !glBindFramebufferEXT || !glDeleteFramebuffersEXT || !glGenFramebuffersEXT || !glCheckFramebufferStatusEXT || !glFramebufferTexture1DEXT || !glFramebufferTexture2DEXT || !glFramebufferTexture3DEXT || !glFramebufferRenderbufferEXT|| !glGetFramebufferAttachmentParameterivEXT || !glGenerateMipmapEXT || !glActiveTexture) { GL_CHECK(AESDK_OpenGL_Extensions_Err); } } char *extP = (char*)glGetString( GL_EXTENSIONS ); if( ::strstr( extP, "GL_ARB_shading_language_100" ) == NULL ) { //This extension string indicates that the OpenGL Shading Language, // version 1.00, is supported. GL_CHECK(AESDK_OpenGL_ShaderInit_Err); } //check for the appropriate extensions - EXT_framebuffer_object if( ::strstr( extP, "GL_ARB_shader_objects" ) == NULL ) { GL_CHECK(AESDK_OpenGL_Extensions_Err); } else { glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)GetProcAddress("glCreateProgramObjectARB"); glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)GetProcAddress("glDeleteObjectARB"); glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)GetProcAddress("glUseProgramObjectARB"); glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)GetProcAddress("glCreateShaderObjectARB"); glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)GetProcAddress("glShaderSourceARB"); glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)GetProcAddress("glCompileShaderARB"); glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)GetProcAddress("glGetObjectParameterivARB"); glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)GetProcAddress("glAttachObjectARB"); glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)GetProcAddress("glGetInfoLogARB"); glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)GetProcAddress("glLinkProgramARB"); glGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)GetProcAddress("glGetUniformLocationARB"); glUniform4fARB = (PFNGLUNIFORM4FARBPROC)GetProcAddress("glUniform4fARB"); glUniform1iARB = (PFNGLUNIFORM1IARBPROC)GetProcAddress("glUniform1iARB"); if( !glCreateProgramObjectARB || !glDeleteObjectARB || !glUseProgramObjectARB || !glCreateShaderObjectARB || !glCreateShaderObjectARB || !glCompileShaderARB || !glGetObjectParameterivARB || !glAttachObjectARB || !glGetInfoLogARB || !glLinkProgramARB || !glGetUniformLocationARB || !glUniform4fARB || !glUniform1iARB ) { GL_CHECK(AESDK_OpenGL_Extensions_Err); } } #elif defined(AE_OS_MAC) Rect rect; SetRect(&rect, 0, 0, 50, 50); if ( noErr != CreateNewWindow(kDocumentWindowClass, kWindowStandardDocumentAttributes, &rect, &inData.mMacWnd)) GL_CHECK(AESDK_OpenGL_OS_Load_Err); GLint aAttribs[64]; u_short nIndexS= -1; // NO color index support aAttribs[++nIndexS]= AGL_RGBA; // double buffering aAttribs[++nIndexS]=AGL_DOUBLEBUFFER; // color aAttribs[++nIndexS] = AGL_RED_SIZE; aAttribs[++nIndexS] = 8; aAttribs[++nIndexS] = AGL_GREEN_SIZE; aAttribs[++nIndexS] = 8; aAttribs[++nIndexS] = AGL_BLUE_SIZE; aAttribs[++nIndexS] = 8; aAttribs[++nIndexS] = AGL_ALPHA_SIZE; aAttribs[++nIndexS] = 8; aAttribs[++nIndexS] = AGL_NONE; // get an appropriate pixel format AGLPixelFormat oPixelFormat = aglChoosePixelFormat( NULL, 0, aAttribs); if( oPixelFormat == NULL ) GL_CHECK(AESDK_OpenGL_OS_Load_Err); // create the context from the pixel format inData.mAGLContext = aglCreateContext(oPixelFormat,NULL); if( NULL == inData.mAGLContext ) GL_CHECK(AESDK_OpenGL_Extensions_Err); // otherwise clean-up the pixel format aglDestroyPixelFormat(oPixelFormat); //attach the window if ( !aglSetDrawable (inData.mAGLContext, GetWindowPort(inData.mMacWnd)) ) GL_CHECK(AESDK_OpenGL_Extensions_Err); glFlush(); aglSetCurrentContext(inData.mAGLContext); #endif } catch(AESDK_OpenGL_Err& err) { result = err; } return result; }
static bool InitializeOpenGL () { #if !USE_REAL_OPENGL_TO_CHECK return false; #endif bool hasGLSL = false; #ifdef _MSC_VER // setup minimal required GL HWND wnd = CreateWindowA( "STATIC", "GL", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 16, 16, NULL, NULL, GetModuleHandle(NULL), NULL ); HDC dc = GetDC( wnd ); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int fmt = ChoosePixelFormat( dc, &pfd ); SetPixelFormat( dc, fmt, &pfd ); HGLRC rc = wglCreateContext( dc ); wglMakeCurrent( dc, rc ); #elif defined(__APPLE__) CGLPixelFormatAttribute attributes[] = { kCGLPFAAccelerated, // no software rendering (CGLPixelFormatAttribute) 0 }; CGLPixelFormatAttribute attributes3[] = { kCGLPFAAccelerated, // no software rendering kCGLPFAOpenGLProfile, // core profile with the version stated below (CGLPixelFormatAttribute) kCGLOGLPVersion_3_2_Core, (CGLPixelFormatAttribute) 0 }; GLint num; CGLPixelFormatObj pix; // create legacy context CGLChoosePixelFormat(attributes, &pix, &num); if (pix == NULL) return false; CGLCreateContext(pix, NULL, &s_GLContext); if (s_GLContext == NULL) return false; CGLDestroyPixelFormat(pix); CGLSetCurrentContext(s_GLContext); // create core 3.2 context CGLChoosePixelFormat(attributes3, &pix, &num); if (pix == NULL) return false; CGLCreateContext(pix, NULL, &s_GLContext3); if (s_GLContext3 == NULL) return false; CGLDestroyPixelFormat(pix); #else int argc = 0; char** argv = NULL; glutInit(&argc, argv); glutCreateWindow("hlsl2glsltest"); glewInit(); #endif // check if we have GLSL const char* extensions = (const char*)glGetString(GL_EXTENSIONS); hasGLSL = extensions != NULL && strstr(extensions, "GL_ARB_shader_objects") && strstr(extensions, "GL_ARB_vertex_shader") && strstr(extensions, "GL_ARB_fragment_shader"); #if defined(__APPLE__) // using core profile; always has GLSL hasGLSL = true; #endif #ifdef _MSC_VER if (hasGLSL) { glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"); glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog"); glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv"); } #endif return hasGLSL; }
bool RenderContextOpenGLWin32::Initialize(Window& window, const RenderParameters_t& renderParameters) { Logger::GetInstance()->Debug("Initializing OpenGL context"); size_t colorBits, redBits, greenBits, blueBits, depthBits; size_t alphaBits = 0; size_t stencilBits = 0; switch (renderParameters.displayFormat) { case DISPLAY_FORMAT_A1R5G5B5: colorBits = 16; alphaBits = 1; redBits = blueBits = 5; greenBits = 6; break; case DISPLAY_FORMAT_A2R10G10B10: colorBits = 24; alphaBits = 2; redBits = greenBits = blueBits = 10; break; case DISPLAY_FORMAT_A8R8G8B8: colorBits = 24; alphaBits = 8; redBits = greenBits = blueBits = 8; break; case DISPLAY_FORMAT_R5G6B5: colorBits = 16; redBits = blueBits = 5; greenBits = 6; break; case DISPLAY_FORMAT_X1R5G5B5: colorBits = 16; redBits = greenBits = blueBits = 5; break; case DISPLAY_FORMAT_X8R8G8B8: colorBits = 24; redBits = greenBits = blueBits = 8; break; } switch (renderParameters.depthStencilBits) { case DEPTH_STENCIL_BITS_D15S1: depthBits = 15; stencilBits = 1; break; case DEPTH_STENCIL_BITS_D16: depthBits = 16; break; case DEPTH_STENCIL_BITS_D24S8: depthBits = 24; stencilBits = 8; break; case DEPTH_STENCIL_BITS_D24X4S4: depthBits = 24; stencilBits = 4; break; case DEPTH_STENCIL_BITS_D24X8: depthBits = 24; break; case DEPTH_STENCIL_BITS_D32: depthBits = 32; break; } if (!window.IsWindowed()) { // From http://www.falloutsoftware.com/tutorials/gl/gl2.htm DEVMODE dmode; memset(&dmode, 0, sizeof(DEVMODE)); dmode.dmSize=sizeof(DEVMODE); dmode.dmPelsWidth = renderParameters.width; dmode.dmPelsHeight = renderParameters.height; dmode.dmBitsPerPel = (colorBits == 24) ? 32 : colorBits; dmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Change resolution, if possible if (ChangeDisplaySettings(&dmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { Logger::GetInstance()->Warning("Couldn't set window to fullscreen mode"); } // Make the window flags compatible with fullscreen mode SetWindowLongW(window.GetHandle(), GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); SetWindowLongW(window.GetHandle(), GWL_EXSTYLE, WS_EX_APPWINDOW); SetWindowPos(window.GetHandle(), NULL, 0, 0, renderParameters.width, renderParameters.height, SWP_FRAMECHANGED); ShowWindow(window.GetHandle(), SW_SHOW); } deviceContext_ = GetDC(reinterpret_cast<HWND>(window.GetHandle())); if (!deviceContext_) { Logger::GetInstance()->Error("Couldn't retrieve device context"); return false; } PIXELFORMATDESCRIPTOR pixelFormat; ZeroMemory(&pixelFormat, sizeof(pixelFormat)); pixelFormat.nSize = sizeof(pixelFormat); pixelFormat.nVersion = 1; pixelFormat.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pixelFormat.iPixelType = PFD_TYPE_RGBA; pixelFormat.cColorBits = colorBits; pixelFormat.cDepthBits = depthBits; pixelFormat.cAlphaBits = alphaBits; pixelFormat.cRedBits = redBits; pixelFormat.cGreenBits = greenBits; pixelFormat.cBlueBits = blueBits; pixelFormat.cStencilBits = stencilBits; pixelFormat.iLayerType = PFD_MAIN_PLANE; int format = ChoosePixelFormat(deviceContext_, &pixelFormat); if (format == 0) { Logger::GetInstance()->Error("Failed to create a suitable pixel format " "for device context"); return false; } if (!SetPixelFormat(deviceContext_, format, &pixelFormat)) { Logger::GetInstance()->Error("Couldn't set the pixel format"); return false; } // Create a dummy context, because we are going to create a context using // an extension function HGLRC dummyRenderContext = wglCreateContext(deviceContext_); wglMakeCurrent(deviceContext_, dummyRenderContext); int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0, 0 }; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB")); renderContext_ = wglCreateContextAttribsARB(deviceContext_, NULL, attributes); if (!renderContext_) { wglDeleteContext(dummyRenderContext); Logger::GetInstance()->Error("Couldn't create render context"); return false; } if (!wglDeleteContext(dummyRenderContext)) { Logger::GetInstance()->Error("Couldn't delete dummy context"); return false; } if (!wglMakeCurrent(deviceContext_, renderContext_)) { Logger::GetInstance()->Error("Couldn't set the new rendering context"); return false; } if (GLEW_OK != glewInit()) { Logger::GetInstance()->Error("Couldn't initialize GLEW library"); return false; } Logger::GetInstance()->Debug("Render context created"); return true; }
GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly, unsigned char layer_type ) { #if TARGET_HOST_WINCE return GL_TRUE; #else PIXELFORMATDESCRIPTOR* ppfd, pfd; int flags, pixelformat; freeglut_return_val_if_fail( window != NULL, 0 ); flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; if( fgState.DisplayMode & GLUT_DOUBLE ) flags |= PFD_DOUBLEBUFFER; #if defined(_MSC_VER) #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" ) #endif /* Specify which pixel format do we opt for... */ pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = flags; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; 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; #if 0 pfd.cDepthBits = 32; pfd.cStencilBits = 0; #else pfd.cDepthBits = 24; pfd.cStencilBits = 8; #endif if( fgState.DisplayMode & GLUT_AUX4 ) pfd.cAuxBuffers = 4; else if( fgState.DisplayMode & GLUT_AUX3 ) pfd.cAuxBuffers = 3; else if( fgState.DisplayMode & GLUT_AUX2 ) pfd.cAuxBuffers = 2; else if( fgState.DisplayMode & GLUT_AUX1 ) pfd.cAuxBuffers = 1; else pfd.cAuxBuffers = 0; pfd.iLayerType = layer_type; pfd.bReserved = 0; pfd.dwLayerMask = 0; pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; pfd.cColorBits = (BYTE) GetDeviceCaps( window->Window.Device, BITSPIXEL ); ppfd = &pfd; pixelformat = ChoosePixelFormat( window->Window.Device, ppfd ); if( pixelformat == 0 ) return GL_FALSE; if( checkOnly ) return GL_TRUE; return SetPixelFormat( window->Window.Device, pixelformat, ppfd ); #endif /* TARGET_HOST_WINCE */ }
HGLRC GL_GenerateRC(HDC hDC, bool bDoubleBuffer/* = true*/) { HGLRC hRC = NULL; if (1/*RunningNT() || bCalledFromMainCellView*/) { static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this struct 1, // struct version PFD_DRAW_TO_WINDOW | // draw to window (not bitmap) // PFD_DOUBLEBUFFER | // double buffered mode PFD_SUPPORT_OPENGL, // support opengl in window PFD_TYPE_RGBA, // RGBA colour mode 24, // want 24bit colour 0,0,0,0,0,0, // not used to select mode 0,0, // not used to select mode 0,0,0,0,0, // not used to select mode 32, // size of depth buffer 0, // not used to select mode 0, // not used to select mode PFD_MAIN_PLANE, // draw in main plane 0, // not used to select mode 0,0,0 // not used to select mode }; if (bDoubleBuffer) { pfd.dwFlags |= PFD_DOUBLEBUFFER; } // choose a pixel format that best matches the one we want... // int iPixelFormat = GLW_ChoosePFD(hDC,&pfd); // try and choose best hardware mode if (iPixelFormat == 0) { // nothing decent found, fall bac to whatever crap the system recommends... // iPixelFormat = ChoosePixelFormat(hDC,&pfd); } // // set the pixel format for this device context... // //JAC FIXME - assertion failed //VERIFY(SetPixelFormat(hDC, iPixelFormat, &pfd)); SetPixelFormat(hDC, iPixelFormat, &pfd); // // create the rendering context... // hRC = wglCreateContext(hDC); if (hRC) { // // make the rendering context current, init, then deselect... // VERIFY(wglMakeCurrent(hDC,hRC)); // first one in creates the global RC, everyone else shares lists with it... // if (g_hRC) { ASSERT_GL; VERIFY(wglShareLists(g_hRC,hRC)); ASSERT_GL; } else { g_hRC = hRC; g_hDC = hDC; // record vendor strings for later display... // csGLVendor = glGetString (GL_VENDOR); csGLRenderer = glGetString (GL_RENDERER); csGLVersion = glGetString (GL_VERSION); csGLExtensions = glGetString (GL_EXTENSIONS); // // for the moment I'll insist on 24 bits and up (texture loading reasons, plus GL issues) // { HDC _hDC = GetDC( GetDesktopWindow() ); int iDesktopBitDepth = GetDeviceCaps( _hDC, BITSPIXEL ); if (iDesktopBitDepth == 8) { WarningBox(va("Your desktop is only %d bit!,\n\nChange the bitdepth to 16 or more (65536 colours or over) and re-run.",iDesktopBitDepth)); } ReleaseDC( GetDesktopWindow(), _hDC ); } } // VERIFY(wglMakeCurrent(NULL,NULL)); // leave context running! } } return hRC; }
bool GL_Init(HWND window, std::string *error_message) { *error_message = "ok"; hWnd = window; GLuint PixelFormat; 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 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 }; hDC = GetDC(hWnd); if (!hDC) { *error_message = "Failed to get a device context."; return false; // Return FALSE } // Did Windows Find A Matching Pixel Format? if (!(PixelFormat = ChoosePixelFormat(hDC,&pfd))) { *error_message = "Can't Find A Suitable PixelFormat."; return false; } // Are We Able To Set The Pixel Format? if (!SetPixelFormat(hDC,PixelFormat,&pfd)) { *error_message = "Can't Set The PixelFormat."; return false; } // Are We Able To Get A Rendering Context? if (!(hRC = wglCreateContext(hDC))) { *error_message = "Can't Create A GL Rendering Context."; return false; } // Try To Activate The Rendering Context if (!wglMakeCurrent(hDC,hRC)) { *error_message = "Can't activate the GL Rendering Context."; return false; } if (GLEW_OK != glewInit()) { *error_message = "Failed to initialize GLEW."; return false; } // Alright, now for the modernity. static const int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, enableGLDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0, 0 }; HGLRC m_hrc; if(wglewIsSupported("WGL_ARB_create_context") == 1) { m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs); 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 (!m_hrc) { *error_message = "No m_hrc"; return false; } hRC = m_hrc; //Checking GL version const char *GLVersionString = (const char *)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]); glstate.Initialize(); CheckGLExtensions(); GL_SetVSyncInterval(0); if (enableGLDebug && glewIsSupported("GL_ARB_debug_output")) { glDebugMessageCallbackARB((GLDEBUGPROCARB)&DebugCallbackARB, 0); // print debug output to stderr glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); } GL_Resized(); // Set Up Our Perspective GL Screen 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); } 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 wgl_FindBestPF(HDC hDC, int *nRegularFormat, int *nMSFormat) { *nRegularFormat = 0; *nMSFormat = 0; // easy check, just look for the entrypoint if(gltIsWGLExtSupported(hDC, "WGL_ARB_pixel_format")) if(wglGetPixelFormatAttribivARB == NULL) wglGetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB"); // First try to use new extended wgl way if(wglGetPixelFormatAttribivARB != NULL) { // Only care about these attributes int nBestMS = 0; int i; int iResults[9]; int iAttributes [9] = { WGL_SUPPORT_OPENGL_ARB, // 0 WGL_ACCELERATION_ARB, // 1 WGL_DRAW_TO_WINDOW_ARB, // 2 WGL_DOUBLE_BUFFER_ARB, // 3 WGL_PIXEL_TYPE_ARB, // 4 WGL_DEPTH_BITS_ARB, // 5 WGL_STENCIL_BITS_ARB, // 6 WGL_SAMPLE_BUFFERS_ARB, // 7 WGL_SAMPLES_ARB}; // 8 // How many pixelformats are there? int nFormatCount[] = { 0 }; int attrib[] = { WGL_NUMBER_PIXEL_FORMATS_ARB }; wglGetPixelFormatAttribivARB(hDC, 1, 0, 1, attrib, nFormatCount); // Loop through all the formats and look at each one for(i = 0; i < nFormatCount[0]; i++) { // Query pixel format wglGetPixelFormatAttribivARB(hDC, i+1, 0, 10, iAttributes, iResults); // Match? Must support OpenGL AND be Accelerated AND draw to Window if(iResults[0] == 1 && iResults[1] == WGL_FULL_ACCELERATION_ARB && iResults[2] == 1) if(iResults[3] == 1) // Double buffered if(iResults[4] == WGL_TYPE_RGBA_ARB) // Full Color if(iResults[5] >= 16) // Any Depth greater than 16 if(iResults[6] > 0) // Any Stencil depth (not zero) { // We have a candidate, look for most samples if multisampled if(iResults[7] == 1) // Multisampled { if(iResults[8] > nBestMS) // Look for most samples { *nMSFormat = i; // Multisamples nBestMS = iResults[8]; // Looking for the best } } else // Not multisampled { // Good enough for "regular". This will fall through *nRegularFormat = i; } } } } else { // Old fashioned way... // or multisample PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, // Full color 32, // Color depth 0,0,0,0,0,0,0, // Ignored 0,0,0,0, // Accumulation buffer 24, // Depth bits 8, // Stencil bits 0,0,0,0,0,0 }; // Some used, some not *nRegularFormat = ChoosePixelFormat(hDC, &pfd); } }
bool WindowsGLContext::Init(HINSTANCE hInst, 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; SwapInterval(0); if (g_Config.bGfxDebugOutput) { if (wglewIsSupported("GL_KHR_debug") == 1) { glGetError(); glDebugMessageCallback((GLDEBUGPROC)&DebugCallbackARB, nullptr); if (glGetError()) { ERROR_LOG(G3D, "Failed to register a debug log callback"); } glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); if (glGetError()) { ERROR_LOG(G3D, "Failed to enable synchronous debug output"); } } else if (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); } glEnable(GL_DEBUG_OUTPUT); } pauseRequested = false; resumeRequested = false; // These are auto-reset events. pauseEvent = CreateEvent(NULL, FALSE, FALSE, NULL); resumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL); return true; // Success }
HRESULT CVCamStream::OpenReceiver() { HDC hdc = NULL; HWND hwnd = NULL; HGLRC hRc = NULL; // char windowtitle[512]; glContext = wglGetCurrentContext(); // Once created it seems stable and retained if(glContext == NULL) { // We only need an OpenGL context with no render window because we don't draw to it // so create an invisible dummy button window. This is then independent from the host // program window (GetForegroundWindow). If SetPixelFormat has been called on the // host window it cannot be called again. This caused a problem in Mapio and could be // a problem with VirtualDJ. // // Microsoft : // // https://msdn.microsoft.com/en-us/library/windows/desktop/dd369049%28v=vs.85%29.aspx // // If hdc references a window, calling the SetPixelFormat function also changes the pixel // format of the window. Setting the pixel format of a window more than once can lead to // significant complications for the Window Manager and for multithread applications, // so it is not allowed. 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. // if(!hwndButton || !IsWindow(hwndButton)) { hwndButton = CreateWindowA("BUTTON", "Spout Cam", WS_OVERLAPPEDWINDOW, 0, 0, 32, 32, NULL, NULL, NULL, NULL); } // hwndButton = GetForegroundWindow(); // causes problems with Mapio if(!hwndButton) { printf("InitOpenGL error 1\n"); MessageBoxA(NULL, "Error 1\n", "InitOpenGL", MB_OK); return S_FALSE; } hdc = GetDC(hwndButton); if(!hdc) { printf("InitOpenGL error 2\n"); MessageBoxA(NULL, "Error 2\n", "InitOpenGL", MB_OK); return S_FALSE; } // GetWindowTextA(hwndButton, windowtitle, 256); // debug 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.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; int iFormat = ChoosePixelFormat(hdc, &pfd); if(!iFormat) { printf("InitOpenGL error 3\n"); MessageBoxA(NULL, "Error 3\n", "InitOpenGL", MB_OK); return S_FALSE; } if(!SetPixelFormat(hdc, iFormat, &pfd)) { DWORD dwError = GetLastError(); printf("InitOpenGL error 4 (Error %d (%x))\n", dwError, dwError); // 2000 (0x7D0) The pixel format is invalid. // Caused by repeated call of the SetPixelFormat function char temp[128]; sprintf_s(temp, "InitOpenGL Error 4\nSetPixelFormat\nError %d (%x)", dwError, dwError); MessageBoxA(NULL, temp, "InitOpenGL", MB_OK); return S_FALSE; } hRc = wglCreateContext(hdc); if(!hRc) { printf("InitOpenGL error 5\n"); MessageBoxA(NULL, "Error 5\n", "InitOpenGL", MB_OK); return S_FALSE; } wglMakeCurrent(hdc, hRc); if(wglGetCurrentContext() == NULL) { printf("InitOpenGL error 6\n"); MessageBoxA(NULL, "Error 6\n", "InitOpenGL", MB_OK); return S_FALSE; } // Drop through to return true // printf("InitOpenGL : hwnd = %x (%s), hdc = %x, context = %x\n", hwnd, windowtitle, hdc, hRc); // int nCurAvailMemoryInKB = 0; // glGetIntegerv(0x9049, &nCurAvailMemoryInKB); // printf("Memory available [%i]\n", nCurAvailMemoryInKB); /* // Glut method (glut.dll dependency) // You need to create a rendering context BEFORE calling glutInit() // First you need to create a valid OpenGL rendering context and call glewInit() // to initialize the extension entry points. HDC GLhdc; int argc = 1; char *argv = (char*)"vCam"; char **vptr = &argv; glutInit(&argc, vptr); // In this case there is not be a rendering context. There is if an external window is present // but we don't know what it is. So create a window here but it will not show. glutCreateWindow("vCamGL"); GLhdc = wglGetCurrentDC(); GLhwnd = WindowFromDC(GLhdc); */ } // end no glcontext /* #ifdef UseD3D9 receiver.SetDX9(true); #else receiver.SetDX9(false); // Set to DX9 for compatibility with Version 1 apps #endif */ // This is a receiver so try to connect if(receiver.CreateReceiver(SharedMemoryName, senderWidth, senderHeight)) { return NO_ERROR; } return S_FALSE; } // end OpenReceiver
bool COpenGL::Initialize(HWND hWnd) { int pfdIndex; RECT windowRect; this->hWnd = hWnd; this->hDC = GetDC(hWnd); 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 16, // 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 }; PIXELFORMATDESCRIPTOR pfdSel; if(!(pfdIndex=ChoosePixelFormat(hDC,&pfd))) { DeInitialize(); return false; } if(!SetPixelFormat(hDC,pfdIndex,&pfd)) { DeInitialize(); return false; } if(!(hRC=wglCreateContext(hDC))) { DeInitialize(); return false; } if(!wglMakeCurrent(hDC,hRC)) { DeInitialize(); return false; } LoadPBOFunctions(); wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho (0.0, 1.0, 0.0, 1.0, -1, 1); glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texcoords); cgAvailable = loadCgFunctions(); if(cgAvailable) { cgContext = cgCreateContext(); cgShader = new CGLCG(cgContext); } ApplyDisplayChanges(); glClearColor(0.0f, 0.0f, 0.0f, 0.5f); glClear(GL_COLOR_BUFFER_BIT); SwapBuffers(hDC); initDone = true; return true; }
//---------------------------------------------------------------------------- bool Renderer_GL::Init(HWND hWnd, HDC hdc) { logger->Write("[OpenGL] Initializing OpenGL\n"); this->hdc = hdc; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags PFD_TYPE_RGBA, //The kind of framebuffer. RGBA or palette. 32, //Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, //Number of bits for the depthbuffer 8, //Number of bits for the stencilbuffer 0, //Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pFormat = ChoosePixelFormat(hdc, &pfd); if (pFormat == 0) { // Windows could not find a format for our needs. logger->Write("[OpenGL] Error choosing pixel Format\n"); return false; } if (!SetPixelFormat(hdc, pFormat, &pfd)) { // Our format was not valid logger->Write("[OpenGL] Error setting pixel Format\n"); return false; } // Temporary OpenGL 2.1 Context used to springboard our 3.0+ Context HGLRC temp = wglCreateContext(hdc); wglMakeCurrent (hdc, temp); // Enable GLEW GLenum error = glewInit(); if (error != GLEW_OK) { // Can not init GLEW return false; } int attr[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { // Success, create new context and switch to it hglrc = wglCreateContextAttribsARB(hdc, NULL, attr); wglMakeCurrent(NULL, NULL); wglDeleteContext(temp); wglMakeCurrent(hdc, hglrc); } else { // Our level not supported, Use temp 2.1 OpenGL hglrc = temp; } #ifdef DEBUG glEnable(GL_DEBUG_OUTPUT); #endif // Dump our GL Versions to verify int glVersion[2] = {-1, -1}; glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); char buffer [50]; int bufferLen = sprintf (buffer, "[OpenGL] Successfully intialized OpenGL %d.%d\n",glVersion[0], glVersion[1]); //std::cout << "Using OpenGL: " << glVersion[0] << "." << glVersion[1] << std::endl; logger->Write(buffer); renderable = new Renderable(); m_logger = *(this->logger); const GLvoid *userParam; glDebugMessageCallback(glDebug, (const GLvoid *) userParam); log_gl_params(); // Success return true; }
void createGLContext(Win32Window* const win32Window, Window* const window) { // Create the GL context. int pixelFormat = 0; PIXELFORMATDESCRIPTOR pfd; DWORD dwStyle = WS_OVERLAPPEDWINDOW; DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; 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 = 24; pfd.cDepthBits = 24; pfd.cStencilBits = 8; pfd.iLayerType = PFD_MAIN_PLANE; win32Window->deviceContext = GetDC(win32Window->windowContext); pixelFormat = ChoosePixelFormat(win32Window->deviceContext, &pfd); SetPixelFormat(win32Window->deviceContext, pixelFormat, &pfd); win32Window->renderingContext = wglCreateContext(win32Window->deviceContext); wglMakeCurrent(win32Window->deviceContext, win32Window->renderingContext); if (CSR_ENABLE_MULTISAMPLING) { int pixelAttribs[] = { WGL_SAMPLES_ARB, 16, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_RED_BITS_ARB, 8, WGL_GREEN_BITS_ARB, 8, WGL_BLUE_BITS_ARB, 8, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, 0 }; int* sampleCount = pixelAttribs + 1; int* useSampleBuffer = pixelAttribs + 3; int pixelFormat = -1; PROC proc = wglGetProcAddress("wglChoosePixelFormatARB"); unsigned int numFormats = 0; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)proc; if (!wglChoosePixelFormatARB) printf("Could not load function pointer for 'wglChoosePixelFormatARB'. Is your driver properly installed?"); // Try fewer and fewer samples per pixel till we find one that is supported: while (pixelFormat <= 0 && *sampleCount >= 0) { wglChoosePixelFormatARB(win32Window->deviceContext, pixelAttribs, 0, 1, &pixelFormat, &numFormats); (*sampleCount)--; if (*sampleCount <= 1) *useSampleBuffer = GL_FALSE; } // Win32 allows the pixel format to be set only once per app, so destroy and re-create the app: DestroyWindow(win32Window->windowContext); win32Window->windowContext = CreateWindowEx(dwExStyle, CSR_WIN32_WINDOW_CLASS_NAME, window->Title, dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, window->X, window->Y, window->Width, window->Height, 0, 0, win32Window->moduleHandle, 0); SetWindowPos(win32Window->windowContext, HWND_TOP, window->X, window->Y, window->Width, window->Height, 0); win32Window->deviceContext = GetDC(win32Window->windowContext); bool setPixFormat = SetPixelFormat(win32Window->deviceContext, pixelFormat, &pfd); win32Window->renderingContext = wglCreateContext(win32Window->deviceContext); wglMakeCurrent(win32Window->deviceContext, win32Window->renderingContext); } // initialize glew { GLint err = glewInit(); if (GLEW_OK != err) { printf("GLEW Error: %s\n", glewGetErrorString(err)); return; } printf("OpenGL Version: %s\n", glGetString(GL_VERSION)); } Window_SetVSync(window, CSR_ENABLE_VSYNC); // make GL3+ context (forward compatible) if (GL_VERSION_3_0) { const int contextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; HGLRC newRC = wglCreateContextAttribsARB(win32Window->deviceContext, 0, contextAttribs); wglMakeCurrent(0, 0); wglDeleteContext(win32Window->renderingContext); win32Window->renderingContext = newRC; wglMakeCurrent(win32Window->deviceContext, win32Window->renderingContext); } ShowWindow(win32Window->windowContext, SW_SHOW); }
/**************************************************************************** SetupWindow() Creates a window and the device and rendering contexts for it. *****************************************************************************/ BOOL SetupWindow(char *title, int width, int height, int bits, bool isFullscreen) { // set the global flag g_isFullScreen = isFullscreen; // get our instance handle g_hInstance = GetModuleHandle(NULL); WNDCLASSEX wc; // window class // fill out the window class structure wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = g_hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow wc.hbrBackground = NULL; //(HBRUSH) GetStockObject(BLACK_BRUSH); // black background wc.lpszMenuName = NULL; // no menu wc.lpszClassName = WND_CLASS_NAME; // register the windows class if (!RegisterClassEx(&wc)) { MessageBox(NULL,"Unable to register the window class", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Exit And Return FALSE } // if we're in fullscreen mode, set the display up for it if (g_isFullScreen) { // set up the device mode structure DEVMODE screenSettings; memset(&screenSettings,0,sizeof(screenSettings)); screenSettings.dmSize = sizeof(screenSettings); screenSettings.dmPelsWidth = width; // screen width screenSettings.dmPelsHeight = height; // screen height screenSettings.dmBitsPerPel = bits; // bits per pixel screenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // attempt to switch to the resolution and bit depth we've selected if (ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { g_isFullScreen = FALSE; } } DWORD dwExStyle; DWORD dwStyle; // if we're still in fullscreen mode, set the window style appropriately if (g_isFullScreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; // simple window with no borders or title bar ShowCursor(FALSE); // hide the cursor for now } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; } // set up the window we're rendering to so that the top left corner is at (0,0) // and the bottom right corner is (height,width) RECT windowRect; windowRect.left = 0; windowRect.right = (LONG) width; windowRect.top = 0; windowRect.bottom = (LONG) height; // change the size of the rect to account for borders, etc. set by the style AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); // class registered, so now create our window g_hwnd = CreateWindowEx(dwExStyle, // extended style WND_CLASS_NAME, // class name title, // app name dwStyle | // window style WS_CLIPCHILDREN | // required for WS_CLIPSIBLINGS, // using OpenGL 0, 0, // x,y coordinate windowRect.right - windowRect.left, // width windowRect.bottom - windowRect.top, // height NULL, // handle to parent NULL, // handle to menu g_hInstance, // application instance NULL); // no extra params // see if our window handle is valid if (!g_hwnd) { // reset the display KillWindow(); MessageBox(NULL, "Unable to create window", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } // get a device context if (!(g_HDC = GetDC(g_hwnd))) { // reset the display KillWindow(); MessageBox(NULL,"Unable to create device context", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } // set the pixel format we want (p55) PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of structure 1, // default version PFD_DRAW_TO_WINDOW | // window drawing support PFD_SUPPORT_OPENGL | // OpenGL support PFD_DOUBLEBUFFER, // double buffering support PFD_TYPE_RGBA, // RGBA color mode bits, // 32 bit color mode 0, 0, 0, 0, 0, 0, // ignore color bits, non-palettized mode 0, // no alpha buffer 0, // ignore shift bit 0, // no accumulation buffer 0, 0, 0, 0, // ignore accumulation bits 16, // 16 bit z-buffer size 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main drawing plane 0, // reserved 0, 0, 0 }; // layer masks ignored GLuint pixelFormat; // choose best matching pixel format if (!(pixelFormat = ChoosePixelFormat(g_HDC, &pfd))) { // reset the display KillWindow(); MessageBox(NULL, "Can't find an appropriate pixel format", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } // set pixel format to device context if(!SetPixelFormat(g_HDC, pixelFormat,&pfd)) { // reset the display KillWindow(); MessageBox(NULL, "Unable to set pixel format", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } // create the OpenGL rendering context if (!(g_HRC = wglCreateContext(g_HDC))) { // reset the display KillWindow(); MessageBox(NULL, "Unable to create OpenGL rendering context", "Error",MB_OK | MB_ICONEXCLAMATION); return FALSE; } // now make the rendering context the active one if(!wglMakeCurrent(g_HDC, g_HRC)) { // reset the display KillWindow(); MessageBox(NULL,"Unable to activate OpenGL rendering context", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; } // show the window in the forground, and set the keyboard focus to it ShowWindow(g_hwnd, SW_SHOW); SetForegroundWindow(g_hwnd); SetFocus(g_hwnd); // set up the perspective for the current screen size ResizeScene(width, height); // do one-time initialization if (!InitializeScene()) { // reset the display KillWindow(); MessageBox(NULL, "Initialization failed", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } return TRUE; } // end SetupWindow()
// // Creates a matching cen64_gl_config from a cen64_gl_hints struct. // // On error, CEN64_GL_CONFIG_BAD is returned. // cen64_gl_config *cen64_gl_config_create(cen64_gl_display display, cen64_gl_screen screen, const cen64_gl_hints *hints, int *matching) { struct cen64_gl_config *config; PIXELFORMATDESCRIPTOR pfd; // Do *NOT* use this hDC HANDLE outside this function. // It is the desktop window's hDC, and we shouldn't mess // with it. The only thing it's used for is to match a // PIXELFORMATDESCRIPTOR and expose success/failure. HDC screen_hdc; if ((config = malloc(sizeof(*config))) == NULL) return CEN64_GL_CONFIG_BAD; if ((screen_hdc = GetDC(screen)) == NULL) { free(config); return CEN64_GL_CONFIG_BAD; } memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); // As of 04/25/15, the MSDN documention (still) just says // to set this field to 1. So, uh, let's go with that. pfd.nVersion = 1; // Pack the structure using the provided hints-> pfd.dwFlags = PFD_SUPPORT_OPENGL; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType |= (enum cen64_gl_context_type) hints->context_type; pfd.dwFlags |= (enum cen64_gl_drawable_type) hints->drawable_type; if (hints->double_buffered != -1) pfd.dwFlags |= PFD_DOUBLEBUFFER; if (hints->stereoscopic != -1) pfd.dwFlags |= PFD_STEREO; if (hints->rgb_color_depth != -1) pfd.cColorBits = hints->rgb_color_depth; if (hints->alpha_color_depth != -1) pfd.cAlphaBits = hints->alpha_color_depth; if (hints->depth_buffer_size != -1) pfd.cDepthBits = hints->depth_buffer_size; if (hints->num_aux_buffers != -1) pfd.cAuxBuffers = hints->num_aux_buffers; if (hints->stencil_buffer_size != -1) pfd.cStencilBits = hints->stencil_buffer_size; if (hints->accum_buffer_red_bits != -1) pfd.cAccumRedBits = hints->accum_buffer_red_bits; if (hints->accum_buffer_green_bits != -1) pfd.cAccumGreenBits = hints->accum_buffer_green_bits; if (hints->accum_buffer_blue_bits != -1) pfd.cAccumBlueBits = hints->accum_buffer_blue_bits; if (hints->accum_buffer_alpha_bits != -1) pfd.cAccumAlphaBits = hints->accum_buffer_alpha_bits; config->pixel_format = ChoosePixelFormat(screen_hdc, &pfd); DescribePixelFormat(screen_hdc, config->pixel_format, sizeof(config->pfd), &config->pfd); ReleaseDC(screen, screen_hdc); *matching = 1; return config; }