bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget) { QGLTemporaryContext tempContext; PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC) wglGetProcAddress("wglCreatePbufferARB"); PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC) wglGetProcAddress("wglGetPbufferDCARB"); PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = (PFNWGLQUERYPBUFFERARBPROC) wglGetProcAddress("wglQueryPbufferARB"); PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB"); if (!wglCreatePbufferARB) // assumes that if one can be resolved, all of them can return false; dc = wglGetCurrentDC(); Q_ASSERT(dc); has_render_texture = false; // sample buffers doesn't work in conjunction with the render_texture extension if (!f.sampleBuffers()) { PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB"); if (wglGetExtensionsStringARB) { QString extensions(QLatin1String(wglGetExtensionsStringARB(dc))); has_render_texture = extensions.contains(QLatin1String("WGL_ARB_render_texture")); } } int attribs[40]; qt_format_to_attrib_list(has_render_texture, f, attribs); // Find pbuffer capable pixel format. unsigned int num_formats = 0; int pixel_format; wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats); // some GL implementations don't support pbuffers with accum // buffers, so try that before we give up if (num_formats == 0 && f.accum()) { QGLFormat tmp = f; tmp.setAccum(false); qt_format_to_attrib_list(has_render_texture, tmp, attribs); wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats); } if (num_formats == 0) { qWarning("QGLPixelBuffer: Unable to find a pixel format with pbuffer - giving up."); return false; } format = pfiToQGLFormat(dc, pixel_format); // NB! The below ONLY works if the width/height are powers of 2. // Set some pBuffer attributes so that we can use this pBuffer as // a 2D RGBA texture target. int pb_attribs[] = {WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB, WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, 0}; int pb_attribs_null[] = {0}; pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(), has_render_texture ? pb_attribs : pb_attribs_null); if (!pbuf) { // try again without the render_texture extension pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(), pb_attribs_null); has_render_texture = false; if (!pbuf) { qWarning("QGLPixelBuffer: Unable to create pbuffer [w=%d, h=%d] - giving up.", size.width(), size.height()); return false; } } dc = wglGetPbufferDCARB(pbuf); ctx = wglCreateContext(dc); if (!dc || !ctx) { qWarning("QGLPixelBuffer: Unable to create pbuffer context - giving up."); return false; } // Explicitly disable the render_texture extension if we have a // multi-sampled pbuffer context. This seems to be a problem only with // ATI cards if multi-sampling is forced globally in the driver. wglMakeCurrent(dc, ctx); GLint samples = 0; glGetIntegerv(GL_SAMPLES_ARB, &samples); if (has_render_texture && samples != 0) has_render_texture = false; HGLRC share_ctx = shareWidget ? shareWidget->d_func()->glcx->d_func()->rc : 0; if (share_ctx && !wglShareLists(share_ctx, ctx)) qWarning("QGLPixelBuffer: Unable to share display lists - with share widget."); int width, height; wglQueryPbufferARB(pbuf, WGL_PBUFFER_WIDTH_ARB, &width); wglQueryPbufferARB(pbuf, WGL_PBUFFER_HEIGHT_ARB, &height); return true; }
static void print_screen_info(HDC _hdc, GLboolean limits, GLboolean singleLine) { WNDCLASS wc; HWND win; HGLRC ctx; int visinfo; HDC hdc; PIXELFORMATDESCRIPTOR pfd; int version; const char *oglString = "OpenGL"; memset(&wc, 0, sizeof wc); wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.lpfnWndProc = WndProc; wc.lpszClassName = "wglinfo"; wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; RegisterClass(&wc); win = CreateWindowEx(0, wc.lpszClassName, "wglinfo", WS_CLIPSIBLINGS | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, wc.hInstance, NULL); if (!win) { fprintf(stderr, "Couldn't create window\n"); return; } hdc = GetDC(win); if (!hdc) { fprintf(stderr, "Couldn't obtain HDC\n"); return; } pfd.cColorBits = 3; pfd.cRedBits = 1; pfd.cGreenBits = 1; pfd.cBlueBits = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.nSize = sizeof(pfd); pfd.nVersion = 1; visinfo = ChoosePixelFormat(hdc, &pfd); if (!visinfo) { pfd.dwFlags |= PFD_DOUBLEBUFFER; visinfo = ChoosePixelFormat(hdc, &pfd); } if (!visinfo) { fprintf(stderr, "Error: couldn't find RGB WGL visual\n"); return; } SetPixelFormat(hdc, visinfo, &pfd); ctx = wglCreateContext(hdc); if (!ctx) { fprintf(stderr, "Error: wglCreateContext failed\n"); return; } if (wglMakeCurrent(hdc, ctx)) { #if defined(WGL_ARB_extensions_string) PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB_func = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); #endif const char *glVendor = (const char *) glGetString(GL_VENDOR); const char *glRenderer = (const char *) glGetString(GL_RENDERER); const char *glVersion = (const char *) glGetString(GL_VERSION); const char *glExtensions = (const char *) glGetString(GL_EXTENSIONS); struct ext_functions extfuncs; #if defined(WGL_ARB_extensions_string) if (wglGetExtensionsStringARB_func) { const char *wglExtensions = wglGetExtensionsStringARB_func(hdc); if(wglExtensions) { printf("WGL extensions:\n"); print_extension_list(wglExtensions, singleLine); } } #endif printf("OpenGL vendor string: %s\n", glVendor); printf("OpenGL renderer string: %s\n", glRenderer); printf("OpenGL version string: %s\n", glVersion); #ifdef GL_VERSION_2_0 if (glVersion[0] >= '2' && glVersion[1] == '.') { char *v = (char *) glGetString(GL_SHADING_LANGUAGE_VERSION); printf("OpenGL shading language version string: %s\n", v); } #endif extfuncs.GetProgramivARB = (PFNGLGETPROGRAMIVARBPROC) wglGetProcAddress("glGetProgramivARB"); extfuncs.GetStringi = (PFNGLGETSTRINGIPROC) wglGetProcAddress("glGetStringi"); extfuncs.GetConvolutionParameteriv = (GETCONVOLUTIONPARAMETERIVPROC) wglGetProcAddress("glGetConvolutionParameteriv"); version = (glVersion[0] - '0') * 10 + (glVersion[2] - '0'); printf("OpenGL extensions:\n"); print_extension_list(glExtensions, singleLine); if (limits) { print_limits(glExtensions, oglString, version, &extfuncs); } } else { fprintf(stderr, "Error: wglMakeCurrent failed\n"); } DestroyWindow(win); }
/** * It creates an OpenGL vout display. */ static int Open(vlc_object_t *object) { vout_display_t *vd = (vout_display_t *)object; vout_display_sys_t *sys; /* Allocate structure */ vd->sys = sys = (vout_display_sys_t *)calloc(1, sizeof(*sys)); // sunqueen modify if (!sys) return VLC_ENOMEM; /* */ if (CommonInit(vd)) goto error; EventThreadUpdateTitle(sys->event, VOUT_TITLE " (OpenGL output)"); /* process selected GPU affinity */ int nVidiaAffinity = var_InheritInteger(vd, "gpu-affinity"); if (nVidiaAffinity >= 0) CreateGPUAffinityDC(vd, nVidiaAffinity); /* */ sys->hGLDC = GetDC(sys->hvideownd); /* Set the pixel format for the DC */ 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 = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; SetPixelFormat(sys->hGLDC, ChoosePixelFormat(sys->hGLDC, &pfd), &pfd); /* * Create and enable the render context * For GPU affinity, attach the window DC * to the GPU affinity DC */ sys->hGLRC = wglCreateContext((sys->affinityHDC != NULL) ? sys->affinityHDC : sys->hGLDC); wglMakeCurrent(sys->hGLDC, sys->hGLRC); const char *extensions = (const char*)glGetString(GL_EXTENSIONS); #ifdef WGL_EXT_swap_control if (HasExtension(extensions, "WGL_EXT_swap_control")) { PFNWGLSWAPINTERVALEXTPROC SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (SwapIntervalEXT) SwapIntervalEXT(1); } #endif /* */ sys->gl.lock = NULL; sys->gl.unlock = NULL; sys->gl.swap = Swap; sys->gl.getProcAddress = OurGetProcAddress; sys->gl.sys = vd; video_format_t fmt = vd->fmt; const vlc_fourcc_t *subpicture_chromas; sys->vgl = vout_display_opengl_New(&fmt, &subpicture_chromas, &sys->gl); if (!sys->vgl) goto error; vout_display_info_t info = vd->info; info.has_double_click = true; info.has_hide_mouse = false; info.has_event_thread = true; info.subpicture_chromas = subpicture_chromas; /* Setup vout_display now that everything is fine */ vd->fmt = fmt; vd->info = info; vd->pool = Pool; vd->prepare = Prepare; vd->display = Display; vd->control = Control; vd->manage = Manage; return VLC_SUCCESS; error: Close(object); return VLC_EGENERIC; }
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); } }
void Tempest::Detail::ImplDeviceBase::initExt() { const char * ext = (const char*)glGetString(GL_EXTENSIONS); if( ext==nullptr ) ext = ""; const char *renderer= (const char*)glGetString(GL_RENDERER); T_ASSERT_X(ext!=nullptr, "opengl context not created"); hasS3tcTextures = (strstr(ext, "GL_OES_texture_compression_S3TC")!=nullptr) || (strstr(ext, "GL_EXT_texture_compression_s3tc")!=nullptr); hasETC1Textures = (strstr(ext, "GL_OES_compressed_ETC1_RGB8_texture")!=nullptr); hasWriteonlyRendering = (strstr(ext, "GL_QCOM_writeonly_rendering")!=nullptr); hasNpotTexture = (strstr(ext, "GL_OES_texture_npot")!=nullptr) || (strstr(ext, "GL_ARB_texture_non_power_of_two")!=nullptr); hasHalfSupport = (strstr(ext, "GL_OES_vertex_half_float")!=nullptr) || (strstr(ext, "GL_ARB_half_float_vertex")!=nullptr); #ifdef __ANDROID__ hasRenderToRGBTexture = strstr(ext, "GL_OES_rgb8_rgba8")!=0; hasRenderToRGBATexture = (strstr(ext, "GL_OES_rgb8_rgba8")!=0)||(strstr(ext, "GL_ARM_rgba8")!=0); #else hasRenderToRGBTexture = 1; hasRenderToRGBATexture = 1; #endif hasTextureFloat = strstr(ext, "GL_ARB_texture_float")!=nullptr; hasPackedFloat = strstr(ext, "GL_EXT_packed_float") !=nullptr; hasQCOMTiles = strstr(ext, "GL_QCOM_tiled_rendering") !=nullptr; hasDiscardBuffers = strstr(ext, "GL_EXT_discard_framebuffer")!=nullptr; #ifdef __WINDOWS__ if( strstr(ext, "WGL_EXT_swap_control") ){ wglSwapInterval = (Detail::PFNGLWGLSWAPINTERVALPROC)wglGetProcAddress("wglSwapIntervalEXT"); } #endif hasTileBasedRender = hasQCOMTiles | hasDiscardBuffers; #ifdef __ANDROID__ if( hasQCOMTiles ){ glStartTilingQCOM = (Detail::PFNGLSTARTTILINGQCOMPROC)eglGetProcAddress("glStartTilingQCOM"); glEndTilingQCOM = (Detail::PFNGLENDTILINGQCOMPROC)eglGetProcAddress("glEndTilingQCOM"); } if( hasDiscardBuffers ){ glDiscardFrameBuffer = (Detail::PFNGLDISCARDFRAMEBUFFERPROC)eglGetProcAddress("glDiscardFramebufferEXT"); } #endif #ifdef __IOS__ if( hasQCOMTiles ){ glStartTilingQCOM = 0; glEndTilingQCOM = 0; } if( hasDiscardBuffers ){ this->glDiscardFrameBuffer = 0; hasDiscardBuffers=false;//TODO } #endif caps.hasHalf2 = hasHalfSupport; caps.hasHalf4 = hasHalfSupport; caps.hasRedableDepth = ((strstr(ext, "GL_OES_depth_texture")!=nullptr) || (strstr(ext, "GL_ARB_depth_texture")!=nullptr)) && (strcmp(renderer,"PowerVR SGX 540")!=0);//PVR bug caps.hasNativeRGB =hasRenderToRGBTexture; caps.hasNativeRGBA=hasRenderToRGBATexture; glGetIntegerv( GL_MAX_TEXTURE_SIZE, &caps.maxTextureSize ); #ifdef __MOBILE_PLATFORM__ glGetIntegerv( GL_MAX_VARYING_VECTORS, &caps.maxVaryingVectors ); caps.maxVaryingComponents = caps.maxVaryingVectors*4; #else glGetIntegerv( GL_MAX_VARYING_COMPONENTS, &caps.maxVaryingComponents ); caps.maxVaryingVectors = caps.maxVaryingComponents/4; #endif #ifdef GL_MAX_FRAGMENT_UNIFORM_COMPONENTS glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &caps.maxVertexUniformVectors ); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS,&caps.maxFragmentUniformVectors); caps.maxVertexUniformVectors /= 4; caps.maxFragmentUniformVectors /= 4; #else glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS,&caps.maxFragmentUniformVectors); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &caps.maxVertexUniformVectors ); #endif //T_ASSERT_X( errCk(), "OpenGL error" ); #ifdef __MOBILE_PLATFORM__ caps.maxRTCount = 1; #else glGetIntegerv( GL_MAX_COLOR_ATTACHMENTS, &caps.maxRTCount ); if( caps.maxRTCount>32 ) caps.maxRTCount = 32; #endif caps.hasNpotTexture = hasNpotTexture; wglSwapInterval = 0; }
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; }
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; }
static int wGLCreateContext(Ihandle* ih, IGlControlData* gldata) { Ihandle* ih_shared; HGLRC shared_context = NULL; int number; int isIndex = 0; int pixelFormat; PIXELFORMATDESCRIPTOR test_pfd; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), /* size of this pfd */ 1, /* version number */ PFD_DRAW_TO_WINDOW | /* support window */ PFD_SUPPORT_OPENGL, /* support OpenGL */ PFD_TYPE_RGBA, /* RGBA type */ 24, /* 24-bit color depth */ 0, 0, 0, 0, 0, 0, /* color bits ignored */ 0, /* no alpha buffer */ 0, /* shift bit ignored */ 0, /* no accumulation buffer */ 0, 0, 0, 0, /* accum bits ignored */ 16, /* 32-bit z-buffer */ 0, /* no stencil buffer */ 0, /* no auxiliary buffer */ PFD_MAIN_PLANE, /* main layer */ 0, /* reserved */ 0, 0, 0 /* layer masks ignored */ }; /* the IupCanvas is already mapped, just initialize the OpenGL context */ /* double or single buffer */ if (iupStrEqualNoCase(iupAttribGetStr(ih,"BUFFER"), "DOUBLE")) pfd.dwFlags |= PFD_DOUBLEBUFFER; /* stereo */ if (iupAttribGetBoolean(ih,"STEREO")) pfd.dwFlags |= PFD_STEREO; /* rgba or index */ if (iupStrEqualNoCase(iupAttribGetStr(ih,"COLOR"), "INDEX")) { isIndex = 1; pfd.iPixelType = PFD_TYPE_COLORINDEX; pfd.cColorBits = 8; /* assume 8 bits when indexed */ number = iupAttribGetInt(ih,"BUFFER_SIZE"); if (number > 0) pfd.cColorBits = (BYTE)number; } /* red, green, blue bits */ number = iupAttribGetInt(ih,"RED_SIZE"); if (number > 0) pfd.cRedBits = (BYTE)number; pfd.cRedShift = 0; number = iupAttribGetInt(ih,"GREEN_SIZE"); if (number > 0) pfd.cGreenBits = (BYTE)number; pfd.cGreenShift = pfd.cRedBits; number = iupAttribGetInt(ih,"BLUE_SIZE"); if (number > 0) pfd.cBlueBits = (BYTE)number; pfd.cBlueShift = pfd.cRedBits + pfd.cGreenBits; number = iupAttribGetInt(ih,"ALPHA_SIZE"); if (number > 0) pfd.cAlphaBits = (BYTE)number; pfd.cAlphaShift = pfd.cRedBits + pfd.cGreenBits + pfd.cBlueBits; /* depth and stencil size */ number = iupAttribGetInt(ih,"DEPTH_SIZE"); if (number > 0) pfd.cDepthBits = (BYTE)number; /* stencil */ number = iupAttribGetInt(ih,"STENCIL_SIZE"); if (number > 0) pfd.cStencilBits = (BYTE)number; /* red, green, blue accumulation bits */ number = iupAttribGetInt(ih,"ACCUM_RED_SIZE"); if (number > 0) pfd.cAccumRedBits = (BYTE)number; number = iupAttribGetInt(ih,"ACCUM_GREEN_SIZE"); if (number > 0) pfd.cAccumGreenBits = (BYTE)number; number = iupAttribGetInt(ih,"ACCUM_BLUE_SIZE"); if (number > 0) pfd.cAccumBlueBits = (BYTE)number; number = iupAttribGetInt(ih,"ACCUM_ALPHA_SIZE"); if (number > 0) pfd.cAccumAlphaBits = (BYTE)number; pfd.cAccumBits = pfd.cAccumRedBits + pfd.cAccumGreenBits + pfd.cAccumBlueBits + pfd.cAccumAlphaBits; /* get a device context */ { LONG style = GetClassLong(gldata->window, GCL_STYLE); gldata->is_owned_dc = (int) ((style & CS_OWNDC) || (style & CS_CLASSDC)); } gldata->device = GetDC(gldata->window); iupAttribSet(ih, "VISUAL", (char*)gldata->device); /* choose pixel format */ pixelFormat = ChoosePixelFormat(gldata->device, &pfd); if (pixelFormat == 0) { iupAttribSet(ih, "ERROR", "No appropriate pixel format."); iupAttribSetStr(ih, "LASTERROR", IupGetGlobal("LASTERROR")); return IUP_NOERROR; } SetPixelFormat(gldata->device,pixelFormat,&pfd); ih_shared = IupGetAttributeHandle(ih, "SHAREDCONTEXT"); if (ih_shared && IupClassMatch(ih_shared, "glcanvas")) /* must be an IupGLCanvas */ { IGlControlData* shared_gldata = (IGlControlData*)iupAttribGet(ih_shared, "_IUP_GLCONTROLDATA"); shared_context = shared_gldata->context; } /* create rendering context */ if (iupAttribGetBoolean(ih, "ARBCONTEXT")) { wglCreateContextAttribsARB_PROC CreateContextAttribsARB; HGLRC tempContext = wglCreateContext(gldata->device); HGLRC oldContext = wglGetCurrentContext(); HDC oldDC = wglGetCurrentDC(); wglMakeCurrent(gldata->device, tempContext); /* wglGetProcAddress only works with an active context */ CreateContextAttribsARB = (wglCreateContextAttribsARB_PROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (CreateContextAttribsARB) { int attribs[9], a = 0; char* value; value = iupAttribGetStr(ih, "CONTEXTVERSION"); if (value) { int major, minor; if (iupStrToIntInt(value, &major, &minor, '.') == 2) { attribs[a++] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[a++] = major; attribs[a++] = WGL_CONTEXT_MINOR_VERSION_ARB; attribs[a++] = minor; } } value = iupAttribGetStr(ih, "CONTEXTFLAGS"); if (value) { int flags = 0; if (iupStrEqualNoCase(value, "DEBUG")) flags = WGL_CONTEXT_DEBUG_BIT_ARB; else if (iupStrEqualNoCase(value, "FORWARDCOMPATIBLE")) flags = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; else if (iupStrEqualNoCase(value, "DEBUGFORWARDCOMPATIBLE")) flags = WGL_CONTEXT_DEBUG_BIT_ARB|WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; if (flags) { attribs[a++] = WGL_CONTEXT_FLAGS_ARB; attribs[a++] = flags; } } value = iupAttribGetStr(ih, "CONTEXTPROFILE"); if (value) { int profile = 0; if (iupStrEqualNoCase(value, "CORE")) profile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; else if (iupStrEqualNoCase(value, "COMPATIBILITY")) profile = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; else if (iupStrEqualNoCase(value, "CORECOMPATIBILITY")) profile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB|WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; if (profile) { attribs[a++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[a++] = profile; } } attribs[a] = 0; /* terminator */ gldata->context = CreateContextAttribsARB(gldata->device, shared_context, attribs); if (!gldata->context) { DWORD error = GetLastError(); if (error == ERROR_INVALID_VERSION_ARB) iupAttribSetStr(ih, "LASTERROR", "Invalid ARB Version"); else if (error == ERROR_INVALID_PROFILE_ARB) iupAttribSetStr(ih, "LASTERROR", "Invalid ARGB Profile"); else iupAttribSetStr(ih, "LASTERROR", IupGetGlobal("LASTERROR")); iupAttribSet(ih, "ERROR", "Could not create a rendering context."); wglMakeCurrent(oldDC, oldContext); wglDeleteContext(tempContext); return IUP_NOERROR; } } wglMakeCurrent(oldDC, oldContext); wglDeleteContext(tempContext); if (!CreateContextAttribsARB) { gldata->context = wglCreateContext(gldata->device); iupAttribSet(ih, "ARBCONTEXT", "NO"); } } else gldata->context = wglCreateContext(gldata->device); if (!gldata->context) { iupAttribSet(ih, "ERROR", "Could not create a rendering context."); iupAttribSetStr(ih, "LASTERROR", IupGetGlobal("LASTERROR")); return IUP_NOERROR; } iupAttribSet(ih, "CONTEXT", (char*)gldata->context); if (shared_context) wglShareLists(shared_context, gldata->context); /* create colormap for index mode */ if (isIndex) { if (!gldata->palette) { LOGPALETTE lp = {0x300,1,{255,255,255,PC_NOCOLLAPSE}}; /* set first color as white */ gldata->palette = CreatePalette(&lp); ResizePalette(gldata->palette,1<<pfd.cColorBits); iupAttribSet(ih, "COLORMAP", (char*)gldata->palette); } SelectPalette(gldata->device,gldata->palette,FALSE); RealizePalette(gldata->device); } DescribePixelFormat(gldata->device, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &test_pfd); if ((pfd.dwFlags & PFD_STEREO) && !(test_pfd.dwFlags & PFD_STEREO)) { iupAttribSet(ih, "STEREO", "NO"); return IUP_NOERROR; } iupAttribSet(ih, "ERROR", NULL); return IUP_NOERROR; }
// Initialize WGL-specific extensions // This function is called once before initial context creation, i.e. before // any WGL extensions could be present. This is done in order to have both // extension variable clearing and loading in the same place, hopefully // decreasing the possibility of forgetting to add one without the other. // static void initWGLExtensions(_GLFWwindow* window) { // This needs to include every function pointer loaded below window->wgl.SwapIntervalEXT = NULL; window->wgl.GetPixelFormatAttribivARB = NULL; window->wgl.GetExtensionsStringARB = NULL; window->wgl.GetExtensionsStringEXT = NULL; window->wgl.CreateContextAttribsARB = NULL; // This needs to include every extension used below except for // WGL_ARB_extensions_string and WGL_EXT_extensions_string window->wgl.ARB_multisample = GL_FALSE; window->wgl.ARB_framebuffer_sRGB = GL_FALSE; window->wgl.ARB_create_context = GL_FALSE; window->wgl.ARB_create_context_profile = GL_FALSE; window->wgl.EXT_create_context_es2_profile = GL_FALSE; window->wgl.ARB_create_context_robustness = GL_FALSE; window->wgl.EXT_swap_control = GL_FALSE; window->wgl.ARB_pixel_format = GL_FALSE; window->wgl.GetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); if (!window->wgl.GetExtensionsStringEXT) { window->wgl.GetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB"); if (!window->wgl.GetExtensionsStringARB) return; } if (_glfwPlatformExtensionSupported("WGL_ARB_multisample")) window->wgl.ARB_multisample = GL_TRUE; if (_glfwPlatformExtensionSupported("WGL_ARB_framebuffer_sRGB")) window->wgl.ARB_framebuffer_sRGB = GL_TRUE; if (_glfwPlatformExtensionSupported("WGL_ARB_create_context")) { window->wgl.CreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); if (window->wgl.CreateContextAttribsARB) window->wgl.ARB_create_context = GL_TRUE; } if (window->wgl.ARB_create_context) { if (_glfwPlatformExtensionSupported("WGL_ARB_create_context_profile")) window->wgl.ARB_create_context_profile = GL_TRUE; } if (window->wgl.ARB_create_context && window->wgl.ARB_create_context_profile) { if (_glfwPlatformExtensionSupported("WGL_EXT_create_context_es2_profile")) window->wgl.EXT_create_context_es2_profile = GL_TRUE; } if (window->wgl.ARB_create_context) { if (_glfwPlatformExtensionSupported("WGL_ARB_create_context_robustness")) window->wgl.ARB_create_context_robustness = GL_TRUE; } if (_glfwPlatformExtensionSupported("WGL_EXT_swap_control")) { window->wgl.SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); if (window->wgl.SwapIntervalEXT) window->wgl.EXT_swap_control = GL_TRUE; } if (_glfwPlatformExtensionSupported("WGL_ARB_pixel_format")) { window->wgl.GetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC) wglGetProcAddress("wglGetPixelFormatAttribivARB"); if (window->wgl.GetPixelFormatAttribivARB) window->wgl.ARB_pixel_format = GL_TRUE; } }
void GlTraceFilterModel::checkExtensions() { const GLubyte *extensionString, *versionString; int supportedMajor, supportedMinor; QGLWidget w; w.makeCurrent(); extensionString = glGetString(GL_EXTENSIONS); versionString = glGetString(GL_VERSION); supportedMajor = versionString[0] - '0'; supportedMinor = versionString[2] - '0'; QByteArray extensions = QByteArray( reinterpret_cast<const char*>(extensionString)); #ifdef GLSLDB_WIN PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0; wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); if(wglGetExtensionsStringARB) { extensions.append(' '); extensions.append(QByteArray(reinterpret_cast<const char*>(wglGetExtensionsStringARB(wglGetCurrentDC())))); } #elif defined(GLSLDB_LINUX) int supportedXMajor, supportedXMinor; const char *versionXString; versionXString = glXQueryServerString(XOpenDisplay(NULL), 0, GLX_VERSION); supportedXMajor = versionXString[0] - '0'; supportedXMinor = versionXString[2] - '0'; extensions.append(' '); extensions.append( QByteArray( reinterpret_cast<const char*>(glXQueryServerString( XOpenDisplay(NULL), 0, GLX_EXTENSIONS)))); extensions.append(' '); extensions.append( QByteArray( reinterpret_cast<const char*>(glXGetClientString( XOpenDisplay(NULL), GLX_EXTENSIONS)))); extensions.append(' '); extensions.append( QByteArray( reinterpret_cast<const char*>(glXQueryExtensionsString( XOpenDisplay(NULL), 0)))); #elif defined(GLSLDB_OSX) #warning "FIXME: any OSX specific extensions wee need to add here?" #endif QList<QByteArray> extList = extensions.split(' '); for (int i = 0; i < this->rootItem->childCount(); i++) { GlTraceFilterItem *item = this->rootItem->child(i); if (strstr(item->function->extname, "GL_VERSION_") == item->function->extname) { int major, minor; major = item->function->extname[11] - '0'; minor = item->function->extname[13] - '0'; if (major < supportedMajor || (major == supportedMajor && minor <= supportedMinor)) { item->isSupported = true; } else { item->isSupported = false; } } #if defined(_WIN32) else if (strstr(item->function->extname, "WGL_VERSION_") == item->function->extname) { item->isSupported = true; } #elif defined(GLSLDB_LINUX) else if (strstr(item->function->extname, "GLX_VERSION_") == item->function->extname) { int major, minor; major = item->function->extname[12] - '0'; minor = item->function->extname[14] - '0'; if (major < supportedXMajor || (major == supportedXMajor && minor <= supportedXMinor)) { item->isSupported = true; } else { item->isSupported = false; } } #elif defined(GLSLDB_OSX) #warning "FIXME: any OSX specific extensions wee need to add here?" #endif else { item->isSupported = extList.contains(item->function->extname); } } }
CoglFuncPtr cogl_get_proc_address (const gchar* name) { /* Sucks to ifdef here but not other option..? would be nice to * split the code up for more reuse (once more backends use this */ #if defined(HAVE_CLUTTER_GLX) static GLXGetProcAddressProc get_proc_func = NULL; static void *dlhand = NULL; if (get_proc_func == NULL && dlhand == NULL) { dlhand = dlopen (NULL, RTLD_LAZY); if (dlhand) { dlerror (); get_proc_func = (GLXGetProcAddressProc) dlsym (dlhand, "glXGetProcAddress"); if (dlerror () != NULL) { get_proc_func = (GLXGetProcAddressProc) dlsym (dlhand, "glXGetProcAddressARB"); } if (dlerror () != NULL) { get_proc_func = NULL; g_warning ("failed to bind GLXGetProcAddress " "or GLXGetProcAddressARB"); } } } if (get_proc_func) return get_proc_func ((unsigned char*) name); #elif defined(HAVE_CLUTTER_WIN32) return (CoglFuncPtr) wglGetProcAddress ((LPCSTR) name); #else /* HAVE_CLUTTER_WIN32 */ /* this should find the right function if the program is linked against a * library providing it */ static GModule *module = NULL; if (module == NULL) module = g_module_open (NULL, G_MODULE_BIND_LAZY | G_MODULE_BIND_LOCAL); if (module) { gpointer symbol; if (g_module_symbol (module, name, &symbol)) return symbol; } #endif /* HAVE_CLUTTER_WIN32 */ return NULL; }
void GlContext::create(uint32_t /*_width*/, uint32_t /*_height*/) { m_opengl32dll = bx::dlopen("opengl32.dll"); BGFX_FATAL(NULL != m_opengl32dll, Fatal::UnableToInitialize, "Failed to load opengl32.dll."); wglGetProcAddress = (PFNWGLGETPROCADDRESSPROC)bx::dlsym(m_opengl32dll, "wglGetProcAddress"); BGFX_FATAL(NULL != wglGetProcAddress, Fatal::UnableToInitialize, "Failed get wglGetProcAddress."); // If g_bgfxHwnd is NULL, the assumption is that GL context was created // by user (for example, using SDL, GLFW, etc.) BX_WARN(NULL != g_bgfxHwnd , "bgfx::winSetHwnd with valid window is not called. This might " "be intentional when GL context is created by the user." ); if (NULL != g_bgfxHwnd) { wglMakeCurrent = (PFNWGLMAKECURRENTPROC)bx::dlsym(m_opengl32dll, "wglMakeCurrent"); BGFX_FATAL(NULL != wglMakeCurrent, Fatal::UnableToInitialize, "Failed get wglMakeCurrent."); wglCreateContext = (PFNWGLCREATECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglCreateContext"); BGFX_FATAL(NULL != wglCreateContext, Fatal::UnableToInitialize, "Failed get wglCreateContext."); wglDeleteContext = (PFNWGLDELETECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglDeleteContext"); BGFX_FATAL(NULL != wglDeleteContext, Fatal::UnableToInitialize, "Failed get wglDeleteContext."); m_hdc = GetDC(g_bgfxHwnd); BGFX_FATAL(NULL != m_hdc, Fatal::UnableToInitialize, "GetDC failed!"); // Dummy window to peek into WGL functionality. // // An application can only set the pixel format of a window one time. // Once a window's pixel format is set, it cannot be changed. // MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/dd369049%28v=vs.85%29.aspx HWND hwnd = CreateWindowA("STATIC" , "" , WS_POPUP|WS_DISABLED , -32000 , -32000 , 0 , 0 , NULL , NULL , GetModuleHandle(NULL) , 0 ); HDC hdc = GetDC(hwnd); BGFX_FATAL(NULL != hdc, Fatal::UnableToInitialize, "GetDC failed!"); HGLRC context = createContext(hdc); wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (NULL != wglGetExtensionsStringARB) { const char* extensions = (const char*)wglGetExtensionsStringARB(hdc); BX_TRACE("WGL extensions:"); dumpExtensions(extensions); } if (NULL != wglChoosePixelFormatARB && NULL != wglCreateContextAttribsARB) { int32_t attrs[] = { WGL_SAMPLE_BUFFERS_ARB, 0, WGL_SAMPLES_ARB, 0, WGL_SUPPORT_OPENGL_ARB, true, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_DRAW_TO_WINDOW_ARB, true, WGL_DOUBLE_BUFFER_ARB, true, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0 }; int result; int pixelFormat; uint32_t numFormats = 0; do { result = wglChoosePixelFormatARB(m_hdc, attrs, NULL, 1, &pixelFormat, &numFormats); if (0 == result || 0 == numFormats) { attrs[3] >>= 1; attrs[1] = attrs[3] == 0 ? 0 : 1; } } while (0 == numFormats); PIXELFORMATDESCRIPTOR pfd; DescribePixelFormat(m_hdc, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd); BX_TRACE("Pixel format:\n" "\tiPixelType %d\n" "\tcColorBits %d\n" "\tcAlphaBits %d\n" "\tcDepthBits %d\n" "\tcStencilBits %d\n" , pfd.iPixelType , pfd.cColorBits , pfd.cAlphaBits , pfd.cDepthBits , pfd.cStencilBits ); result = SetPixelFormat(m_hdc, pixelFormat, &pfd); // When window is created by SDL and SDL_WINDOW_OPENGL is set SetPixelFormat // will fail. Just warn and continue. In case it failed for some other reason // create context will fail and it will error out there. BX_WARN(result, "SetPixelFormat failed (last err: 0x%08x)!", GetLastError() ); uint32_t flags = BGFX_CONFIG_DEBUG ? WGL_CONTEXT_DEBUG_BIT_ARB : 0; BX_UNUSED(flags); int32_t contextAttrs[9] = { #if BGFX_CONFIG_RENDERER_OPENGL >= 31 WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, WGL_CONTEXT_FLAGS_ARB, flags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, #else WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 1, 0, 0, 0, 0, #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31 0 }; m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs); if (NULL == m_context) { // nVidia doesn't like context profile mask for contexts below 3.2? contextAttrs[6] = WGL_CONTEXT_PROFILE_MASK_ARB == contextAttrs[6] ? 0 : contextAttrs[6]; m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs); } BGFX_FATAL(NULL != m_context, Fatal::UnableToInitialize, "Failed to create context 0x%08x.", GetLastError() ); }
void InitWGLStuff () { _glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)wglGetProcAddress((LPCSTR)"glActiveTextureARB"); _glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)wglGetProcAddress((LPCSTR)"glBlendFuncSeparate"); }
int main(int argc, char **argv) { int i; glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); for (i=1; i<argc; i++) { if(!strcmp("-noms", argv[i])) { glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); printf("forcing no multisampling\n"); } else if(!strcmp("-nomipmaps", argv[i])) { useMipmaps = 0; } else if(!strcmp("-nearest", argv[i])) { linearFiltering = 0; } } glutCreateWindow("point burst"); hasPointParameters = glutExtensionSupported("GL_SGIS_point_parameters") || glutExtensionSupported("GL_EXT_point_parameters"); if (hasPointParameters) { #if defined(_WIN32) && !defined(MESA) glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC) wglGetProcAddress("glPointParameterfEXT"); glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC) wglGetProcAddress("glPointParameterfvEXT"); if (!glPointParameterfEXT || !glPointParameterfvEXT) { hasPointParameters = 0; } #endif } if (hasPointParameters) { printf("has point parameters extension!\n"); } else { printf("does NOT have point parameters extension!\n"); } glutDisplayFunc(redraw); glutMouseFunc(mouse); glutMotionFunc(mouseMotion); glutVisibilityFunc(visible); glutKeyboardFunc(key); glutCreateMenu(menu); glutAddMenuEntry("Reset time", 0); glutAddMenuEntry("Constant", 1); glutAddMenuEntry("Linear", 2); glutAddMenuEntry("Quadratic", 3); glutAddMenuEntry("Blend on", 4); glutAddMenuEntry("Blend off", 5); glutAddMenuEntry("Threshold 1", 6); glutAddMenuEntry("Threshold 10", 7); glutAddMenuEntry("Point smooth on", 8); glutAddMenuEntry("Point smooth off", 9); glutAddMenuEntry("Point size 2", 10); glutAddMenuEntry("Point size 4", 11); glutAddMenuEntry("Point size 8", 12); glutAddMenuEntry("Point size 16", 18); glutAddMenuEntry("Toggle spin", 13); glutAddMenuEntry("200 points", 14); glutAddMenuEntry("500 points", 15); glutAddMenuEntry("1000 points", 16); glutAddMenuEntry("2000 points", 17); glutAddMenuEntry("Toggle texture", 19); glutAddMenuEntry("Quit", 666); glutAttachMenu(GLUT_RIGHT_BUTTON); glEnable(GL_DEPTH_TEST); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(8.0); #if GL_EXT_point_parameters if (hasPointParameters) { glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic); } #endif glMatrixMode(GL_PROJECTION); gluPerspective( /* field of view in degree */ 40.0, /* aspect ratio */ 1.0, /* Z near */ 0.5, /* Z far */ 40.0); glMatrixMode(GL_MODELVIEW); gluLookAt(0.0, 1.0, 8.0, /* eye location */ 0.0, 1.0, 0.0, /* center is at (0,0,0) */ 0.0, 1.0, 0.); /* up is in postivie Y direction */ glPushMatrix(); /* dummy push so we can pop on model recalc */ makePointList(); makeFloorTexture(); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
bool COpenGL::LoadShaderFunctions() { if(shaderFunctionsLoaded) return true; const char *extensions = (const char *) glGetString(GL_EXTENSIONS); if(extensions && strstr(extensions, "fragment_program")) { glCreateProgram = (PFNGLCREATEPROGRAMPROC) wglGetProcAddress ("glCreateProgram"); glCreateShader = (PFNGLCREATESHADERPROC) wglGetProcAddress ("glCreateShader"); glCompileShader = (PFNGLCOMPILESHADERPROC) wglGetProcAddress ("glCompileShader"); glDeleteShader = (PFNGLDELETESHADERPROC) wglGetProcAddress ("glDeleteShader"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC) wglGetProcAddress ("glDeleteProgram"); glAttachShader = (PFNGLATTACHSHADERPROC) wglGetProcAddress ("glAttachShader"); glDetachShader = (PFNGLDETACHSHADERPROC) wglGetProcAddress ("glDetachShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC) wglGetProcAddress ("glLinkProgram"); glUseProgram = (PFNGLUSEPROGRAMPROC) wglGetProcAddress ("glUseProgram"); glShaderSource = (PFNGLSHADERSOURCEPROC) wglGetProcAddress ("glShaderSource"); glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) wglGetProcAddress ("glGetUniformLocation"); glUniform2fv = (PFNGLUNIFORM2FVPROC) wglGetProcAddress ("glUniform2fv"); if(glCreateProgram && glCreateShader && glCompileShader && glDeleteShader && glDeleteProgram && glAttachShader && glDetachShader && glLinkProgram && glUseProgram && glShaderSource && glGetUniformLocation && glUniform2fv) { shaderFunctionsLoaded = true; } } return shaderFunctionsLoaded; }
GLFWglproc _glfwPlatformGetProcAddress(const char* procname) { return (GLFWglproc) wglGetProcAddress(procname); }
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); }
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 }
void* XdevLOpenGLWGL::getProcAddress(const xdl_char* func) { return (void*)wglGetProcAddress(func); }
void initGLExt() { glTexImage3D = (PFNGLTEXIMAGE3DPROC) wglGetProcAddress("glTexImage3D"); glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture"); }
// 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); }
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; }
static bool glew_dynamic_binding() { const char *gl_extensions = (const char*)glGetString(GL_EXTENSIONS); // If the current opengl driver doesn't have framebuffers methods, check if an extension exists if (glGenFramebuffers == nullptr) { log("OpenGL: glGenFramebuffers is nullptr, try to detect an extension"); if (strstr(gl_extensions, "ARB_framebuffer_object")) { log("OpenGL: ARB_framebuffer_object is supported"); glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC) wglGetProcAddress("glIsRenderbuffer"); glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) wglGetProcAddress("glBindRenderbuffer"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) wglGetProcAddress("glDeleteRenderbuffers"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) wglGetProcAddress("glGenRenderbuffers"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) wglGetProcAddress("glRenderbufferStorage"); glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC) wglGetProcAddress("glGetRenderbufferParameteriv"); glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC) wglGetProcAddress("glIsFramebuffer"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) wglGetProcAddress("glBindFramebuffer"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) wglGetProcAddress("glDeleteFramebuffers"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) wglGetProcAddress("glGenFramebuffers"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) wglGetProcAddress("glCheckFramebufferStatus"); glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC) wglGetProcAddress("glFramebufferTexture1D"); glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) wglGetProcAddress("glFramebufferTexture2D"); glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC) wglGetProcAddress("glFramebufferTexture3D"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) wglGetProcAddress("glFramebufferRenderbuffer"); glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) wglGetProcAddress("glGetFramebufferAttachmentParameteriv"); glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC) wglGetProcAddress("glGenerateMipmap"); } else if (strstr(gl_extensions, "EXT_framebuffer_object")) { log("OpenGL: EXT_framebuffer_object is supported"); glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC) wglGetProcAddress("glIsRenderbufferEXT"); glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) wglGetProcAddress("glBindRenderbufferEXT"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) wglGetProcAddress("glDeleteRenderbuffersEXT"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) wglGetProcAddress("glGenRenderbuffersEXT"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) wglGetProcAddress("glRenderbufferStorageEXT"); glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC) wglGetProcAddress("glGetRenderbufferParameterivEXT"); glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC) wglGetProcAddress("glIsFramebufferEXT"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) wglGetProcAddress("glBindFramebufferEXT"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) wglGetProcAddress("glDeleteFramebuffersEXT"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) wglGetProcAddress("glGenFramebuffersEXT"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) wglGetProcAddress("glCheckFramebufferStatusEXT"); glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC) wglGetProcAddress("glFramebufferTexture1DEXT"); glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) wglGetProcAddress("glFramebufferTexture2DEXT"); glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC) wglGetProcAddress("glFramebufferTexture3DEXT"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) wglGetProcAddress("glFramebufferRenderbufferEXT"); glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) wglGetProcAddress("glGetFramebufferAttachmentParameterivEXT"); glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC) wglGetProcAddress("glGenerateMipmapEXT"); } else { log("OpenGL: No framebuffers extension is supported"); log("OpenGL: Any call to Fbo will crash!"); return false; } } return true; }
glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)wglGetProcAddress("glCreateProgramObjectARB"); glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram"); glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader"); glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)wglGetProcAddress("glUseProgramObjectARB"); glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"); glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB"); glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"); glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB"); glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wglGetProcAddress("glBindAttribLocation"); glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB"); glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)wglGetProcAddress("glGetObjectParameterivARB"); glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)wglGetProcAddress("glAttachObjectARB"); glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader"); glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB"); glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"); glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)wglGetProcAddress("glLinkProgramARB"); glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wglGetProcAddress("glGetUniformLocation"); glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wglGetProcAddress("glGetAttribLocation"); glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"); glUniform1iARB = (PFNGLUNIFORM1IARBPROC)wglGetProcAddress("glUniform1iARB"); glUniform3f = (PFNGLUNIFORM3FPROC)wglGetProcAddress("glUniform3f"); glUniform3fARB = (PFNGLUNIFORM3FARBPROC)wglGetProcAddress("glUniform3fARB"); glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f"); glUniform4f = (PFNGLUNIFORM4FPROC)wglGetProcAddress("glUniform4f"); glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)wglGetProcAddress("glActiveTextureARB");
bool InitGLSL() { // This grabs a list of all the video card's extensions it supports char *szGLExtensions = (char*)glGetString(GL_EXTENSIONS); // Make sure find the GL_ARB_shader_objects extension so we can use shaders. if(!strstr(szGLExtensions, "GL_ARB_shader_objects")) { MessageBox(hWnd, "GL_ARB_shader_objects extension not supported!", "Error", MB_OK); return false; } // Make sure we support the GLSL shading language 1.0 if(!strstr(szGLExtensions, "GL_ARB_shading_language_100")) { MessageBox(hWnd, "GL_ARB_shading_language_100 extension not supported!", "Error", MB_OK); return false; } // Now let's set all of our function pointers for our extension functions glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB"); glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB"); glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB"); glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)wglGetProcAddress("glCreateProgramObjectARB"); glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)wglGetProcAddress("glAttachObjectARB"); glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)wglGetProcAddress("glLinkProgramARB"); glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)wglGetProcAddress("glUseProgramObjectARB"); glUniform1iARB = (PFNGLUNIFORM1IARBPROC)wglGetProcAddress("glUniform1iARB"); glUniform1fARB = (PFNGLUNIFORM1FARBPROC)wglGetProcAddress("glUniform1fARB"); glUniform2fARB = (PFNGLUNIFORM2FARBPROC)wglGetProcAddress("glUniform2fARB"); glUniform3fARB = (PFNGLUNIFORM3FARBPROC)wglGetProcAddress("glUniform3fARB"); glUniform4fARB = (PFNGLUNIFORM4FARBPROC)wglGetProcAddress("glUniform4fARB"); glGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)wglGetProcAddress("glGetUniformLocationARB"); glDetachObjectARB = (PFNGLDETACHOBJECTARBPROC)wglGetProcAddress("glDetachObjectARB"); glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)wglGetProcAddress("glDeleteObjectARB"); glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIV)wglGetProcAddress("glGetObjectParameterivARB"); glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB"); // Return a success! return true; }
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; }
void glInit() { initFont(); // create openGL functions for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]); // Create and link shader and stuff: // I will have to separate these to be able to use more than one shader... // TODO: I should make some sort of compiling and linking loop... // create noise Texture #ifdef FLOAT_TEXTURE for (int i = 0; i < NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * 4; i++) { noiseData[i] = frand() - 0.5f; } #else for (int i = 0; i < NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * 4; i++) { noiseData[i] = (unsigned char)rand(); } #endif // init objects: GLuint vMainObject = glCreateShader(GL_VERTEX_SHADER); GLuint fMainBackground = glCreateShader(GL_FRAGMENT_SHADER); GLuint fOffscreenCopy = glCreateShader(GL_FRAGMENT_SHADER); shaderPrograms[0] = glCreateProgram(); shaderPrograms[1] = glCreateProgram(); // compile sources: glShaderSource(vMainObject, 1, &vertexMainObject, NULL); glCompileShader(vMainObject); glShaderSource(fMainBackground, 1, &fragmentMainBackground, NULL); glCompileShader(fMainBackground); glShaderSource(fOffscreenCopy, 1, &fragmentOffscreenCopy, NULL); glCompileShader(fOffscreenCopy); // Check programs int tmp, tmp2; glGetShaderiv(vMainObject, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(vMainObject, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "vMainObject shader error", MB_OK); return; } glGetShaderiv(fMainBackground, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(fMainBackground, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "fMainBackground shader error", MB_OK); return; } glGetShaderiv(fOffscreenCopy, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(fOffscreenCopy, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "fOffscreeCopy shader error", MB_OK); return; } // link shaders: glAttachShader(shaderPrograms[0], vMainObject); glAttachShader(shaderPrograms[0], fMainBackground); glLinkProgram(shaderPrograms[0]); glAttachShader(shaderPrograms[1], vMainObject); glAttachShader(shaderPrograms[1], fOffscreenCopy); glLinkProgram(shaderPrograms[1]); // Create a rendertarget texture glGenTextures(1, &offscreenTexture); glBindTexture(GL_TEXTURE_2D, offscreenTexture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); #if 1 // RLE uncompress int pos = 0; for (int k = 0; k < numValues; k++) { for (int i = 0; i < fontLength[k]; i++) { fontCompressed[0][0][pos+fontLength[k]-i-1] = fontValues[k]; } pos += fontLength[k]; } // uncompress font for (int color = 0; color < 4; color++) { for (int y = 0; y < fontHeight; y++) { for (int x = 0; x < fontWidth; x++) { font[y][x][color] = fontCompressed[color][y][x]; } } } // Set texture. glEnable(GL_TEXTURE_3D); // automatic? glGenTextures(1, &noiseTexture); glBindTexture(GL_TEXTURE_3D, noiseTexture); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); #ifdef FLOAT_TEXTURE glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, 0, GL_RGBA, GL_FLOAT, noiseData); #else glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, noiseData); #endif // Load font texture glGenTextures(1, &fontTexture); glBindTexture(GL_TEXTURE_2D, fontTexture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // TODO: Mip Mapping!!!! glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering glEnable(GL_TEXTURE_2D); // Enable Texture Mapping gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA8, fontWidth, fontHeight, GL_BGRA, GL_UNSIGNED_BYTE, font); glDisable(GL_TEXTURE_2D); // Enable Texture Mapping #endif }
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; }
static void *OurGetProcAddress(vlc_gl_t *gl, const char *name) { VLC_UNUSED(gl); return wglGetProcAddress(name); }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // console for debugging //AllocConsole(); //freopen("CONOUT$","wb",stdout); WNDCLASSEX wc; HWND hwnd; MSG msg; // register window class wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = g_windowClass; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); unsigned int winWidth = WINDOW_WIDTH; unsigned int winHeight = WINDOW_HEIGHT; if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed", "Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // create window hwnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, g_windowClass, "Title Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, winWidth, winHeight, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(NULL, "Window Creation Failed", "Error", MB_ICONEXCLAMATION | MB_OK); return 0; } HDC hdc; if(!(hdc = GetDC(hwnd))) printf("GetDC failed\n"); //* old set pixel format // set pixel format PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // flags PFD_TYPE_RGBA, // rgba framebuffer 32, // 32 bit color depth 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 8, // 24 bit depth, 8 bit stencil 0, // # of aux buffers PFD_MAIN_PLANE, 0, 0, 0, 0 }; // get available matching pixel format int iPixelFormat; if(!(iPixelFormat = ChoosePixelFormat(hdc, &pfd))) printf("ChoosePixelFormat failed\n"); //*/ // assign pixel format to device context if(!(SetPixelFormat(hdc, iPixelFormat, &pfd))) printf("SetPixelFormat failed\n"); // create opengl context HGLRC context; if(!(context = wglCreateContext(hdc))) printf("wglCreateContext failed\n"); if(!(wglMakeCurrent(hdc, context))) printf("wglMakeCurrent failed\n"); // Now we want an updated pixel format and context //* PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if(!wglChoosePixelFormatARB) { printf("wgl choose pixel format not supported?\n"); } PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if(!wglCreateContextAttribsARB) printf("wglCreateContextAttribsARB undefined\n"); // using wglchoosepixelformat const int attribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0, }; int ePixelFormat; unsigned int numFormats; int valid = wglChoosePixelFormatARB(hdc, attribList, NULL, 1, &ePixelFormat, &numFormats); if (valid && numFormats >= 1) { // we have a valid format printf("we have a valid format\n"); } else { printf("wglchoosepixel format didn't find a valid format\n"); } // if we found a valid format, it is stored in ePixelFormat // delete old rendering context int delc = wglDeleteContext(context); if (!delc) printf("failed to delete old context\n"); // release device context ReleaseDC(hwnd, hdc); // destroy the window DestroyWindow(hwnd); while(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // get rid of the first destroy message so it doesn't screw up later int temp = GetMessage(&msg, NULL, 0, 0); if (temp != 0) { printf("whoops, something other than destroy was in message queue after destroywindow: (%i)\n", temp); } else { printf("disposed of the first destory message\n"); } } // now, make it all again hwnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, g_windowClass, "Title Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, winWidth, winHeight, NULL, NULL, hInstance, NULL); // get the new device context if(!(hdc = GetDC(hwnd))) printf("second GetDC failed\n"); // set the pixel format the the extended one we got earlier if (!SetPixelFormat(hdc, ePixelFormat, &pfd)) { // failed to set pixel format printf("failed to set extended pixel format\n"); } // create extended opengl rendering context int contextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if(!(context = wglCreateContextAttribsARB(hdc, NULL, contextAttribs))) printf("second wglCreateContext failed\n"); if(!(wglMakeCurrent(hdc, context))) printf("second wglMakeCurrent failed\n"); //*/ ShowWindow(hwnd, nCmdShow); SetForegroundWindow(hwnd); SetFocus(hwnd); UpdateWindow(hwnd); // set initial mouse position POINT p; if(GetCursorPos(&p)) { if (ScreenToClient(hwnd, &p)) { g_mouse_x = p.x; g_mouse_y = p.y; } else { printf("ScreenToClient failed\n"); } } else { printf("GetCursorPos failed\n"); } initGL(winWidth, winHeight); printf("finished init, starting main loop\n"); g_hwnd = hwnd; g_current_millis = currentMillis(); // main loop while(g_running) { while(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { int temp = GetMessage(&msg, NULL, 0, 0); if(temp > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } else { printf("getmessage returned nonpositive: (%i)\n", temp); g_running = false; break; } } long long current_millis = currentMillis(); //printf("current_millis is %i\n", current_millis); // wouldn't current_millis be bigger? float dt = g_current_millis - current_millis; g_current_millis = current_millis; // draw stuff renderGL(); update(dt); g_running &= !keys[frontKeyBuffer][VK_ESCAPE]; swapKeyBuffers(); SwapBuffers(hdc); } printf("quitting\n"); //FreeConsole(); // delete the rendering context wglMakeCurrent(NULL, NULL); wglDeleteContext(context); return msg.wParam; }