void EnableDrawing (HGLRC *hRC) { /** * Edited by Cool Breeze on 16th October 2013 * + Updated the Pixel Format to support 24-bitdepth buffers * + Correctly create a GL 3.x compliant context */ HGLRC LegacyRC; PIXELFORMATDESCRIPTOR pfd; int iFormat; enigma::window_hDC = GetDC (hWnd); 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.iLayerType = PFD_MAIN_PLANE; iFormat = ChoosePixelFormat (enigma::window_hDC, &pfd); if (iFormat==0) { show_error("Failed to set the format of the OpenGL graphics device.",1); } SetPixelFormat ( enigma::window_hDC, iFormat, &pfd ); LegacyRC = wglCreateContext( enigma::window_hDC ); wglMakeCurrent( enigma::window_hDC, LegacyRC ); // -- Initialise GLEW GLenum err = glewInit(); if (GLEW_OK != err) { return; } // -- Define an array of Context Attributes int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; if ( wglewIsSupported("WGL_ARB_create_context") ) { *hRC = wglCreateContextAttribsARB( enigma::window_hDC,0, attribs ); wglMakeCurrent( NULL,NULL ); wglDeleteContext( LegacyRC ); wglMakeCurrent(enigma::window_hDC, *hRC ); } else // Unable to get a 3.0 Core Context, use the Legacy 1.x context { *hRC = LegacyRC; } //TODO: This never reports higher than 8, but display_aa should be 14 if 2,4,and 8 are supported and 8 only when only 8 is supported glGetIntegerv(GL_MAX_SAMPLES_EXT, &enigma_user::display_aa); }
bool cOpenGl::CreateGLContext(CDC* pDC) { PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(pDC->m_hDC, &pfd); if (nPixelFormat == 0) return false; BOOL bResult = SetPixelFormat (pDC->m_hDC, nPixelFormat, &pfd); if (!bResult) return false; HGLRC tempContext = wglCreateContext(pDC->m_hDC); wglMakeCurrent(pDC->m_hDC, tempContext); GLenum err = glewInit(); if (GLEW_OK != err) { AfxMessageBox(_T("GLEW is not initialized!")); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; if(wglewIsSupported("WGL_ARB_create_context") == 1) { m_hrc = wglCreateContextAttribsARB(pDC->m_hDC,0, attribs); wglMakeCurrent(NULL,NULL); wglDeleteContext(tempContext); wglMakeCurrent(pDC->m_hDC, m_hrc); } else { //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) m_hrc = tempContext; } //Checking GL version const GLubyte *GLVersionString = glGetString(GL_VERSION); //Or better yet, use the GL3 way to get the version number int OpenGLVersion[2]; glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); if (!m_hrc) return false; return true; }
void initializeGL() { HGLRC tempContext = wglCreateContext(ghDC); wglMakeCurrent(ghDC, tempContext); GLenum err = glewInit(); if (err != GLEW_OK) { // failed to initialize GLEW! } // My card currently only supports OpenGL 4.1 -- jbl int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { ghRC = wglCreateContextAttribsARB(ghDC, 0, attribs); wglMakeCurrent(NULL, NULL); wglDeleteContext(tempContext); wglMakeCurrent(ghDC, ghRC); } else { // It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) ghRC = tempContext; } int OpenGLVersion[2]; glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); }
// Initialize GL //***************************************************************************** void InitGL(int* argc, char **argv) { // initialize GLUT glutInit(argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowPosition (glutGet(GLUT_SCREEN_WIDTH)/2 - iGraphicsWinWidth/2, glutGet(GLUT_SCREEN_HEIGHT)/2 - iGraphicsWinHeight/2); glutInitWindowSize(iGraphicsWinWidth, iGraphicsWinHeight); iGLUTWindowHandle = glutCreateWindow("OpenCL for GPU RGB Sobel Filter Demo"); #if !(defined (__APPLE__) || defined(MACOSX)) glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif // register glut callbacks glutKeyboardFunc(KeyboardGL); glutDisplayFunc(DisplayGL); glutReshapeFunc(Reshape); glutIdleFunc(Idle); glutTimerFunc(REFRESH_DELAY, timerEvent,0); // create GLUT menu iGLUTMenuHandle = glutCreateMenu(MenuGL); glutAddMenuEntry("Toggle Filter On/Off <spacebar>", ' '); glutAddMenuEntry("Toggle Processing between GPU and CPU [p]", 'p'); glutAddMenuEntry("Toggle between Full Screen and Windowed [f]", 'f'); glutAddMenuEntry("Increase Threshold [+]", '+'); glutAddMenuEntry("Decrease Threshold [-]", '-'); glutAddMenuEntry("Quit <esc>", '\033'); glutAttachMenu(GLUT_RIGHT_BUTTON); // Set clear color glClearColor(0.f, 0.f, 0.f, 0.f); // Zoom with fixed aspect ratio float fAspects[2] = {(float)glutGet(GLUT_WINDOW_WIDTH)/(float)uiImageWidth , (float)glutGet(GLUT_WINDOW_HEIGHT)/(float)uiImageHeight}; fZoom = fAspects[0] > fAspects[1] ? fAspects[1] : fAspects[0]; glPixelZoom(fZoom, fZoom); glewInit(); // Disable vertical sync, if supported #ifdef _WIN32 if (wglewIsSupported("WGL_EXT_swap_control")) { iVsyncState = wglGetSwapIntervalEXT(); wglSwapIntervalEXT(0); } #else #if defined (__APPLE__) || defined(MACOSX) GLint VBL = 0; CGLGetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &iVsyncState); CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); #else if(glxewIsSupported("GLX_SGI_swap_control")) { glXSwapIntervalSGI(0); } #endif #endif }
// initialize OpenGL void initGL(int *argc, char **argv) { glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(width, height); glutCreateWindow("CUDA Particles"); glewInit(); if (!glewIsSupported("GL_VERSION_2_0 GL_VERSION_1_5 GL_ARB_multitexture GL_ARB_vertex_buffer_object")) { fprintf(stderr, "Required OpenGL extensions missing."); exit(EXIT_FAILURE); } #if defined (_WIN32) if (wglewIsSupported("WGL_EXT_swap_control")) { // disable vertical sync wglSwapIntervalEXT(0); } #endif glEnable(GL_DEPTH_TEST); glClearColor(0.25, 0.25, 0.25, 1.0); glutReportErrors(); }
ofxWMFVideoPlayer::ofxWMFVideoPlayer() : _player(NULL) { if (_instanceCount == 0) { if (!ofIsGLProgrammableRenderer()) { if (wglewIsSupported("WGL_NV_DX_interop")) { ofLogVerbose("ofxWMFVideoPlayer") << "WGL_NV_DX_interop supported"; } else { ofLogError("ofxWMFVideoPlayer") << "WGL_NV_DX_interop not supported. Upgrade your graphc drivers and try again."; return; } } HRESULT hr = MFStartup(MF_VERSION); if (!SUCCEEDED(hr)) { ofLog(OF_LOG_ERROR, "ofxWMFVideoPlayer: Error while loading MF"); } } _id = _instanceCount; _instanceCount++; this->InitInstance(); _waitingForLoad = false; _waitForLoadedToPlay = false; _sharedTextureCreated = false; _wantToSetVolume = false; _currentVolume = 1.0; _frameRate = 0.0f; }
/* create30Context creates an OpenGL context and attaches it to the window provided by the HWND. This method currently creates and OpenGL 3.2 context by default, but will default to an OpenGL 2.1 capable context if the OpenGL 3.2 context cannot be created. */ bool OpenGLContext::create30Context(HWND hwnd) { this->hwnd = hwnd; // Set the hwnd for our window hdc = GetDC(hwnd); // Get the device context for our window PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; //Enable double buffering, opengl support, and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(hdc, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return false; bool bResult = SetPixelFormat(hdc, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (!bResult) // If it fails return false; HGLRC tempOpenGLContext = wglCreateContext(hdc); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(hdc, tempOpenGLContext); // Make the OpenGL 2.1 context current and active GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails return false; int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // Set the MAJOR version of OpenGL to 3 WGL_CONTEXT_MINOR_VERSION_ARB, 2, // Set the MINOR version of OpenGL to 2 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 3.x context creation extension is available hrc = wglCreateContextAttribsARB(hdc, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context wglMakeCurrent(hdc, hrc); // Make our OpenGL 3.0 context current } else { hrc = tempOpenGLContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context } int glVersion[2] = { -1, -1 }; // Set some default values for the version glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using //std::cout << "Using OpenGL: " << glVersion[0] << "." << glVersion[1] << std::endl; // Output which version of OpenGL we are using On Windows, you won’t get a console for a Win32 Application, but a nifty trick to get console output, is to open up Command Prompt, navigate to your directory with your executable file, and use something like: “program.exe > temp.txt” return true; // We have successfully created a context, return true }
const bool GPUQuery::extensionSupported(const char * extension) { bool supported = glewIsSupported(extension) ? true : false; if(!supported) #ifdef WIN32 return wglewIsSupported(extension) ? true : false; #else return glxewIsSupported(extension) ? true : false; #endif return supported; }
// De-initialize GL //***************************************************************************** void DeInitGL() { // Restore startup Vsync state, if supported #ifdef _WIN32 if (wglewIsSupported("WGL_EXT_swap_control")) { wglSwapIntervalEXT(iVsyncState); } #else #if defined (__APPLE__) || defined(MACOSX) CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &iVsyncState); #endif #endif }
// initialize OpenGL void initGL(int *argc, char **argv) { glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(winWidth, winHeight); glutCreateWindow("CUDA Smoke Particles"); glewInit(); if (!glewIsSupported("GL_VERSION_2_0 GL_VERSION_1_5")) { fprintf(stderr, "The following required OpenGL extensions missing:\n\tGL_VERSION_2_0\n\tGL_VERSION_1_5\n"); fprintf(stderr, " PASSED\n"); cutilExit(*argc, argv); exit(-1); } if (!glewIsSupported("GL_ARB_multitexture GL_ARB_vertex_buffer_object GL_EXT_geometry_shader4")) { fprintf(stderr, "The following required OpenGL extensions missing:\n\tGL_ARB_multitexture\n\tGL_ARB_vertex_buffer_object\n\tGL_EXT_geometry_shader4.\n"); fprintf(stderr, " PASSED\n"); cutilExit(*argc, argv); exit(-1); } #if defined (_WIN32) if (wglewIsSupported("WGL_EXT_swap_control")) { // disable vertical sync wglSwapIntervalEXT(0); } #endif glEnable(GL_DEPTH_TEST); // load floor texture char* imagePath = cutFindFilePath("floortile.ppm", argv[0]); if (imagePath == 0) { fprintf(stderr, "Error finding floor image file\n"); fprintf(stderr, " FAILED\n"); exit(EXIT_FAILURE); } floorTex = loadTexture(imagePath); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0f); floorProg = new GLSLProgram(floorVS, floorPS); glutReportErrors(); }
const bool GPUQuery::extensionSupported(const char * extension) { if(isCoreProfile()) return false; bool supported = glewIsSupported(extension) ? true : false; if(!supported) #ifdef WIN32 return wglewIsSupported(extension) ? true : false; #elif defined(LINUX) return glxewIsSupported(extension) ? true : false; #else return supported; #endif return supported; }
// Setup function for GLUT parameters and loop //***************************************************************************** void InitGL(int* argc, char **argv) { // init GLUT glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowPosition (glutGet(GLUT_SCREEN_WIDTH)/2 - iGraphicsWinWidth/2, glutGet(GLUT_SCREEN_HEIGHT)/2 - iGraphicsWinHeight/2); glutInitWindowSize(iGraphicsWinWidth, iGraphicsWinHeight); iGLUTWindowHandle = glutCreateWindow("OpenCL for GPU Nbody Demo"); #if !(defined (__APPLE__) || defined(MACOSX) || defined(__EMSCRIPTEN__)) glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif // init GLEW #ifndef __EMSCRIPTEN__ glewInit(); GLboolean bGlew = glewIsSupported("GL_VERSION_2_0 " "GL_VERSION_1_5 " "GL_ARB_multitexture " "GL_ARB_vertex_buffer_object"); oclCheckErrorEX(bGlew, shrTRUE, pCleanup); #endif glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); renderer = new ParticleRenderer(); // check GL errors GLenum error; while ((error = glGetError()) != GL_NO_ERROR) { #ifdef __EMSCRIPTEN__ shrLog("InitGL: error - %d\n", error); #else shrLog("InitGL: error - %s\n", (char *)gluErrorString(error)); #endif } // Disable vertical sync, if supported #ifdef _WIN32 if (wglewIsSupported("WGL_EXT_swap_control")) { iVsyncState = wglGetSwapIntervalEXT(); wglSwapIntervalEXT(0); } #else #if defined (__APPLE__) || defined(MACOSX) GLint VBL = 0; CGLGetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &iVsyncState); CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &VBL); #elif __EMSCRIPTEN__ #else if(glxewIsSupported("GLX_SGI_swap_control")) { glXSwapIntervalSGI(0); } #endif #endif // create a new parameter list paramlist = new ParamListGL("sliders"); paramlist->bar_col_outer[0] = 0.8f; paramlist->bar_col_outer[1] = 0.8f; paramlist->bar_col_outer[2] = 0.0f; paramlist->bar_col_inner[0] = 0.8f; paramlist->bar_col_inner[1] = 0.8f; paramlist->bar_col_inner[2] = 0.0f; // add parameters to the list // Point Size paramlist->AddParam(new Param<float>("Point Size", activeParams.m_pointSize, 0.0f, 10.0f, 0.01f, &activeParams.m_pointSize)); // Velocity Damping paramlist->AddParam(new Param<float>("Velocity Damping", activeParams.m_damping, 0.5f, 1.0f, .0001f, &(activeParams.m_damping))); // Softening Factor paramlist->AddParam(new Param<float>("Softening Factor", activeParams.m_softening, 0.001f, 1.0f, .0001f, &(activeParams.m_softening))); // Time step size paramlist->AddParam(new Param<float>("Time Step", activeParams.m_timestep, 0.0f, 1.0f, .0001f, &(activeParams.m_timestep))); // Cluster scale (only affects starting configuration paramlist->AddParam(new Param<float>("Cluster Scale", activeParams.m_clusterScale, 0.0f, 10.0f, 0.01f, &(activeParams.m_clusterScale))); // Velocity scale (only affects starting configuration) paramlist->AddParam(new Param<float>("Velocity Scale", activeParams.m_velocityScale, 0.0f, 1000.0f, 0.1f, &activeParams.m_velocityScale)); }
Api::Api(Files::Api * files, HWND handle) : deviceContext(0), glContext(0), files(files), baseShader(0), texCopyShader(0), texShaderQuad(0), backbufferWidth(0), backbufferHeight(0), texVertexShader(0), texVertexShaderRequested(false) { deviceContext = GetDC(handle); PIXELFORMATDESCRIPTOR pfd = { 0 }; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information pfd.cDepthBits = 32; // Give us 32 bits of depth information pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int pixelFormat = ChoosePixelFormat(deviceContext, &pfd); SetPixelFormat(deviceContext, pixelFormat, &pfd); HGLRC tempContext = wglCreateContext(deviceContext); wglMakeCurrent(deviceContext, tempContext); GLenum error = glewInit(); int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // Set the MAJOR version of OpenGL to 3 WGL_CONTEXT_MINOR_VERSION_ARB, 2, // Set the MINOR version of OpenGL to 2 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible 0 }; if(wglewIsSupported("WGL_ARB_create_context") == 1) { glContext = wglCreateContextAttribsARB(deviceContext, 0, attributes); wglMakeCurrent(0, 0); wglDeleteContext(tempContext); wglMakeCurrent(deviceContext, glContext); const char * currentVersion = (const char*) glGetString(GL_VERSION); const char * currentExtensions = (const char*) glGetString(GL_EXTENSIONS); OutputDebugStringA(currentVersion); OutputDebugStringA("\n"); OutputDebugStringA(currentExtensions); OutputDebugStringA("\n"); } else { glContext = tempContext; } SetClearColor(0.0f, 0.0f, 0.0f, 1.0f); glEnable(GL_DEPTH_TEST); glFrontFace(GL_CW); glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(Api::DebugMessageCallback, 0); RECT windowRect; GetClientRect(handle, &windowRect); OnScreenResize(windowRect.right, windowRect.bottom); }
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static HWND shwnd; static HDC hdc; static HGLRC hglrc, hglrc_legacy; static Engine altEngine; static POINT center; static WSADATA wsadata; switch (message) { case WM_CREATE: WSAStartup(MAKEWORD(2, 2), &wsadata); AllocConsole(); RedirectIOToConsole(); SetTimer ( hwnd, TICK_TIMER, 16, NULL ); hdc = GetDC(hwnd); setupPixelFormat(hdc); #ifndef DIRECTX hglrc_legacy = wglCreateContext(hdc); wglMakeCurrent(hdc, hglrc_legacy); glewInit(); if(wglewIsSupported("WGL_ARB_create_context") == TRUE) { const int context[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, // WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; const int pixelformat[] = { 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, }; int format; unsigned int num_formats; wglChoosePixelFormatARB(hdc, (int *)pixelformat, NULL, 1, &format, &num_formats); hglrc = wglCreateContextAttribsARB(hdc, 0, context); wglMakeCurrent(NULL,NULL); wglDeleteContext(hglrc_legacy); wglMakeCurrent(hdc, hglrc); } else { //opengl 2.0 hglrc = hglrc_legacy; } #endif shwnd = hwnd; altEngine.init(&shwnd, &hdc); return 0; case WMU_RENDER: altEngine.render(); return 0; case WM_TIMER: if (glGetError() != GL_NO_ERROR) { printf("GL_ERROR\n"); } switch(wParam) { case TICK_TIMER: altEngine.step(); break; } return 0; case WM_MOUSEMOVE: { int x, y; x = LOWORD(lParam); y = HIWORD(lParam); if ((x == center.x) && (y == center.y)) return 0; if ( altEngine.mousepos(x, y, x - center.x, y - center.y) ) { POINT screen = center; ClientToScreen(hwnd, &screen); SetCursorPos(screen.x, screen.y); } } return 0; case WM_LBUTTONDOWN: case WM_LBUTTONUP: { bool pressed = (message == WM_LBUTTONDOWN) ? true : false; altEngine.keypress("leftbutton", pressed); return 0; } case WM_MBUTTONDOWN: case WM_MBUTTONUP: { bool pressed = (message == WM_MBUTTONDOWN) ? true : false; altEngine.keypress("middlebutton", pressed); return 0; } case WM_RBUTTONDOWN: case WM_RBUTTONUP: { bool pressed = (message == WM_RBUTTONDOWN) ? true : false; altEngine.keypress("rightbutton", pressed); return 0; } case WM_KEYDOWN: case WM_KEYUP: { bool pressed = (message == WM_KEYDOWN) ? true : false; switch (wParam) { case VK_PAUSE: break; case VK_TAB: break; case VK_RETURN: altEngine.keypress("enter", pressed); break; case VK_SHIFT: altEngine.keypress("shift", pressed); break; case VK_CONTROL: altEngine.keypress("control", pressed); break; case VK_ESCAPE: altEngine.keypress("escape", pressed); break; case VK_UP: altEngine.keypress("up", pressed); break; case VK_LEFT: altEngine.keypress("left", pressed); break; case VK_DOWN: altEngine.keypress("down", pressed); break; case VK_RIGHT: altEngine.keypress("right", pressed); break; } return 0; } case WM_CHAR: altEngine.keystroke((char)wParam); return 0; case WM_SIZE: { int width, height; width = LOWORD(lParam); height = HIWORD(lParam); center.x = width / 2; center.y = height / 2; altEngine.resize(width, height); } return 0; case WM_SYSCOMMAND: switch(wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; case WM_DESTROY: #ifndef DIRECTX if (hglrc) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hglrc); ReleaseDC(hwnd, hdc); } #endif altEngine.destroy(); WSACleanup(); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }
GLRenderWindow::GLRenderWindow() :GLFrameBuffer(false) { WindowPtr win = Engine::Instance().AppInstance().MainWnd(); //callback win->PaintEvent.connect(std::bind(&GLRenderWindow::OnPaint, this)); win->CloseEvent.connect(std::bind(&GLRenderWindow::OnClose, this)); win->ExitSizeMoveEvent.connect(std::bind(&GLRenderWindow::OnExitSizeMove, this)); win->EnterSizeMoveEvent.connect(std::bind(&GLRenderWindow::OnEnterSizeMove, this)); win->SizeEvent.connect(std::bind(&GLRenderWindow::OnSize, this, std::placeholders::_1)); win->ActiveEvent.connect(std::bind(&GLRenderWindow::OnActive, this, std::placeholders::_1)); hWnd_ = win->HWnd(); hDC_ = ::GetDC(hWnd_); left_ = 0; top_ = 0; width_ = win->Width(); height_ = win->Height(); int style = WS_OVERLAPPEDWINDOW; RECT rc = { 0, 0, static_cast<LONG>(width_), static_cast<LONG>(height_) }; ::AdjustWindowRect(&rc, style, false); ::SetWindowLongPtrW(hWnd_, GWL_STYLE, style); ::SetWindowPos(hWnd_, nullptr, left_, top_, width_, height_, SWP_SHOWWINDOW | SWP_NOZORDER); // there is no guarantee that the contents of the stack that become // the pfd are zeroed, therefore _make sure_ to clear these bits. PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, 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 = static_cast<BYTE>(32); pfd.cDepthBits = static_cast<BYTE>(24); pfd.cStencilBits = static_cast<BYTE>(8); pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormat = ::ChoosePixelFormat(hDC_, &pfd); //static_assert(, L"sd"); ::SetPixelFormat(hDC_, pixelFormat, &pfd); HGLRC tempContext = ::wglCreateContext(hDC_); ::wglMakeCurrent(hDC_, tempContext); GLenum err = glewInit(); if (GLEW_OK != err) { printf("GLEW is not initialized!"); } int OpenGLVersion[2]; glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, OpenGLVersion[0], WGL_CONTEXT_MINOR_VERSION_ARB, OpenGLVersion[1], WGL_CONTEXT_FLAGS_ARB, 0, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { hRC_ = wglCreateContextAttribsARB(hDC_, 0, attribs); wglMakeCurrent(NULL, NULL); wglDeleteContext(tempContext); wglMakeCurrent(hDC_, hRC_); } else { hRC_ = tempContext; } glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); //::ShowWindow(hWnd_, SW_SHOWNORMAL); ::UpdateWindow(hWnd_); }
bool CWinAPIOpenGLWindow::Create(char* title, int width, int height, int bits, bool fullscreenflag, WNDPROC WndProc) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height m_Fullscreen = fullscreenflag; // Set The Global Fullscreen Flag m_hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = m_hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = "OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (m_Fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { m_Fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (m_Fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(m_hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu m_hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { Kill(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 8, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(m_hDC=GetDC(m_hWnd))) // Did We Get A Device Context? { Kill(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(m_hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { Kill(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(m_hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { Kill(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } HGLRC TempContext; if (!(TempContext = wglCreateContext(m_hDC))) // Are We Able To Get A Rendering Context? { Kill(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(m_hDC,TempContext)) // Try To Activate The Rendering Context { Kill(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } GLenum err = glewInit(); if (GLEW_OK != err) { MessageBox(NULL, "GLEW is not initialized!", "ERROR", MB_OK|MB_ICONEXCLAMATION); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; if(wglewIsSupported("WGL_ARB_create_context") == 1) { m_hRC = wglCreateContextAttribsARB(m_hDC,0, attribs); wglMakeCurrent(NULL,NULL); wglDeleteContext(TempContext); wglMakeCurrent(m_hDC, m_hRC); } else { //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) m_hRC = TempContext; } ShowWindow(m_hWnd,SW_SHOW); // Show The Window SetForegroundWindow(m_hWnd); // Slightly Higher Priority SetFocus(m_hWnd); // Sets Keyboard Focus To The Window //ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen /*if (!InitGL()) // Initialize Our Newly Created GL Window { Kill(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE }*/ return true; // Success }
static void GLimp_InitOpenGL3xContext() { int retVal; const char *success[] = { "failed", "success" }; if(!r_glCoreProfile->integer) return; GLimp_GetCurrentContext(); // try to initialize an OpenGL 3.0 context #if defined(WIN32) if(WGLEW_ARB_create_context || wglewIsSupported("WGL_ARB_create_context")) { int attribs[256]; // should be really enough int numAttribs; /* int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, r_glMinMajorVersion->integer, WGL_CONTEXT_MINOR_VERSION_ARB, r_glMinMinorVersion->integer, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,// | WGL_CONTEXT_DEBUG_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; */ memset(attribs, 0, sizeof(attribs)); numAttribs = 0; attribs[numAttribs++] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[numAttribs++] = r_glMinMajorVersion->integer; attribs[numAttribs++] = WGL_CONTEXT_MINOR_VERSION_ARB; attribs[numAttribs++] = r_glMinMinorVersion->integer; if(WGLEW_ARB_create_context_profile) { attribs[numAttribs++] = WGL_CONTEXT_FLAGS_ARB; #if 0 if(GLXEW_ARB_debug_output) { attribs[numAttribs++] = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB; } else #endif { attribs[numAttribs++] = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } attribs[numAttribs++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[numAttribs++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; } // set current context to NULL retVal = wglMakeCurrent(opengl_context.hDC, NULL) != 0; ri.Printf(PRINT_ALL, "...wglMakeCurrent( %p, %p ): %s\n", opengl_context.hDC, NULL, success[retVal]); // delete HGLRC if(opengl_context.hGLRC) { retVal = wglDeleteContext(opengl_context.hGLRC) != 0; ri.Printf(PRINT_ALL, "...deleting standard GL context: %s\n", success[retVal]); opengl_context.hGLRC = NULL; } ri.Printf(PRINT_ALL, "...initializing OpenGL %i.%i context ", r_glMinMajorVersion->integer, r_glMinMinorVersion->integer); opengl_context.hGLRC = wglCreateContextAttribsARB(opengl_context.hDC, 0, attribs); if(wglMakeCurrent(opengl_context.hDC, opengl_context.hGLRC)) { ri.Printf(PRINT_ALL, " done\n"); glConfig.driverType = GLDRV_OPENGL3; } else { ri.Error(ERR_FATAL, "Could not initialize OpenGL %i.%i context\n" "Make sure your graphics card supports OpenGL %i.%i or newer", r_glMinMajorVersion->integer, r_glMinMinorVersion->integer, r_glMinMajorVersion->integer, r_glMinMinorVersion->integer); } } #elif 0 //defined(__linux__) // TODO /* // GLX_ARB_create_context #ifndef GLX_ARB_create_context #define GLX_CONTEXT_DEBUG_BIT_ARB 0x00000001 #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 #define GLX_CONTEXT_FLAGS_ARB 0x2094 extern GLXContext (APIENTRY * glXCreateContextAttribsARB) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list); */ glXCreateContextAttribsARB = SDL_GL_GetProcAddress("glXCreateContextAttribsARB"); if(glXCreateContextAttribsARB) { int attribs[3]; ri.Printf(PRINT_ALL, "Initializing OpenGL 3.0 context..."); attribs[0] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[1] = 3; attribs[2] = 0; //terminate first pair opengl_context->hGLRC = glXCreateContextAttribsARB(opengl_context->, attribs); if(wglMakeCurrent(opengl_context->hDC, opengl_context->hGLRC)) { ri.Printf(PRINT_ALL, " done\n"); glConfig.driverType = GLDRV_OPENGL3; } else { ri.Printf(PRINT_ALL, " failed\n"); } } #endif }
int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode) { // Tick frequency { int64 TicksPerSecond; QueryPerformanceFrequency((LARGE_INTEGER *)&TicksPerSecond); Timer::Init(1000.0 / TicksPerSecond); } QueryPerformanceCounter((LARGE_INTEGER *)&Mem.Debug.Time); Timer::StartTime(&Mem.Debug.Timers[Timer_Startup]); Mem.IsRunning = true; // Set current path to this executable's path { HMODULE Module = GetModuleHandleA(NULL); char PathString[MAX_PATH]; uint32 PathLength = GetModuleFileNameA(Module, PathString, MAX_PATH); if (PathLength != -1) { char *LastSlash = strrchr(PathString, '\\'); if (LastSlash) { *LastSlash = '\0'; } SetCurrentDirectoryA(PathString); } } HWND Window; // Create Window { WNDCLASSA WindowClass = {}; WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; WindowClass.lpfnWndProc = Win32MainWindowCallback; WindowClass.hInstance = Instance; const char* IcoPath = "papaya.ico"; WindowClass.hIcon = (HICON)LoadImage(0, IcoPath, IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE | LR_SHARED); WindowClass.lpszClassName = "PapayaWindowClass"; if (!RegisterClassA(&WindowClass)) { // TODO: Log: Register window class failed return 0; } Window = CreateWindowExA( 0, // Extended window style WindowClass.lpszClassName, // Class name, "Papaya", // Name, WS_POPUP | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE, // Window style CW_USEDEFAULT, // X, CW_USEDEFAULT, // Y, CW_USEDEFAULT, // Width, CW_USEDEFAULT, // Height, 0, // Window Parent, 0, // Menu, Instance, // Handle to the instance, 0); // lpParam if (!Window) { // TODO: Log: Create window failed return 0; } SystemParametersInfo(SPI_GETWORKAREA, 0, &WindowsWorkArea, 0); #ifdef PAPAYARELEASE SetWindowPos(Window, HWND_TOP, 0, 0, 600, 600, NULL); ShowWindow(Window, SW_MAXIMIZE); #else uint32 ScreenWidth = GetSystemMetrics(SM_CXSCREEN); uint32 ScreenHeight = GetSystemMetrics(SM_CYSCREEN); Mem.Window.Width = (uint32)((float)ScreenWidth * 0.5); Mem.Window.Height = (uint32)((float)ScreenHeight * 0.8); uint32 WindowX = (ScreenWidth - Mem.Window.Width) / 2; uint32 WindowY = (ScreenHeight - Mem.Window.Height) / 2; SetWindowPos(Window, HWND_TOP, WindowX, WindowY, Mem.Window.Width, Mem.Window.Height, NULL); #endif // PAPAYARELEASE // Get window size { RECT WindowRect = { 0 }; BOOL foo = GetClientRect(Window, &WindowRect); Mem.Window.Width = WindowRect.right - WindowRect.left; Mem.Window.Height = WindowRect.bottom - WindowRect.top; } } // Initialize OpenGL { DeviceContext = GetDC(Window); // Setup pixel format { PIXELFORMATDESCRIPTOR PixelFormatDesc = { 0 }; // TODO: Program seems to work perfectly fine without all other params except dwFlags. // Can we skip other params for the sake of brevity? PixelFormatDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR); PixelFormatDesc.nVersion = 1; PixelFormatDesc.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; PixelFormatDesc.iPixelType = PFD_TYPE_RGBA; PixelFormatDesc.cColorBits = 32; PixelFormatDesc.cDepthBits = 32; PixelFormatDesc.dwLayerMask = PFD_MAIN_PLANE; // int32 PixelFormat = ChoosePixelFormat(DeviceContext, &PixelFormatDesc); if (!PixelFormat) { exit(1); } // TODO: Log: Choose pixel format failed if (!SetPixelFormat(DeviceContext, PixelFormat, &PixelFormatDesc)) { exit(1); } // TODO: Log: Set pixel format failed } // Create rendering context { // TODO: Create "proper" context? // https://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)#Proper_Context_Creation HGLRC RenderingContext = wglCreateContext(DeviceContext); wglMakeCurrent(DeviceContext, RenderingContext); if (!GL::InitAndValidate()) { exit(1); } glGetIntegerv(GL_MAJOR_VERSION, &Mem.System.OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &Mem.System.OpenGLVersion[1]); } // Disable vsync if (wglewIsSupported("WGL_EXT_swap_control")) { wglSwapIntervalEXT(0); } } // Initialize tablet EasyTab_Load(Window); Core::Initialize(&Mem); // Initialize ImGui { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; io.KeyMap[ImGuiKey_Home] = VK_HOME; io.KeyMap[ImGuiKey_End] = VK_END; io.KeyMap[ImGuiKey_Delete] = VK_DELETE; io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; io.RenderDrawListsFn = Core::RenderImGui; io.ImeWindowHandle = Window; } Mem.Window.MenuHorizontalOffset = 32; Mem.Window.TitleBarButtonsWidth = 109; Mem.Window.TitleBarHeight = 30; Timer::StopTime(&Mem.Debug.Timers[Timer_Startup]); // Handle command line arguments (if present) if (strlen(CommandLine)) { // Remove double quotes from string if present { char* PtrRead = CommandLine; char* PtrWrite = CommandLine; while (*PtrRead) { *PtrWrite = *PtrRead++; if (*PtrWrite != '\"') { PtrWrite++; } } *PtrWrite = '\0'; } Core::OpenDocument(CommandLine, &Mem); } #ifdef PAPAYA_DEFAULT_IMAGE Core::OpenDocument(PAPAYA_DEFAULT_IMAGE, &Mem); #endif // PAPAYA_DEFAULT_IMAGE while (Mem.IsRunning) { Timer::StartTime(&Mem.Debug.Timers[Timer_Frame]); // Windows message handling { MSG Message; while (PeekMessage(&Message, 0, 0, 0, PM_REMOVE)) { if (Message.message == WM_QUIT) { Mem.IsRunning = false; } TranslateMessage(&Message); DispatchMessageA(&Message); } } // Tablet input // TODO: Put this in papaya.cpp { Mem.Tablet.Pressure = EasyTab->Pressure; Mem.Tablet.PosX = EasyTab->PosX; Mem.Tablet.PosY = EasyTab->PosY; Mem.Tablet.Buttons = EasyTab->Buttons; } BOOL IsMaximized = IsMaximized(Window); if (IsIconic(Window)) { goto EndOfFrame; } // Start new ImGui frame { ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) RECT rect; GetClientRect(Window, &rect); io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Read keyboard modifiers inputs io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0; io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0; io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0; // Setup time step INT64 current_time; QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); io.DeltaTime = (float)(current_time - Mem.Debug.Time) * (float)Timer::GetFrequency() / 1000.0f; Mem.Debug.Time = current_time; // TODO: Move Imgui timers from Debug to their own struct // Hide OS mouse cursor if ImGui is drawing it //SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW)); // Start the frame ImGui::NewFrame(); } // Title Bar Icon { ImGui::SetNextWindowSize(ImVec2((float)Mem.Window.MenuHorizontalOffset,(float)Mem.Window.TitleBarHeight)); ImGui::SetNextWindowPos(ImVec2(1.0f, 1.0f)); ImGuiWindowFlags WindowFlags = 0; // TODO: Create a commonly-used set of Window flags, and use them across ImGui windows WindowFlags |= ImGuiWindowFlags_NoTitleBar; WindowFlags |= ImGuiWindowFlags_NoResize; WindowFlags |= ImGuiWindowFlags_NoMove; WindowFlags |= ImGuiWindowFlags_NoScrollbar; WindowFlags |= ImGuiWindowFlags_NoCollapse; WindowFlags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2,2)); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0,0)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); ImGui::PushStyleColor(ImGuiCol_WindowBg, Mem.Colors[PapayaCol_Transparent]); bool bTrue = true; ImGui::Begin("Title Bar Icon", &bTrue, WindowFlags); #define CALCUV(X, Y) ImVec2((float)X/256.0f, (float)Y/256.0f) ImGui::Image((void*)(intptr_t)Mem.Textures[PapayaTex_UI], ImVec2(28,28), CALCUV(0,200), CALCUV(28,228)); #undef CALCUV ImGui::End(); ImGui::PopStyleColor(1); ImGui::PopStyleVar(5); } // Title Bar Buttons { ImGui::SetNextWindowSize(ImVec2((float)Mem.Window.TitleBarButtonsWidth,24.0f)); ImGui::SetNextWindowPos(ImVec2((float)Mem.Window.Width - Mem.Window.TitleBarButtonsWidth, 0.0f)); ImGuiWindowFlags WindowFlags = 0; WindowFlags |= ImGuiWindowFlags_NoTitleBar; WindowFlags |= ImGuiWindowFlags_NoResize; WindowFlags |= ImGuiWindowFlags_NoMove; WindowFlags |= ImGuiWindowFlags_NoScrollbar; WindowFlags |= ImGuiWindowFlags_NoCollapse; WindowFlags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0,0)); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0,0)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); ImGui::PushStyleColor(ImGuiCol_Button, Mem.Colors[PapayaCol_Transparent]); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, Mem.Colors[PapayaCol_ButtonHover]); ImGui::PushStyleColor(ImGuiCol_ButtonActive, Mem.Colors[PapayaCol_ButtonActive]); ImGui::PushStyleColor(ImGuiCol_WindowBg, Mem.Colors[PapayaCol_Transparent]); bool bTrue = true; #define CALCUV(X, Y) ImVec2((float)X/256.0f, (float)Y/256.0f) ImGui::Begin("Title Bar Buttons", &bTrue, WindowFlags); ImGui::PushID(0); if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), CALCUV(62,200),CALCUV(96,226), 1, ImVec4(0,0,0,0))) { ShowWindow(Window, SW_MINIMIZE); } ImVec2 StartUV = IsMaximized ? CALCUV(28,226) : CALCUV(62,226); ImVec2 EndUV = IsMaximized ? CALCUV(62,252) : CALCUV(96,252); ImGui::PopID(); ImGui::SameLine(); ImGui::PushID(1); if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), StartUV, EndUV, 1, ImVec4(0,0,0,0))) { if (IsMaximized) { ShowWindow(Window, SW_RESTORE); } else { ShowWindow(Window, SW_MAXIMIZE); } } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID(2); if(ImGui::ImageButton((void*)(size_t)Mem.Textures[PapayaTex_UI], ImVec2(34,26), CALCUV(28,200),CALCUV(62,226), 1, ImVec4(0,0,0,0))) { SendMessage(Window, WM_CLOSE, 0, 0); } ImGui::PopID(); ImGui::End(); #undef CALCUV ImGui::PopStyleVar(5); ImGui::PopStyleColor(4); } // ImGui::ShowTestWindow(); Core::UpdateAndRender(&Mem); SwapBuffers(DeviceContext); EndOfFrame: Timer::StopTime(&Mem.Debug.Timers[Timer_Frame]); double FrameRate = (Mem.CurrentTool == PapayaTool_Brush && Mem.Mouse.IsDown[0]) ? 500.0 : 60.0; double FrameTime = 1000.0 / FrameRate; double SleepTime = FrameTime - Mem.Debug.Timers[Timer_Frame].ElapsedMs; Mem.Debug.Timers[Timer_Sleep].ElapsedMs = SleepTime; if (SleepTime > 0) { Sleep((int32)SleepTime); } } Core::Shutdown(&Mem); EasyTab_Unload(); return 0; }
bool PlatformInitOpenGLContext(int color_bits, int depth_bits, int stencil_bits) { sht::Application * app = sht::Application::GetInstance(); const int kContextMajorVersion = 3; const int kContextMinorVersion = 3; static int msaa_pixel_format = 0; g_window.dc = GetDC(g_window.hwnd); // Grab A Device Context For This Window if (g_window.dc == 0) { return false; } 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 (BYTE)color_bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored (BYTE)depth_bits, // Z-Buffer (Depth Buffer) (BYTE)stencil_bits, // Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; int pixel_format = ChoosePixelFormat(g_window.dc, &pfd); // Find A Compatible Pixel Format if (pixel_format == 0) { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Choose MSAA pixel format if needed if (msaa_pixel_format != 0) pixel_format = msaa_pixel_format; if (SetPixelFormat(g_window.dc, pixel_format, &pfd) == FALSE) // Try To Set The Pixel Format { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } HGLRC temp_rc = wglCreateContext(g_window.dc); // Try To Get A Rendering Context if (temp_rc == 0) { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent(g_window.dc, temp_rc) == FALSE) { // Failed wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "glewInit failed: %s\n", glewGetErrorString(err)); wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Try to create a MSAA pixel format if (app->IsMultisample() && msaa_pixel_format == 0) { if (GLEW_ARB_multisample && WGLEW_ARB_pixel_format) { int samples = 4; // = msaa_samples while (samples > 0) { UINT num_formats = 0; int attribs[] = { 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, color_bits, WGL_DEPTH_BITS_ARB, depth_bits, WGL_STENCIL_BITS_ARB, stencil_bits, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, samples, 0 }; if (wglChoosePixelFormatARB(g_window.dc, attribs, NULL, 1, &msaa_pixel_format, &num_formats) == TRUE && num_formats > 0) { // We cant's set pixel format twice, so we have to recreate a window *?* wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; PlatformWindowDestroy(); // Don't forget do dispatch any upcoming messages, such as WM_QUIT MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (PlatformWindowCreate()) { PlatformWindowCenter(); // Call this function again with msaa pixel format already known return PlatformInitOpenGLContext(color_bits, depth_bits, stencil_bits); } else return false; } else msaa_pixel_format = 0; --samples; } fprintf(stderr, "Error: failed to find any compatible MSAA format\n"); } else { fprintf(stderr, "Error: WGL_ARB_multisample isn't supported, using standart context\n"); } } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, kContextMajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, kContextMinorVersion, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if ((wglewIsSupported("WGL_ARB_create_context")) && (g_window.rc = wglCreateContextAttribsARB(g_window.dc, 0, attribs)) && (wglMakeCurrent(g_window.dc, g_window.rc))) { // Forward context has been successfully created wglDeleteContext(temp_rc); } else // failed to obtain forward context { // Use old context g_window.rc = temp_rc; } return true; }
Window *CreateNewWindow(void) { static system::UINT32 sWindowID = 0; char wndClassName[256] = {0}; _snprintf_s(wndClassName, 256, "EngineWindowClass_%d", sWindowID++); HINSTANCE hInstance = GetModuleHandle(NULL); WNDCLASSEX wndClass; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = WGLWindowProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = wndClassName; wndClass.hIconSm = LoadIcon(wndClass.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); if (!RegisterClassEx(&wndClass)) { // TODO: Log Error return NULL; } HWND hWnd = CreateWindow(wndClassName, "Untitled", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1024, 768, NULL, NULL, hInstance, NULL); if (!hWnd) { // TODO: Log Error return NULL; } PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_SWAP_EXCHANGE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cAccumBits = 32; pfd.cStencilBits = 32; HDC hDC = GetDC(hWnd); int pixelFormat = ChoosePixelFormat(hDC, &pfd); if (!pixelFormat) { // TODO: Log Error return NULL; } if(!SetPixelFormat(hDC, pixelFormat, &pfd)) { // TODO: Log Error return NULL; } HGLRC hGLRC = wglCreateContext(hDC); if (!wglMakeCurrent(hDC, hGLRC)) { // TODO: Log Error return NULL; } if (glewInit() != GLEW_OK) { //TODO: Log Error return NULL; } if (wglewIsSupported("WGL_ARB_create_context")) { int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; wglMakeCurrent(NULL, NULL); wglDeleteContext(hGLRC); hGLRC = wglCreateContextAttribsARB(hDC,0, attribs); } if (!hGLRC) { // TODO: Log Error return NULL; } if (!wglMakeCurrent(hDC, hGLRC)) { // TODO: Log Error return NULL; } RenderContext *pRC = new WGLRenderContext(hGLRC); WGLWindow *pWindow = new WGLWindow(hInstance, hWnd, hDC, pRC); pWindow->Hide(); pWindow->SetPosition(pWindow->GetPosition()); pWindow->SetSize(pWindow->GetSize()); return pWindow; }
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 }
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 }
bool GLContext::create30Context() { running = true; render = NULL; hdc = GetDC(hwnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL;// | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(hdc, &pfd); if (nPixelFormat == 0) return false; int bResult = SetPixelFormat(hdc, nPixelFormat, &pfd); if (!bResult) return false; HGLRC tempOGLWidget = wglCreateContext(hdc); wglMakeCurrent(hdc, tempOGLWidget); GLenum error = glewInit(); if (error != GLEW_OK) return false; int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { hrc = wglCreateContextAttribsARB(hdc, NULL, attributes); wglMakeCurrent(NULL, NULL); wglDeleteContext(tempOGLWidget); wglMakeCurrent(hdc, hrc); } else { hrc = tempOGLWidget; } int glVersion[2] = {-1, -1}; glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); std::cout << "Using OpenGL: " << glVersion[0] << "." << glVersion[1] << std::endl; // Output which version of OpenGL we are using render = new Render(); render->Init(); SetWindowLongPtr( hwnd, GWLP_USERDATA, reinterpret_cast<long>(render)); return true; // We have successfully created a context, 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; }
// 创建opengl窗口 BOOL GLWindow::CreateGlWnd(const char* title, int x, int y, int width, int height) { m_width = width; m_height = height; RECT windowRect = { 0, 0, width, height }; DWORD windowStyle = WS_OVERLAPPEDWINDOW; // 预留做全屏 DWORD windowExStyle = WS_EX_APPWINDOW; // 扩展样式 // 全屏处理 - 预留 // 窗口样式 //windowStyle = WS_POPUP; //windowExStyle |= WS_EX_TOPMOST; ::AdjustWindowRectEx(&windowRect, windowStyle, 0, windowExStyle); // 调整窗口 CreateEx(0, "OpenGL", title, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, x, y, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, NULL); if (!(m_hDc = GetDC(m_hWnd))) // 获取DC { DestroyGL(); // 销毁 return FALSE; // 不能获取DC } m_timerFrame = 1000; // 初始化 GLuint PixelFormat; static PIXELFORMATDESCRIPTOR pdf = { sizeof(PIXELFORMATDESCRIPTOR), // 结构体大小 1, // 版本号 PFD_DRAW_TO_WINDOW | // 支持窗口 PFD_SUPPORT_OPENGL | // 支持opengl PFD_DOUBLEBUFFER, // 支持双缓冲 PFD_TYPE_RGBA, // 申请RGBA格式 32, // 色彩深度 0, 0, 0, 0, 0, 0, // 忽略的色彩位 0, // 无alpha缓存 0, // 无shift Bit 0, // 无累加缓存 0, 0, 0, 0, // 忽略聚集位 24, // 16位Z-缓存 8, // 无蒙版缓存 0, // 无辅助缓存 PFD_MAIN_PLANE, // 主绘图层 0, // Reserved 0, 0, 0 // 忽略层遮罩 }; if (!(PixelFormat = ChoosePixelFormat(m_hDc, &pdf))) // 寻找相应像素格式 { DestroyGL(); // 销毁 // printf("1====error choose===="); return FALSE; } if (!SetPixelFormat(m_hDc, PixelFormat, &pdf)) { DestroyGL(); // printf("1====error choose===="); return FALSE; // 不能设置像素格式 } HGLRC tempContext; if (!(tempContext = wglCreateContext(m_hDc))) { DestroyGL(); // printf("2====error create context===="); return FALSE; // 不能获得着色描述表 } if (!wglMakeCurrent(m_hDc, tempContext)) // 开启低版本opengl { DestroyGL(); // printf("3========"); return FALSE; // 不能激活当前opengl渲染描述表 } if (GLEW_OK != glewInit()) { DestroyGL(); return FALSE; // glew初始化失败 } // 开启 opengl 4.3 支持 GLint attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, // 主版本4 WGL_CONTEXT_MINOR_VERSION_ARB, 3, // 次版本号3 WGL_CONTEXT_PROFILE_MASK_ARB,WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,//要求返回兼容模式环境,如果不指定或指定为WGL_CONTEXT_CORE_PROFILE_BIT_ARB会返回只包含核心功能的环境 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { m_hRc = wglCreateContextAttribsARB(m_hDc, 0, attribs); wglMakeCurrent(NULL, NULL); wglDeleteContext(tempContext); int result = wglMakeCurrent(m_hDc, m_hRc); // 设置opengl 4.3 if (result != 1) { return FALSE; } } else { // 不支持opengl4.X 还原为opengl 2.1 m_hRc = tempContext; } //RECT rect; // 客户区大小 //::GetClientRect(m_hWnd, &rect); //ResizeGLScene(rect.right - rect.left, rect.bottom - rect.top); // 设置GL屏幕 (注意,这里只使用客户区计算) ResizeGLScene(width, height); if (!initGL()) // 初始化opengl { DestroyGL(); return FALSE; } // 设定计时器 每秒刷新60次 SetTimer(m_hWnd, m_timerFrame, 1000 / 60, NULL); return TRUE; }
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC) { PIXELFORMATDESCRIPTOR pfd; int format; int zdepth, sdepth; #if defined WGL_CONTEXT_MAJOR_VERSION_ARB // NOT tested because WGL_CONTEXT_MAJOR_VERSION_ARB is undefined on my computer int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; #endif // get the device context (DC) *hDC = GetDC( hWnd ); if (gContextInitMode & GLUT_DEPTH) zdepth = 32; else zdepth = 0; if (gContextInitMode & GLUT_STENCIL) sdepth = 32; else sdepth = 0; // set the pixel format for the DC // MUCH OF THIS SHOULD BE OPTIONAL (like depth and stencil above)! 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 = zdepth; pfd.iLayerType = PFD_MAIN_PLANE; format = ChoosePixelFormat( *hDC, &pfd ); SetPixelFormat( *hDC, format, &pfd ); #if defined WGL_CONTEXT_MAJOR_VERSION_ARB // NOT tested because WGL_CONTEXT_MAJOR_VERSION_ARB is undefined on my computer // Try to support new OpenGL! attribs[1] = gContextVersionMajor; attribs[3] = gContextVersionMinor; if(wglewIsSupported("WGL_ARB_create_context") == 1) { *hRC = wglCreateContextAttribsARB(*hDC,0, attribs); wglMakeCurrent(*hDC, *hRC); } else { //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) // create and enable the render context (RC) *hRC = wglCreateContext( *hDC ); wglMakeCurrent( *hDC, *hRC ); } #else *hRC = wglCreateContext( *hDC ); wglMakeCurrent( *hDC, *hRC ); #endif }
// Setup function for GLUT parameters and loop //***************************************************************************** void InitGL(int* argc, char** argv) { // init GLUT glutInit(argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowPosition (glutGet(GLUT_SCREEN_WIDTH)/2 - iGraphicsWinWidth/2, glutGet(GLUT_SCREEN_HEIGHT)/2 - iGraphicsWinHeight/2); glutInitWindowSize(iGraphicsWinWidth, iGraphicsWinHeight); iGLUTWindowHandle = glutCreateWindow("OpenCL particles"); #if !(defined (__APPLE__) || defined(MACOSX)) glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif // register GLUT callbacks glutDisplayFunc(DisplayGL); glutReshapeFunc(ReshapeGL); glutMouseFunc(MouseGL); glutTimerFunc(REFRESH_DELAY, timerEvent, 0); glutMotionFunc(MotionGL); glutKeyboardFunc(KeyboardGL); glutSpecialFunc(SpecialGL); glutIdleFunc(IdleGL); // init GLEW glewInit(); if (!glewIsSupported("GL_VERSION_2_0 " "GL_VERSION_1_5 " "GL_ARB_multitexture " " GL_ARB_vertex_buffer_object")) { shrLog("Required OpenGL extensions missing !!!\n"); shrQAFinish(*argc, (const char **)argv, QA_FAILED); Cleanup(EXIT_FAILURE); } #ifdef _WIN32 if (wglewIsSupported("WGL_EXT_swap_control")) { // disable vertical sync wglSwapIntervalEXT(0); } #endif glEnable(GL_DEPTH_TEST); glClearColor(0.25, 0.25, 0.25, 1.0); glutReportErrors(); // create GLUT menu iGLUTMenuHandle = glutCreateMenu(MenuGL); glutAddMenuEntry("Reset Stacked Block [1]", '1'); glutAddMenuEntry("Reset Random Paricle Cloud [2]", '2'); glutAddMenuEntry("Drop particle sphere [3]", '3'); glutAddMenuEntry("Shoot particle sphere [4]", '4'); glutAddMenuEntry("Change to 'View' mode [v]", 'v'); glutAddMenuEntry("Change to 'Move cue-ball' mode [m]", 'm'); glutAddMenuEntry("Toggle Tour mode [t]", 't'); glutAddMenuEntry("Toggle point rendering [p]", 'p'); glutAddMenuEntry("Toggle animation On/Off <spacebar>", ' '); glutAddMenuEntry("Toggle between Full Screen and Windowed [f]", 'f'); glutAddMenuEntry("Step animation <return>", 13); glutAddMenuEntry("Toggle sliders [h]", 'h'); glutAddMenuEntry("Quit <esc>", '\033'); glutAttachMenu(GLUT_RIGHT_BUTTON); // Init view transform ResetViewTransform(); }
bool CGLDevice::Create30Context( const tInitStruct& initData ) { // store some variables m_hWnd = initData.hwnd; m_hDC = GetDC(m_hWnd); // choose PixelFormat PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(m_hDC, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return false; BOOL bResult = SetPixelFormat(m_hDC, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (bResult == 0) // If it fails return false; HGLRC tempOpenGLContext = wglCreateContext(m_hDC); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(m_hDC, tempOpenGLContext); // Make the OpenGL 2.1 context current and active // init GLEW (Have to be done after create a default Context) GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails return false; // get OpenGL version int32_t major, minor; GetGLVersion(major, minor); // *note* highly suggested to use CORE_PROFILE instead of COMPATIBLE_PROFILE uint32_t context_flags = WGL_CONTEXT_DEBUG_BIT_ARB //| WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB // Set our OpenGL context to be forward compatible ; int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, major, // Set the MAJOR version of OpenGL to 4 WGL_CONTEXT_MINOR_VERSION_ARB, minor, // Set the MINOR version of OpenGL to 2 // *note* highly suggested to use CORE_PROFILE instead of COMPATIBLE_PROFILE WGL_CONTEXT_FLAGS_ARB, context_flags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 3.x context creation extension is available m_hRC = wglCreateContextAttribsARB(m_hDC, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context wglMakeCurrent(m_hDC, m_hRC); // Make our OpenGL 3.0 context current } else { m_hRC = tempOpenGLContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context } int glVersion[2] = {-1, -1}; // Set some default values for the version glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using Debug::Print((boost::wformat(TEXT("Using OpenGL: %1%.%2%")) % glVersion[0] % glVersion[1])); // Output which version of OpenGL we are using // setup debug context if (context_flags & WGL_CONTEXT_DEBUG_BIT_ARB) { if (glDebugMessageCallback) { auto func = &CGLDevice::GLDebugCallback; glDebugMessageCallback(func, nullptr); } } // get window info glm::vec2 vp_size = BackBufferSize(); glViewport(0,0,(int32_t)vp_size.x, (int32_t)vp_size.y); // setup v-sync // http://www.3dbuzz.com/forum/threads/188320-Enable-or-Disable-VSync-in-OpenGL if(wglSwapIntervalEXT) { if(initData.bWaitForVSync) { wglSwapIntervalEXT(1); } else { wglSwapIntervalEXT(0); } } return true; }
bool GL_Init(HWND window, std::string *error_message) { *error_message = "ok"; hWnd = window; GLuint PixelFormat; // TODO: Change to use WGL_ARB_pixel_format instead static const PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 24, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 8, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // At least a 16Bit Z-Buffer (Depth Buffer) 8, // 8-bit Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; hDC = GetDC(hWnd); if (!hDC) { *error_message = "Failed to get a device context."; return false; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { *error_message = "Can't find a suitable PixelFormat."; return false; } if (!SetPixelFormat(hDC, PixelFormat, &pfd)) { *error_message = "Can't set the PixelFormat."; return false; } if (!(hRC = wglCreateContext(hDC))) { *error_message = "Can't create a GL rendering context."; return false; } if (!wglMakeCurrent(hDC, hRC)) { *error_message = "Can't activate the GL rendering context."; return false; } // Check for really old OpenGL drivers and refuse to run really early in some cases. // TODO: Also either tell the user to give up or point the user to the right websites. Here's some collected // information about a system that will not work: // GL_VERSION GL_VENDOR GL_RENDERER // "1.4.0 - Build 8.14.10.2364" "intel" intel Pineview Platform I18NCategory *err = GetI18NCategory("Error"); std::string glVersion = (const char *)glGetString(GL_VERSION); std::string glRenderer = (const char *)glGetString(GL_RENDERER); const std::string openGL_1 = "1."; if (glRenderer == "GDI Generic" || glVersion.substr(0, openGL_1.size()) == openGL_1) { const char *defaultError = "Insufficient OpenGL driver support detected!\n\n" "Your GPU reports that it does not support OpenGL 2.0, which is currently required for PPSSPP to run.\n\n" "Please check that your GPU is compatible with OpenGL 2.0.If it is, you need to find and install new graphics drivers from your GPU vendor's website.\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; MessageBox(hWnd, combined.c_str(), title.c_str(), MB_ICONERROR); // Avoid further error messages. Let's just bail, it's safe, and we can't continue. ExitProcess(0); } if (GLEW_OK != glewInit()) { *error_message = "Failed to initialize GLEW."; return false; } CheckGLExtensions(); int contextFlags = enableGLDebug ? 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; /* MessageBox(0,ConvertUTF8ToWString((const char *)glGetString(GL_VERSION)).c_str(),0,0); MessageBox(0,ConvertUTF8ToWString((const char *)glGetString(GL_VENDOR)).c_str(),0,0); MessageBox(0,ConvertUTF8ToWString((const char *)glGetString(GL_RENDERER)).c_str(),0,0); MessageBox(0,ConvertUTF8ToWString((const char *)glGetString(GL_SHADING_LANGUAGE_VERSION)).c_str(),0,0); */ glstate.Initialize(); if (wglSwapIntervalEXT) wglSwapIntervalEXT(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 }
bool GLAppWindow::Create(LPCWSTR title, int width, int height) { WNDCLASS window_class; DWORD ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; _hinstance = GetModuleHandle(NULL); window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; window_class.lpfnWndProc = (WNDPROC) CoreApp::MsgProc; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = _hinstance; window_class.hIcon = LoadIcon(NULL, IDI_WINLOGO); window_class.hCursor = LoadCursor(NULL, IDC_ARROW); window_class.hbrBackground = NULL; window_class.lpszMenuName = NULL; window_class.lpszClassName = title; if(!RegisterClass(&window_class)) return false; _hwnd = CreateWindowEx(ex_style, title, title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, _width, _height, NULL, NULL, _hinstance, NULL); //create opengl context _hdc = GetDC(_hwnd); PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(_hdc, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return false; BOOL bResult = SetPixelFormat(_hdc, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (!bResult) // If it fails return false; HGLRC tempOpenGLContext = wglCreateContext(_hdc); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(_hdc, tempOpenGLContext); // Make the OpenGL 2.1 context current and active GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails return false; int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // Set the MAJOR version of OpenGL to 3 WGL_CONTEXT_MINOR_VERSION_ARB, 2, // Set the MINOR version of OpenGL to 2 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 3.x context creation extension is available _hrc = wglCreateContextAttribsARB(_hdc, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context wglMakeCurrent(_hdc, _hrc); // Make our OpenGL 3.0 context current } else { _hrc = tempOpenGLContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context } int glVersion[2] = {-1, -1}; // Set some default values for the version glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using ShowWindow(_hwnd, SW_SHOW); UpdateWindow(_hwnd); return true; }