Esempio n. 1
0
/** 
    TODO: more parameters!
 */
static int
selectPixelFormat(HDC hDC, bool double_buffered)
{
    // Try to select a format that supports multisampling
    int pixelFormats[32];
    BOOL bStatus;
    UINT numFormats;
    float fAttributes[] = {0,0};
    int iAttributes[] = { 
        WGL_DRAW_TO_WINDOW_ARB,		GL_TRUE,
        WGL_SUPPORT_OPENGL_ARB,		GL_TRUE,
        WGL_ACCELERATION_ARB,		WGL_FULL_ACCELERATION_ARB,
        WGL_COLOR_BITS_ARB,			24,
        WGL_ALPHA_BITS_ARB,			8,
        WGL_DEPTH_BITS_ARB,			24,
        WGL_STENCIL_BITS_ARB,		0,
        WGL_DOUBLE_BUFFER_ARB,		double_buffered ? GL_TRUE : GL_FALSE,
        // Multisampling only works when double-buffering is enabled
        WGL_SAMPLE_BUFFERS_ARB,		double_buffered ? GL_TRUE : GL_FALSE,
        WGL_SAMPLES_ARB,			double_buffered ? 4 : 0,
        0, 0
    };
	// Multisampling ?
    if (iAttributes[17] == GL_TRUE) {
        // TODO: make sample count configurable
        for (unsigned samples = 4; samples > 0; samples -= 2) {
            iAttributes[19] = samples;
            bStatus = wglChoosePixelFormatARB(hDC, iAttributes, fAttributes,1, pixelFormats, &numFormats);
            if (bStatus == GL_TRUE && numFormats > 0) {
                return pixelFormats[0];
            }
        }
    }
    else {
        bStatus = wglChoosePixelFormatARB(hDC, iAttributes, fAttributes,1, pixelFormats, &numFormats);
        if (bStatus == GL_TRUE && numFormats > 0)
            return pixelFormats[0];
    }
    // Log a warning here
    OutputDebugString("selectPixelFormat(): wglChoosePixelFormatARB() failed, falling back to ChoosePixelFormat\n");

    // Fall back to standard method
    PIXELFORMATDESCRIPTOR pfd;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED
        | (double_buffered ? PFD_DOUBLEBUFFER : 0);
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 32;
    pfd.iLayerType = PFD_MAIN_PLANE;
    return ChoosePixelFormat(hDC, &pfd);
}
Esempio n. 2
0
/*
====================
GLW_ChoosePixelFormat

Returns -1 on failure, or a pixel format
====================
*/
static int GLW_ChoosePixelFormat( const HDC hdc, const int multisamples, const bool stereo3D ) {
#if !NGD_USE_OPENGL_ES_2_0
    FLOAT	fAttributes[] = { 0, 0 };
    int		iAttributes[] = {
        WGL_SAMPLE_BUFFERS_ARB, ( ( multisamples > 1 ) ? 1 : 0 ),
        WGL_SAMPLES_ARB, multisamples,
        WGL_DOUBLE_BUFFER_ARB, TRUE,
        WGL_STENCIL_BITS_ARB, 8,
        WGL_DEPTH_BITS_ARB, 24,
        WGL_RED_BITS_ARB, 8,
        WGL_BLUE_BITS_ARB, 8,
        WGL_GREEN_BITS_ARB, 8,
        WGL_ALPHA_BITS_ARB, 8,
        WGL_STEREO_ARB, ( stereo3D ? TRUE : FALSE ),
        0, 0
    };
#endif

    int	pixelFormat = -1;

#if !NGD_USE_OPENGL_ES_2_0
    UINT numFormats = -1;
    if ( !wglChoosePixelFormatARB( hdc, iAttributes, fAttributes, 1, &pixelFormat, &numFormats ) ) {
        return -1;
    }
#else
    NGD_MISSING_FUNCTIONALITY;
#endif // !NGD_USE_OPENGL_ES_2_0
    return pixelFormat;
}
Esempio n. 3
0
//----------------------------------------------------------------------------//
OpenGLWGLPBTextureTarget::OpenGLWGLPBTextureTarget(OpenGLRendererBase& owner) :
    OpenGLTextureTarget(owner),
    d_pixfmt(0),
    d_pbuffer(0),
    d_context(0),
    d_hdc(0),
    d_prevContext(0),
    d_prevDC(0)
{
    if (!WGLEW_ARB_pbuffer)
        CEGUI_THROW(RendererException("WGL_ARB_pbuffer extension is needed to "
            "use OpenGLWGLPBTextureTarget!"));

    HDC hdc = wglGetCurrentDC();

    uint fmtcnt;
    wglChoosePixelFormatARB(hdc, pbAttrs, 0, 1, &d_pixfmt, &fmtcnt);

    if (!fmtcnt)
        CEGUI_THROW(RendererException(
            "pbuff creation failure, no suitable pixel formats."));

    initialiseTexture();

    // set default size (and cause initialisation of the pbuffer)
    declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE));
}
Esempio n. 4
0
bool OglContext::createPBuffer(ms_uint32 width, ms_uint32 height)
{
  HPBUFFERARB hPBuffer = NULL;
  hPBufferDC = NULL;
  hPBufferRC = NULL;

  int pixelFormat;
  int valid = false;
  UINT numFormats = 0;
  float fAttributes[] = {0,0};
  int samples = MAX_MULTISAMPLE_SAMPLES;

  while ((!valid || numFormats == 0) && samples >= 0) {
    int iAttributes[] = {
      WGL_SAMPLES_ARB,samples,
      WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
      WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
      WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
      WGL_COLOR_BITS_ARB,24,
      WGL_ALPHA_BITS_ARB,8,
      WGL_DEPTH_BITS_ARB,16,
      WGL_STENCIL_BITS_ARB,0,
      WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
      WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
      0,0
    };

    valid = wglChoosePixelFormatARB(window,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
    if (!valid || numFormats == 0) samples -= 2;
  }

  if(numFormats == 0) {
    msSetError(MS_OGLERR, "P-buffer Error: Unable to find an acceptable pixel format.", "OglContext::createPBuffer()");
    return FALSE;
  }

  if (!(hPBuffer = wglCreatePbufferARB(window, pixelFormat, width, height, 0))) {
    msSetError(MS_OGLERR, "P-buffer Error: Unable to create P-buffer. glError: %d", "OglContext::createPBuffer()", glGetError());
    return FALSE;
  }
  if (!(hPBufferDC = wglGetPbufferDCARB(hPBuffer))) {
    msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
    return FALSE;
  }
  if (!(hPBufferRC = wglCreateContext(hPBufferDC))) {
    msSetError(MS_OGLERR, "P-buffer Error: Unable to get P-buffer DC. glError: %d", "OglContext::createPBuffer()", glGetError());
    return FALSE;
  }

  if (wglShareLists(sharingContext,hPBufferRC) == FALSE) {
    msSetError(MS_OGLERR, "P-buffer Error: Unable to share display lists. glError: %d", "OglContext::createPBuffer()", glGetError());
    return FALSE;
  }

  return TRUE;
}
Esempio n. 5
0
HRESULT InitContext()
{
	int iMajorVersion=3;
	int iMinorVersion=0;

	HDC hDC = GetDC(g_hWnd);

	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd,sizeof(pfd)); 

	bool bError=false;
	

	if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format)
	{
		const int iPixelFormatAttribList[] =
		{
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
			WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, 
			WGL_COLOR_BITS_ARB, 32,			       
			WGL_DEPTH_BITS_ARB, 24,             
			WGL_STENCIL_BITS_ARB, 8,
			0 // End of attributes list
		};
		int iContextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion,
			WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion,
			WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			0 // End of attributes list
		};

		int iPixelFormat, iNumFormats;
		wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats);
		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false; 

		hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs);
		// If everything went OK
		if(hRC) wglMakeCurrent(hDC, hRC);
		else bError = true;
	}
	else bError = true;
	
	if(bError)
	{
		// Generate error messages
		char sErrorMessage[255], sErrorTitle[255];
		sprintf(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion);
		sprintf(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion);
		MessageBoxA(g_hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION);
		return false;
	}
   return S_OK;
}
Esempio n. 6
0
bool               P3DGLMemoryContextPBuffer::Create
                                      (unsigned int        Width,
                                       unsigned int        Height,
                                       bool                NeedAlpha)
 {
  int              PixelFormat;
  UINT             FormatCount;
  HDC              CurrDeviceContext;

  CurrDeviceContext = wglGetCurrentDC();

  if (wglChoosePixelFormatARB( CurrDeviceContext,
                               NeedAlpha ? PBufferPixelFormatIntAttrsAlpha :
                                           PBufferPixelFormatIntAttrsNoAlpha,
                               NULL,
                               1,
                              &PixelFormat,
                              &FormatCount))
   {
    if (FormatCount == 0)
     {
      return(false);
     }
   }
  else
   {
    return(false);
   }

  PBufferHandle = wglCreatePbufferARB
                   (CurrDeviceContext,
                    PixelFormat, 
                    Width,
                    Height,
                    PBufferAttrs);

  if (PBufferHandle == NULL)
   {
    return(false);
   }

  PBufferDC = wglGetPbufferDCARB(PBufferHandle);
  GLContext = wglCreateContext(PBufferDC);

  if (MakeCurrent())
   {
    return(P3DGLExtInit());
   }
  else
   {
    return(false);
   }

  return(true);
 }
Esempio n. 7
0
static int ChoosePixelFormatARB(_THIS, const int *iAttribs, const FLOAT *fAttribs)
{
	HWND hwnd;
	HDC hdc;
	HGLRC hglrc;
	const char * (WINAPI *wglGetExtensionsStringARB)(HDC) = 0;
	const char *extensions;
	int pformat = 0;
	UINT matches = 0;

	hwnd = CreateWindow(SDL_Appname, SDL_Appname, WS_POPUP | WS_DISABLED,
	                    0, 0, 10, 10,
	                    NULL, NULL, SDL_Instance, NULL);
	WIN_FlushMessageQueue();

	hdc = GetDC(hwnd);

	SetPixelFormat(hdc, ChoosePixelFormat(hdc, &GL_pfd), &GL_pfd);

	hglrc = this->gl_data->wglCreateContext(hdc);
	if ( hglrc ) {
		this->gl_data->wglMakeCurrent(hdc, hglrc);
	}

	wglGetExtensionsStringARB = (const char * (WINAPI *)(HDC))
		this->gl_data->wglGetProcAddress("wglGetExtensionsStringARB");

	if( wglGetExtensionsStringARB ) {
		extensions = wglGetExtensionsStringARB(hdc);
	} else {
		extensions = NULL;
	}

	this->gl_data->WGL_ARB_pixel_format = 0;
	if( ExtensionSupported("WGL_ARB_pixel_format", extensions) ) {
		BOOL (WINAPI *wglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
		wglChoosePixelFormatARB =
			(BOOL (WINAPI *)(HDC, const int *, const FLOAT *, UINT, int *, UINT *))
			this->gl_data->wglGetProcAddress("wglChoosePixelFormatARB");
		if( wglChoosePixelFormatARB &&
		    wglChoosePixelFormatARB(hdc, iAttribs, fAttribs, 1, &pformat, &matches) && pformat ) {
			this->gl_data->WGL_ARB_pixel_format = 1;
		}
	}
	
	if ( hglrc ) {
		this->gl_data->wglMakeCurrent(NULL, NULL);
		this->gl_data->wglDeleteContext(hglrc);
	}
	ReleaseDC(hwnd, hdc);
	DestroyWindow(hwnd);
	WIN_FlushMessageQueue();

	return pformat;
}
	void WindowRendererSupportGLWin32::setPixelFormat(const DeviceContext* deviceContext, const PixelFormat& pixelFormat) const
	{
		HDC hdc = static_cast<const DeviceContextWin32*>(deviceContext)->getHDC();

		ushort colourBits = pixelFormat.getRedBits() + pixelFormat.getGreenBits() + pixelFormat.getBlueBits();
		ushort alphaBits = pixelFormat.getAlphaBits();
		ushort depthBits = 24;
		ushort stencilBits = 8;
		ushort samples = 4;

		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 = (BYTE)colourBits;
		pfd.cAlphaBits = (BYTE)alphaBits;
		pfd.cDepthBits = (BYTE)depthBits;
		pfd.cStencilBits = (BYTE)stencilBits;

		int format = 0;

		if(mHasMultisample)
		{
			vector<int> attribList;
			attribList.push_back(WGL_DRAW_TO_WINDOW_ARB);	attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_SUPPORT_OPENGL_ARB);	attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_DOUBLE_BUFFER_ARB);	attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_SAMPLE_BUFFERS_ARB);	attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_ACCELERATION_ARB);		attribList.push_back(WGL_FULL_ACCELERATION_ARB);
			attribList.push_back(WGL_COLOR_BITS_ARB);		attribList.push_back(colourBits);
			attribList.push_back(WGL_ALPHA_BITS_ARB);		attribList.push_back(alphaBits);
			attribList.push_back(WGL_DEPTH_BITS_ARB);		attribList.push_back(depthBits);
			attribList.push_back(WGL_STENCIL_BITS_ARB);		attribList.push_back(stencilBits);
			attribList.push_back(WGL_SAMPLES_ARB);			attribList.push_back(samples);

			if(mHasHardwareGamma)
			{
				attribList.push_back(WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT);	attribList.push_back(GL_TRUE);
			}

			attribList.push_back(0);

			UINT nformats;
			wglChoosePixelFormatARB(hdc, &(attribList[0]), nullptr, 1, &format, &nformats);
		}
		else
		{
			format = ChoosePixelFormat(hdc, &pfd);
		}

		SetPixelFormat(hdc, format, &pfd);
	}
Esempio n. 9
0
    void WindowGL3::setupDC()
    {
        if (!wglChoosePixelFormatARB || !wglCreateContextAttribsARB)
        {
            Window::setupDC();
            return;
        }

        int nPixCount = 0;
        int nPixelFormat  = -1;

        int pixAttribs[] = {
            WGL_SUPPORT_OPENGL_ARB, 1,
            WGL_DRAW_TO_WINDOW_ARB, 1,
            WGL_ACCELERATION_ARB, 1,
            WGL_RED_BITS_ARB, 8,
            WGL_GREEN_BITS_ARB, 8,
            WGL_BLUE_BITS_ARB, 8,
            WGL_DEPTH_BITS_ARB, 16,
            WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
            0 };

        wglChoosePixelFormatARB(mHDC, pixAttribs, NULL, 1, &nPixelFormat,
            (UINT*)&nPixCount);

        if (nPixelFormat == -1)
        {
            std::cerr << "wglChoosePixelFormatARB failed\n";
            mHDC = 0;
            return;
        }

        if (mSettings.profile == Context::GL32)
        {
            mSettings.context.vMajor = 3;
            mSettings.context.vMinor = 2;
        }

        GLint attribs[] = {
            WGL_CONTEXT_MAJOR_VERSION_ARB, mSettings.context.vMajor,
            WGL_CONTEXT_MINOR_VERSION_ARB, mSettings.context.vMinor,
            0 };

        mHGLRC = wglCreateContextAttribsARB(mHDC, 0, attribs);
        if (!mHGLRC)
        {
            std::cerr << "wglCreateContextAttribsARB failed\n";
            return;
        }
    }
Esempio n. 10
0
internal void
Win32SetPixelFormat(HDC WindowDC)
{
    int SuggestedPixelFormatIndex = 0;
    GLuint ExtendedPick           = 0;

    if(wglChoosePixelFormatARB)
    {
        int AttribList[] = {
            WGL_DRAW_TO_WINDOW_ARB,
            GL_TRUE,
            WGL_ACCELERATION_ARB,
            WGL_FULL_ACCELERATION_ARB,
            WGL_SUPPORT_OPENGL_ARB,
            GL_TRUE,
            WGL_DOUBLE_BUFFER_ARB,
            GL_TRUE,
            WGL_PIXEL_TYPE_ARB,
            WGL_TYPE_RGBA_ARB,
            WGL_SAMPLE_BUFFERS_ARB,
            GL_TRUE,
            WGL_SAMPLES_ARB,
            4,
            0,
        };

        wglChoosePixelFormatARB(WindowDC, AttribList, 0, 1, &SuggestedPixelFormatIndex, &ExtendedPick);
    }

    if(!ExtendedPick)
    {
        PIXELFORMATDESCRIPTOR DesiredPixelFormat = {0};
        DesiredPixelFormat.nSize                 = sizeof(PIXELFORMATDESCRIPTOR);
        DesiredPixelFormat.nVersion              = 1;
        DesiredPixelFormat.iPixelType            = PFD_TYPE_RGBA;
        DesiredPixelFormat.dwFlags               = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
        DesiredPixelFormat.cColorBits            = 32;
        DesiredPixelFormat.cAlphaBits            = 8;
        DesiredPixelFormat.iLayerType            = PFD_MAIN_PLANE;

        SuggestedPixelFormatIndex = ChoosePixelFormat(WindowDC, &DesiredPixelFormat);
    }

    PIXELFORMATDESCRIPTOR SuggestedPixelFormat;
    DescribePixelFormat(WindowDC, SuggestedPixelFormatIndex, sizeof(SuggestedPixelFormat), &SuggestedPixelFormat);
    SetPixelFormat(WindowDC, SuggestedPixelFormatIndex, &SuggestedPixelFormat);
}
Esempio n. 11
0
//рекурсивная функция, которая выбирает близайший возможный уровень мультисемплинга
int selectMaxMultisampleLevel(HDC hDC,GLint *iAttributes,int *multi_level)
{
	iAttributes[19] = *multi_level;
	float fAttributes[] = {0,0};
	int pixelFormat_;
	UINT numFormats;

	bool valid=wglChoosePixelFormatARB(hDC,iAttributes,fAttributes,1,&pixelFormat_,&numFormats);
	if (valid && numFormats>=1) 
		return pixelFormat_;
	if (*multi_level==1) 
		return -1;
	else
	{
		(*multi_level)/=2;
		return selectMaxMultisampleLevel(hDC,iAttributes,multi_level);
	}
}
Esempio n. 12
0
	void WGL_SetPixelFormat(HDC hDC, const RenderSystem::Config & config)
	{
		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 = config.colorBits;
		pfd.cAlphaBits = config.alphaBits; 
		pfd.cDepthBits = config.depthBits;
		pfd.cStencilBits = config.stencilBits;

		int PixelFormat = 0;
		{
			int iAttributes[] = {
				WGL_DRAW_TO_WINDOW_ARB,		GL_TRUE,
				WGL_SUPPORT_OPENGL_ARB,		GL_TRUE,
				WGL_ACCELERATION_ARB,		WGL_FULL_ACCELERATION_ARB,
				WGL_COLOR_BITS_ARB,			config.colorBits,
				WGL_ALPHA_BITS_ARB,			config.alphaBits,
				WGL_DEPTH_BITS_ARB,			config.depthBits,
				WGL_STENCIL_BITS_ARB,		config.stencilBits,
				WGL_DOUBLE_BUFFER_ARB,		GL_TRUE,
				WGL_SAMPLE_BUFFERS_ARB,		config.msaa ? GL_TRUE : GL_FALSE,
				WGL_SAMPLES_ARB,			4,
				0,							0
			};

			float fAttributes[] = {
				0, 0
			};

			UINT numFormats = 0;

			if (WGLEW_GET_FUN(__wglewChoosePixelFormatARB) != NULL)
				wglChoosePixelFormatARB(hDC, iAttributes, fAttributes, 1, &PixelFormat, &numFormats);

			if (numFormats == 0)
				PixelFormat = ChoosePixelFormat(hDC, &pfd);
		}

		SetPixelFormat(hDC, PixelFormat, &pfd);
	}
Esempio n. 13
0
/* Creates the real pixel format for the target window */
static int gl_choose_pixel_format(HDC hdc, struct gs_init_data *info)
{
	struct darray attribs;
	int color_bits   = get_color_format_bits(info->format);
	int depth_bits   = get_depth_format_bits(info->zsformat);
	int stencil_bits = get_stencil_format_bits(info->zsformat);
	UINT num_formats;
	BOOL success;
	int format;

	if (!color_bits) {
		blog(LOG_ERROR, "gl_init_pixel_format: color format not "
		                "supported");
		return false;
	}

	darray_init(&attribs);
	add_attrib(&attribs, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE);
	add_attrib(&attribs, WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
	add_attrib(&attribs, WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB);
	add_attrib(&attribs, WGL_DOUBLE_BUFFER_ARB,  GL_TRUE);
	add_attrib(&attribs, WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB);
	add_attrib(&attribs, WGL_COLOR_BITS_ARB,     color_bits);
	add_attrib(&attribs, WGL_DEPTH_BITS_ARB,     depth_bits);
	add_attrib(&attribs, WGL_STENCIL_BITS_ARB,   stencil_bits);
	add_attrib(&attribs, 0, 0);

	success = wglChoosePixelFormatARB(hdc, attribs.array, NULL, 1, &format,
				&num_formats);
	if (!success || !num_formats) {
		blog(LOG_ERROR, "wglChoosePixelFormatARB failed, %u",
				GetLastError());
		format = 0;
	}

	darray_free(&attribs);

	return format;
}
Esempio n. 14
0
///////////////////////////////////////////////////////////////////////////////
// Setup the actual window and related state.
// Create the window, find a pixel format, create the OpenGL context
bool SetupWindow(int nWidth, int nHeight)
{
    bool bRetVal = true;

    int nWindowX = 0;
    int nWindowY = 0;
    int nPixelFormat  = -1;
    PIXELFORMATDESCRIPTOR pfd;

    DWORD dwExtStyle;
    DWORD dwWindStyle;

    HINSTANCE g_hInstance = GetModuleHandle(NULL);

    TCHAR szWindowName[50] =  TEXT("Block Redux");
    TCHAR szClassName[50]  =  TEXT("OGL_CLASS");

    // setup window class
    g_windClass.lpszClassName = szClassName;                // Set the name of the Class
    g_windClass.lpfnWndProc   = (WNDPROC)WndProc;
    g_windClass.hInstance     = g_hInstance;                // Use this module for the module handle
    g_windClass.hCursor       = LoadCursor(NULL, IDC_ARROW);// Pick the default mouse cursor
    g_windClass.hIcon         = LoadIcon(NULL, IDI_WINLOGO);// Pick the default windows icons
    g_windClass.hbrBackground = NULL;                       // No Background
    g_windClass.lpszMenuName  = NULL;                       // No menu for this window
    g_windClass.style         = CS_HREDRAW | CS_OWNDC |     // set styles for this class, specifically to catch
                                CS_VREDRAW;                 // window redraws, unique DC, and resize
    g_windClass.cbClsExtra    = 0;                          // Extra class memory
    g_windClass.cbWndExtra    = 0;                          // Extra window memory

    // Register the newly defined class
    if(!RegisterClass( &g_windClass ))
        bRetVal = false;

    dwExtStyle  = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
    dwWindStyle = WS_OVERLAPPEDWINDOW;
    ShowCursor(TRUE);

    g_windowRect.left   = nWindowX;
    g_windowRect.right  = nWindowX + nWidth;
    g_windowRect.top    = nWindowY;
    g_windowRect.bottom = nWindowY + nHeight;

    // Setup window width and height
    AdjustWindowRectEx(&g_windowRect, dwWindStyle, FALSE, dwExtStyle);

    //Adjust for adornments
    int nWindowWidth = g_windowRect.right   - g_windowRect.left;
    int nWindowHeight = g_windowRect.bottom - g_windowRect.top;

    // Create window
    g_hWnd = CreateWindowEx(dwExtStyle,     // Extended style
                            szClassName,    // class name
                            szWindowName,   // window name
                            dwWindStyle |        
                            WS_CLIPSIBLINGS | 
                            WS_CLIPCHILDREN,// window stlye
                            nWindowX,       // window position, x
                            nWindowY,       // window position, y
                            nWindowWidth,   // height
                            nWindowHeight,  // width
                            NULL,           // Parent window
                            NULL,           // menu
                            g_hInstance,    // instance
                            NULL);          // pass this to WM_CREATE

    // now that we have a window, setup the pixel format descriptor
    g_hDC = GetDC(g_hWnd);

    // Set a dummy pixel format so that we can get access to wgl functions
    SetPixelFormat( g_hDC, 1,&pfd);
    // Create OGL context and make it current
    g_hRC = wglCreateContext( g_hDC );
    wglMakeCurrent( g_hDC, g_hRC );

    if (g_hDC == 0 ||
        g_hDC == 0)
    {
        bRetVal = false;
        printf("!!! An error occured creating an OpenGL window.\n");
    }

    // Setup GLEW which loads OGL function pointers
    GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		/* Problem: glewInit failed, something is seriously wrong. */
        bRetVal = false;
		printf("Error: %s\n", glewGetErrorString(err));
	}
    const GLubyte *oglVersion = glGetString(GL_VERSION);
    printf("This system supports OpenGL Version %s.\n", oglVersion);

    // Now that extensions are setup, delete window and start over picking a real format.
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(g_hRC);
    ReleaseDC(g_hWnd, g_hDC);
    DestroyWindow(g_hWnd);

    // Create the window again
    g_hWnd = CreateWindowEx(dwExtStyle,     // Extended style
                            szClassName,    // class name
                            szWindowName,   // window name
                            dwWindStyle |        
                            WS_CLIPSIBLINGS | 
                            WS_CLIPCHILDREN,// window stlye
                            nWindowX,       // window position, x
                            nWindowY,       // window position, y
                            nWindowWidth,   // height
                            nWindowHeight,  // width
                            NULL,           // Parent window
                            NULL,           // menu
                            g_hInstance,    // instance
                            NULL);          // pass this to WM_CREATE

    g_hDC = GetDC(g_hWnd);

    int nPixCount = 0;

    // Specify the important attributes we care about
    int pixAttribs[] = { WGL_SUPPORT_OPENGL_ARB, 1, // Must support OGL rendering
                         WGL_DRAW_TO_WINDOW_ARB, 1, // pf that can run a window
                         WGL_ACCELERATION_ARB,   1, // must be HW accelerated
                         WGL_RED_BITS_ARB,       8, // 8 bits of red precision in window
                         WGL_GREEN_BITS_ARB,     8, // 8 bits of green precision in window
                         WGL_BLUE_BITS_ARB,      8, // 8 bits of blue precision in window
                         WGL_DEPTH_BITS_ARB,     16, // 16 bits of depth precision for window
                         WGL_PIXEL_TYPE_ARB,      WGL_TYPE_RGBA_ARB, // pf should be RGBA type
                         0}; // NULL termination

    // Ask OpenGL to find the most relevant format matching our attribs
    // Only get one format back.
    wglChoosePixelFormatARB(g_hDC, &pixAttribs[0], NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

    if(nPixelFormat == -1) 
    {
        // Couldn't find a format, perhaps no 3D HW or drivers are installed
        g_hDC = 0;
        g_hDC = 0;
        bRetVal = false;
        printf("!!! An error occurred trying to find a pixel format with the requested attribs.\n");
    }
    else
    {
        // Got a format, now set it as the current one
        SetPixelFormat( g_hDC, nPixelFormat, &pfd );

        GLint attribs[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,  3,
	                       WGL_CONTEXT_MINOR_VERSION_ARB,  3,
                           0 };
        
        g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
        if (g_hRC == NULL)
        {
            printf("!!! Could not create an OpenGL 3.3 context.\n");
            attribs[3] = 2;
            g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
            if (g_hRC == NULL)
            {
                printf("!!! Could not create an OpenGL 3.2 context.\n");
                attribs[3] = 1;
                g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
                if (g_hRC == NULL)
                {
                    printf("!!! Could not create an OpenGL 3.1 context.\n");
                    attribs[3] = 0;
                    g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
                    if (g_hRC == NULL)
                    {
                        printf("!!! Could not create an OpenGL 3.0 context.\n");
                        printf("!!! OpenGL 3.0 and higher are not supported on this system.\n");
                    }
                }
            }
        }

        wglMakeCurrent( g_hDC, g_hRC );
    }

    if (g_hDC == 0 ||
        g_hDC == 0)
    {
        bRetVal = false;
        printf("!!! An error occured creating an OpenGL window.\n");
    }

    // If everything went as planned, display the window 
    if( bRetVal )
    {
        ShowWindow( g_hWnd, SW_SHOW );
        SetForegroundWindow( g_hWnd );
        SetFocus( g_hWnd );
        g_ContinueRendering = true;
    }
    
    return bRetVal;
}
Esempio n. 15
0
bool CWin32Workspace::CreateBestPixelFormat(PIXELFORMATDESCRIPTOR & pfd)
{
// Creating the Dummy window (test FSAA)
	HWND DummyHwnd = NULL;
	HDC DummyHdc = NULL;
	GLuint TestFormat = 0;
	char szDummyClass[MAX_LOADSTRING];
	LoadString(mModuleHandle, IDS_DUMMYCLASS, szDummyClass, MAX_LOADSTRING);

	DummyHwnd = CreateWindowEx(NULL, szDummyClass, "Dummy", WS_OVERLAPPEDWINDOW,
		0, 0, 100, 100, NULL, NULL, mModuleHandle, NULL);
	if(!DummyHwnd)
		NOVA_EXP("CWin32Workspace::CreateBestPixelFormat - Can not create dummy window(", BAD_OPERATION);

	DummyHdc = GetDC(DummyHwnd);
	if(!DummyHdc)
		NOVA_EXP("CWin32Workspace::CreateBestPixelFormat - Can not get HDC from dummy window!", BAD_OPERATION);

	CWGLContext DummyContext(DummyHdc);

	TestFormat = ChoosePixelFormat(DummyHdc, &pfd);
	DummyContext.CreateRenderContext(&pfd, TestFormat);

	DummyContext.SetCurrent();

// Starting wgl
	if(!mSupport->GetState())
	{
		dynamic_cast<CWGLSupport *>(mSupport)->InitGLExtentions();
		dynamic_cast<CWGLSupport *>(mSupport)->InitWGLExtensions(DummyContext.GetDeviceContext());
	}

// Setting multisumple options 
	if(mMetrics.FSAA > 1)
	{
		nstring e1("WGL_ARB_multisample"), e2("WGL_ARB_pixel_format"), e3("WGL_EXT_framebuffer_sRGB");
		if(mSupport->CheckExtention(e1) && mSupport->CheckExtention(e2))
		{
			bool useHwGamma = false;
			// Use WGL to test extended caps (multisample, sRGB)
			stl<int>::vector attribList;
			attribList.push_back(WGL_DRAW_TO_WINDOW_ARB); attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_SUPPORT_OPENGL_ARB); attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_DOUBLE_BUFFER_ARB); attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_SAMPLE_BUFFERS_ARB); attribList.push_back(GL_TRUE);
			attribList.push_back(WGL_ACCELERATION_ARB); attribList.push_back(WGL_FULL_ACCELERATION_ARB);
			attribList.push_back(WGL_COLOR_BITS_ARB); attribList.push_back(pfd.cColorBits);
			attribList.push_back(WGL_ALPHA_BITS_ARB); attribList.push_back(pfd.cAlphaBits);
			attribList.push_back(WGL_DEPTH_BITS_ARB); attribList.push_back(24);
			attribList.push_back(WGL_STENCIL_BITS_ARB); attribList.push_back(8);
			attribList.push_back(WGL_SAMPLES_ARB); attribList.push_back(mMetrics.FSAA);
			if (useHwGamma && mSupport->CheckExtention(e3))
			{
				attribList.push_back(WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT); attribList.push_back(GL_TRUE);
			}
			// terminator
			attribList.push_back(0);

			GLuint numformats;
			GLint format;
			int valid = wglChoosePixelFormatARB(DummyContext.GetDeviceContext(), &(attribList[0]),
				NULL, 1, &format, &numformats);

			if(valid && numformats > 0)
			{
				mBestPixelFormat = format;
				mBestFormatFinded = true;

				nstring str("Find compatible best pixel format: 0x");
				str.append(CStringUtils::IntTo16xString(mBestPixelFormat));
				LOG_MESSAGE(str);
			}
			else
			{
				mBestPixelFormat = TestFormat;
				mBestFormatFinded = false;
				
				nstring str("CWin32Workspace::CreateBestPixelFormat: Can not find compatible best pixel format,\n using simple format.. 0x");
				str.append(CStringUtils::IntTo16xString(mBestPixelFormat));
				LOG_MESSAGE(str);
			}
		}
		else
		{
			mBestPixelFormat = TestFormat;
			mBestFormatFinded = false;

			nstring str("CWin32Workspace::CreateBestPixelFormat: Can not find compatible best pixel format\n (extention WGL_ARB_multisample not supported) using simple format.. 0x");
			str.append(CStringUtils::IntTo16xString(mBestPixelFormat));
			LOG_MESSAGE(str);
		}

	}
	else
		mBestPixelFormat = TestFormat;

	DummyContext.EndCurrent();
	DummyContext.DestroyThisContext();

	ReleaseDC(DummyHwnd, DummyContext.GetDeviceContext());
	DestroyWindow(DummyHwnd);
	DummyHwnd = NULL;

	return true;
}
Esempio n. 16
0
// this is a wrapper around wglChoosePixelFormatARB(): returns the pixel format
// index matching the given attributes on success or 0 on failure
static int ChoosePixelFormatARB(HDC hdc, const int *attribList)
{
    if ( !wxGLCanvas::IsExtensionSupported("WGL_ARB_multisample") )
        return 0;

    typedef BOOL (WINAPI * wglChoosePixelFormatARB_t)
                 (HDC hdc,
                  const int *piAttribIList,
                  const FLOAT *pfAttribFList,
                  UINT nMaxFormats,
                  int *piFormats,
                  UINT *nNumFormats
                 );

    wxDEFINE_WGL_FUNC(wglChoosePixelFormatARB);
    if ( !wglChoosePixelFormatARB )
        return 0; // should not occur if extension is supported

    int iAttributes[128];
    int dst = 0; // index in iAttributes array

    #define ADD_ATTR(attr, value) \
        iAttributes[dst++] = attr; iAttributes[dst++] = value

    ADD_ATTR( WGL_DRAW_TO_WINDOW_ARB,    GL_TRUE );
    ADD_ATTR( WGL_SUPPORT_OPENGL_ARB,    GL_TRUE );
    ADD_ATTR( WGL_ACCELERATION_ARB,      WGL_FULL_ACCELERATION_ARB );

    if ( !attribList )
    {
        ADD_ATTR( WGL_COLOR_BITS_ARB,          24 );
        ADD_ATTR( WGL_ALPHA_BITS_ARB,           8 );
        ADD_ATTR( WGL_DEPTH_BITS_ARB,          16 );
        ADD_ATTR( WGL_STENCIL_BITS_ARB,         0 );
        ADD_ATTR( WGL_DOUBLE_BUFFER_ARB,  GL_TRUE );
        ADD_ATTR( WGL_SAMPLE_BUFFERS_ARB, GL_TRUE );
        ADD_ATTR( WGL_SAMPLES_ARB,              4 );
    }
    else // have custom attributes
    {
        #define ADD_ATTR_VALUE(attr) ADD_ATTR(attr, attribList[src++])

        int src = 0;
        while ( attribList[src] )
        {
            switch ( attribList[src++] )
            {
                case WX_GL_RGBA:
                    ADD_ATTR( WGL_COLOR_BITS_ARB, 24 );
                    ADD_ATTR( WGL_ALPHA_BITS_ARB,  8 );
                    break;

                case WX_GL_BUFFER_SIZE:
                    ADD_ATTR_VALUE( WGL_COLOR_BITS_ARB);
                    break;

                case WX_GL_LEVEL:
                    if ( attribList[src] > 0 )
                    {
                        ADD_ATTR( WGL_NUMBER_OVERLAYS_ARB, 1 );
                    }
                    else if ( attribList[src] <0 )
                    {
                        ADD_ATTR( WGL_NUMBER_UNDERLAYS_ARB, 1 );
                    }
                    //else: ignore it

                    src++; // skip the value in any case
                    break;

                case WX_GL_DOUBLEBUFFER:
                    ADD_ATTR( WGL_DOUBLE_BUFFER_ARB, GL_TRUE );
                    break;

                case WX_GL_STEREO:
                    ADD_ATTR( WGL_STEREO_ARB, GL_TRUE );
                    break;

                case WX_GL_AUX_BUFFERS:
                    ADD_ATTR_VALUE( WGL_AUX_BUFFERS_ARB );
                    break;

                case WX_GL_MIN_RED:
                    ADD_ATTR_VALUE( WGL_RED_BITS_ARB );
                    break;

                case WX_GL_MIN_GREEN:
                    ADD_ATTR_VALUE( WGL_GREEN_BITS_ARB );
                    break;

                case WX_GL_MIN_BLUE:
                    ADD_ATTR_VALUE( WGL_BLUE_BITS_ARB );
                    break;

                case WX_GL_MIN_ALPHA:
                    ADD_ATTR_VALUE( WGL_ALPHA_BITS_ARB );
                   break;

                case WX_GL_DEPTH_SIZE:
                    ADD_ATTR_VALUE( WGL_DEPTH_BITS_ARB );
                    break;

                case WX_GL_STENCIL_SIZE:
                    ADD_ATTR_VALUE( WGL_STENCIL_BITS_ARB );
                    break;

               case WX_GL_MIN_ACCUM_RED:
                    ADD_ATTR_VALUE( WGL_ACCUM_RED_BITS_ARB );
                    break;

                case WX_GL_MIN_ACCUM_GREEN:
                    ADD_ATTR_VALUE( WGL_ACCUM_GREEN_BITS_ARB );
                    break;

                case WX_GL_MIN_ACCUM_BLUE:
                    ADD_ATTR_VALUE( WGL_ACCUM_BLUE_BITS_ARB );
                    break;

                case WX_GL_MIN_ACCUM_ALPHA:
                    ADD_ATTR_VALUE( WGL_ACCUM_ALPHA_BITS_ARB );
                    break;

                case WX_GL_SAMPLE_BUFFERS:
                    ADD_ATTR_VALUE( WGL_SAMPLE_BUFFERS_ARB );
                    break;

                case WX_GL_SAMPLES:
                    ADD_ATTR_VALUE( WGL_SAMPLES_ARB );
                    break;
            }
        }

        #undef ADD_ATTR_VALUE
    }

    #undef ADD_ATTR

    iAttributes[dst++] = 0;

    int pf;
    UINT numFormats = 0;
    if ( !wglChoosePixelFormatARB(hdc, iAttributes, NULL, 1, &pf, &numFormats) )
    {
        wxLogLastError(_T("wglChoosePixelFormatARB"));
        return 0;
    }

    return pf;
}
Esempio n. 17
0
int glwtInitWGL(const GLWTConfig *config)
{
    UINT num_formats;
    int pixel_attribs[] = {
        WGL_RED_BITS_ARB, config ? config->red_bits : 0,
        WGL_GREEN_BITS_ARB, config ? config->green_bits : 0,
        WGL_BLUE_BITS_ARB, config ? config->blue_bits : 0,
        WGL_ALPHA_BITS_ARB, config ? config->alpha_bits : 0,
        WGL_DEPTH_BITS_ARB, config ? config->depth_bits : 0,
        WGL_STENCIL_BITS_ARB, config ? config->stencil_bits : 0,
        WGL_SAMPLES_ARB, config ? config->samples : 0,
        WGL_SAMPLE_BUFFERS_ARB, config ? config->sample_buffers : 0,
        WGL_SUPPORT_OPENGL_ARB, 1,
        WGL_DOUBLE_BUFFER_ARB, 1,
        WGL_DRAW_TO_WINDOW_ARB, 1,
        0, 0
    };

    HGLRC old_context = 0, temp_context = 0;
    HDC old_hdc = 0;

    glwt.api = config ? config->api : GLWT_API_ANY;
    glwt.api_version_major = config ? config->api_version_major : 0;
    glwt.api_version_minor = config ? config->api_version_minor : 0;

    old_context = wglGetCurrentContext();
    old_hdc = wglGetCurrentDC();

    temp_context = wglCreateContext(glwt.win32.dummy_hdc);
    if(!temp_context)
    {
        glwtWin32Error("wglCreateContext failed");
        goto error;
    }

    if(!wglMakeCurrent(glwt.win32.dummy_hdc, temp_context))
    {
        glwtWin32Error("wglMakeCurrent failed");
        goto error;
    }

    if(glxwInitWGL() != 0)
        goto error;

    // Required: WGL_ARB_extensions_string, WGL_ARB_pixel_format, WGL_ARB_multisample, WGL_ARB_make_current_read, WGL_EXT_swap_control

    if(!wglChoosePixelFormatARB(glwt.win32.dummy_hdc, pixel_attribs, NULL, 1, &glwt.wgl.pixel_format, &num_formats) ||
        num_formats == 0)
    {
        glwtWin32Error("wglChoosePixelFormatARB failed");
        goto error;
    }

    wglMakeCurrent(old_hdc, old_context);
    wglDeleteContext(temp_context);

    return 0;
error:

    wglMakeCurrent(old_hdc, old_context);
    if(temp_context)
        wglDeleteContext(temp_context);

    glwtQuitWGL();
    return -1;
}
    bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
    {
        makeActive();

        PIXELFORMATDESCRIPTOR pfd;
        initialisePixelFormatDescriptor (pfd, pixelFormat);

        int format = 0;

        if (wglChoosePixelFormatARB != nullptr)
        {
            int atts[64];
            int n = 0;

            atts[n++] = WGL_DRAW_TO_WINDOW_ARB;   atts[n++] = GL_TRUE;
            atts[n++] = WGL_SUPPORT_OPENGL_ARB;   atts[n++] = GL_TRUE;
            atts[n++] = WGL_DOUBLE_BUFFER_ARB;    atts[n++] = GL_TRUE;
            atts[n++] = WGL_PIXEL_TYPE_ARB;       atts[n++] = WGL_TYPE_RGBA_ARB;

            atts[n++] = WGL_COLOR_BITS_ARB;  atts[n++] = pfd.cColorBits;
            atts[n++] = WGL_RED_BITS_ARB;    atts[n++] = pixelFormat.redBits;
            atts[n++] = WGL_GREEN_BITS_ARB;  atts[n++] = pixelFormat.greenBits;
            atts[n++] = WGL_BLUE_BITS_ARB;   atts[n++] = pixelFormat.blueBits;
            atts[n++] = WGL_ALPHA_BITS_ARB;  atts[n++] = pixelFormat.alphaBits;
            atts[n++] = WGL_DEPTH_BITS_ARB;  atts[n++] = pixelFormat.depthBufferBits;

            atts[n++] = WGL_STENCIL_BITS_ARB;       atts[n++] = pixelFormat.stencilBufferBits;
            atts[n++] = WGL_ACCUM_RED_BITS_ARB;     atts[n++] = pixelFormat.accumulationBufferRedBits;
            atts[n++] = WGL_ACCUM_GREEN_BITS_ARB;   atts[n++] = pixelFormat.accumulationBufferGreenBits;
            atts[n++] = WGL_ACCUM_BLUE_BITS_ARB;    atts[n++] = pixelFormat.accumulationBufferBlueBits;
            atts[n++] = WGL_ACCUM_ALPHA_BITS_ARB;   atts[n++] = pixelFormat.accumulationBufferAlphaBits;

            if (pixelFormat.multisamplingLevel > 0
                  && OpenGLHelpers::isExtensionSupported ("GL_ARB_multisample"))
            {
                atts[n++] = WGL_SAMPLE_BUFFERS_ARB;
                atts[n++] = 1;
                atts[n++] = WGL_SAMPLES_ARB;
                atts[n++] = pixelFormat.multisamplingLevel;
            }

            atts[n++] = 0;
            jassert (n <= numElementsInArray (atts));

            UINT formatsCount = 0;
            wglChoosePixelFormatARB (dc, atts, nullptr, 1, &format, &formatsCount);
        }

        if (format == 0)
            format = ChoosePixelFormat (dc, &pfd);

        if (format != 0)
        {
            makeInactive();

            // win32 can't change the pixel format of a window, so need to delete the
            // old one and create a new one..
            jassert (nativeWindow != 0);
            ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
            nativeWindow = nullptr;

            createNativeWindow();

            if (SetPixelFormat (dc, format, &pfd))
            {
                wglDeleteContext (renderContext);
                renderContext = wglCreateContext (dc);

                jassert (renderContext != 0);
                return renderContext != 0;
            }
        }

        return false;
    }
	void Win32PBuffer::createPBuffer() 
	{

        // Process format
        int bits=0;
        bool isFloat=false;
#if 0
		bool hasAlpha=true;
#endif
        switch(mFormat)
        {
            case PCT_BYTE:
                bits=8; isFloat=false;
                break;
            case PCT_SHORT:
                bits=16; isFloat=false;
                break;
            case PCT_FLOAT16:
                bits=16; isFloat=true;
                break;
            case PCT_FLOAT32:
                bits=32; isFloat=true;
                break;
            default: break;
        };
		LogManager::getSingleton().logMessage(
			" Win32PBuffer::Creating PBuffer of format bits="+
			StringConverter::toString(bits)+
			" float="+StringConverter::toString(isFloat)
	    );


		HDC old_hdc = wglGetCurrentDC();
		HGLRC old_context = wglGetCurrentContext();

		// Bind to RGB or RGBA texture
		int bttype = 0;
#if 0
		if(mUseBind)
		{
			// Only provide bind type when actually binding
			bttype = PixelUtil::hasAlpha(mInternalFormat)?
				WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB;
		}
		int texformat = hasAlpha?
			WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB;
#endif
		// Make a float buffer?
        int pixeltype = isFloat?
			WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB;
		
		int attrib[] = {
			WGL_RED_BITS_ARB,bits,
			WGL_GREEN_BITS_ARB,bits,
			WGL_BLUE_BITS_ARB,bits,
			WGL_ALPHA_BITS_ARB,bits,
			WGL_STENCIL_BITS_ARB,1,
			WGL_DEPTH_BITS_ARB,15,
			WGL_DRAW_TO_PBUFFER_ARB,true,
			WGL_SUPPORT_OPENGL_ARB,true,
			WGL_PIXEL_TYPE_ARB,pixeltype,
			//WGL_DOUBLE_BUFFER_ARB,true,
			//WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Make sure it is accelerated
			bttype,true, // must be last, as bttype can be zero
			0
		};
		int pattrib_default[] = { 
			0
		};
#if 0
		int pattrib_bind[] = { 
			WGL_TEXTURE_FORMAT_ARB, texformat, 
			WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,
			WGL_PBUFFER_LARGEST_ARB, true,
			0 
		};
#endif
		int format;
		unsigned int count;

		// Choose suitable pixel format
		wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count);
		if(count == 0)
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglChoosePixelFormatARB() failed", " Win32PBuffer::createPBuffer");

		// Analyse pixel format
		const int piAttributes[]={
				WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB,
				WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB
		};
		int piValues[sizeof(piAttributes)/sizeof(const int)];
		wglGetPixelFormatAttribivARB(old_hdc,format,0,sizeof(piAttributes)/sizeof(const int),piAttributes,piValues);

        LogManager::getSingleton().stream()
			<< " Win32PBuffer::PBuffer -- Chosen pixel format rgba="
            << piValues[0] << ","  
            << piValues[1] << ","  
            << piValues[2] << ","  
            << piValues[3] 
            << " depth=" << piValues[4]
            << " stencil=" << piValues[5];

		mPBuffer = wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default);
		if(!mPBuffer)
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreatePbufferARB() failed", " Win32PBuffer::createPBuffer");

		mHDC = wglGetPbufferDCARB(mPBuffer);
		if(!mHDC) {
			wglDestroyPbufferARB(mPBuffer);
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglGetPbufferDCARB() failed", " Win32PBuffer::createPBuffer");
		}
			
		mGlrc = wglCreateContext(mHDC);
		if(!mGlrc) {
			wglReleasePbufferDCARB(mPBuffer,mHDC);
			wglDestroyPbufferARB(mPBuffer);
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext() failed", " Win32PBuffer::createPBuffer");
		}

		if(!wglShareLists(old_context,mGlrc)) {
			wglDeleteContext(mGlrc);
			wglReleasePbufferDCARB(mPBuffer,mHDC);
			wglDestroyPbufferARB(mPBuffer);
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32PBuffer::createPBuffer");
		}
				
		// Query real width and height
		int iWidth, iHeight;
		wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth);
		wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight);
		mWidth = iWidth;  
		mHeight = iHeight;
		LogManager::getSingleton().stream()
			<< "Win32RenderTexture::PBuffer created -- Real dimensions "
            << mWidth << "x" << mHeight;
	}
Esempio n. 20
0
// 启动 OpenGL 后, 才能调用它的扩展函数来设置 multi-sampling 功能.
// 还需要重新打开新的窗口来使用 multi-sampling 模式, 不能使用原来的窗口.
static bool SetPixelformatEX(HCoreDeviceSpec *pSpec)
{
	HWND hWnd = HCoreGetWindowHandleWin32();
	g_hDC = GetDC(hWnd);

	PIXELFORMATDESCRIPTOR pfd;
	ZeroMemory(&pfd, sizeof(pfd));

	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cDepthBits = 24; // 24 bits zbuffer
	pfd.cStencilBits = 8; // 8 bits stencil buffer
	pfd.iLayerType = PFD_MAIN_PLANE; // main layer

	int pixelformat = ChoosePixelFormat(g_hDC, &pfd);

    if ( pixelformat == 0 ) 
    { 
        return false; 
    } 

    if ( SetPixelFormat(g_hDC, pixelformat, &pfd) == FALSE) 
    { 
		ReleaseDC(hWnd, g_hDC);
        return false; 
    }

	g_hGLRC = wglCreateContext(g_hDC);
	wglMakeCurrent(g_hDC, g_hGLRC);

	if (!wglChoosePixelFormatARB)
	{
		wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
	}

	if ( !wglChoosePixelFormatARB )
	{
		printf("OpenGL Display driver does not support wglChoosePixelFormatARB function\n");
		return false;
	}

	int iAttributes[] = { 
		WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
		WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
		WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
		WGL_COLOR_BITS_ARB,24,
		WGL_ALPHA_BITS_ARB,8,
		WGL_DEPTH_BITS_ARB,24,
		WGL_STENCIL_BITS_ARB,8,
		WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
		WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
		WGL_SAMPLES_ARB, pSpec->m_iMultiSamples, 
		0,0};

	float fAttributes[] = {0,0};

	UINT numFormats = 0;

	BOOL valid = wglChoosePixelFormatARB(g_hDC, iAttributes, fAttributes,1, &pixelformat, &numFormats);

	if (!valid && numFormats==0)
	{
		return false;
	}

	DescribePixelFormat(g_hDC, pixelformat, sizeof(pfd), &pfd); 

	if ( g_hGLRC && g_hDC )
	{
		wglMakeCurrent(g_hDC, NULL);
		wglDeleteContext(g_hGLRC);
		g_hGLRC = NULL;

		ReleaseDC(hWnd, g_hDC);
		g_hDC = NULL;

		DestroyWindow(hWnd);

		MSG msg;
		while(GetMessage(&msg, NULL, 0, 0)!=0) {} 
	}

	HCoreCreateWindow(-1, -1, -1, -1, "OpenGL");

	hWnd = HCoreGetWindowHandleWin32();
	g_hDC = GetDC(hWnd);

	if ( SetPixelFormat(g_hDC, pixelformat, &pfd)==FALSE) 
	{ 
		ErrorMessage("SetPixelFormatEX");
		ReleaseDC(hWnd, g_hDC);
		return false;
	}

	g_hGLRC = wglCreateContext(g_hDC);
	wglMakeCurrent(g_hDC, g_hGLRC);

	return true;
}
Esempio n. 21
0
bool OpenGLApp::initAPI(){
	if (screen >= GetSystemMetrics(SM_CMONITORS)) screen = 0;

	int monitorCounter = screen;
	EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM) &monitorCounter);

  // TODO: Use this when saving out position?
  // HMONITOR hMonitor = MonitorFromWindow(m_handle->hWnd, MONITOR_DEFAULTTOPRIMARY);

	DWORD flags = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
	int x, y;


	x = monInfo.rcMonitor.left;
	y = monInfo.rcMonitor.top;

	device.cb = sizeof(device);
	//TODO: Monitor count is not equal to device count?
	EnumDisplayDevices(NULL, 0/*screen*/, &device, 0);

	DEVMODE dm, tdm;
	memset(&dm, 0, sizeof(dm));
	dm.dmSize = sizeof(dm);
	dm.dmBitsPerPel = colorBits;
	dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
	dm.dmPelsWidth  = fullscreenWidth;
	dm.dmPelsHeight = fullscreenHeight;
	dm.dmDisplayFrequency = 60;

	// Find a suitable fullscreen format
	int i = 0;
	int targetHz = 85;
	char str[128];

	resolution->clear();
	while (EnumDisplaySettings((const char *) device.DeviceName, i, &tdm)){
		if (int(tdm.dmBitsPerPel) == colorBits && tdm.dmPelsWidth >= 640 && tdm.dmPelsHeight >= 480){
			sprintf(str, "%dx%d", tdm.dmPelsWidth, tdm.dmPelsHeight);
			int index = resolution->addItemUnique(str);

			if (int(tdm.dmPelsWidth) == fullscreenWidth && int(tdm.dmPelsHeight) == fullscreenHeight){
				if (abs(int(tdm.dmDisplayFrequency) - targetHz) < abs(int(dm.dmDisplayFrequency) - targetHz)){
					dm = tdm;
				}
				resolution->selectItem(index);
			}
		}
		i++;
	}


	if (fullscreen){
    //TODO: Select correct monitor?
    //dm.dmFields |= DM_POSITION ;
    //dm.dmPosition.x = x;
    //dm.dmPosition.y = y;

		if (ChangeDisplaySettingsEx((const char *) device.DeviceName, &dm, NULL, CDS_FULLSCREEN, NULL) == DISP_CHANGE_SUCCESSFUL){
			flags |= WS_POPUP;
			captureMouse(!configDialog->isVisible());
		} else {
			ErrorMsg("Couldn't set fullscreen mode");
			fullscreen = false;
		}
	}

	sprintf(str, "%s (%dx%d)", getTitle(), width, height);
	if (!fullscreen){
		flags |= WS_OVERLAPPEDWINDOW;

		RECT wRect;
		wRect.left = 0;
		wRect.right = width;
		wRect.top = 0;
		wRect.bottom = height;
		AdjustWindowRect(&wRect, flags, FALSE);

		width  = min(wRect.right  - wRect.left, monInfo.rcWork.right  - monInfo.rcWork.left);
		height = min(wRect.bottom - wRect.top,  monInfo.rcWork.bottom - monInfo.rcWork.top);

		x = (monInfo.rcWork.left + monInfo.rcWork.right  - width ) / 2;
		y = (monInfo.rcWork.top  + monInfo.rcWork.bottom - height) / 2;
	}


	hwnd = CreateWindow("Humus", str, flags, x, y, width, height, HWND_DESKTOP, NULL, hInstance, NULL);
  
	PIXELFORMATDESCRIPTOR pfd = {
        sizeof (PIXELFORMATDESCRIPTOR), 1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA, colorBits,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		depthBits, stencilBits,
		0, PFD_MAIN_PLANE, 0, 0, 0, 0
    };

	hdc = GetDC(hwnd);

	int iAttribs[] = {
		WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
		WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB,
		WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
		WGL_RED_BITS_ARB,       8,
		WGL_GREEN_BITS_ARB,     8,
		WGL_BLUE_BITS_ARB,      8,
		WGL_ALPHA_BITS_ARB,     (colorBits > 24)? 8 : 0,
		WGL_DEPTH_BITS_ARB,     depthBits,
		WGL_STENCIL_BITS_ARB,   stencilBits,
		0
	};

	int pixelFormats[256];
	int bestFormat = 0;
	int bestSamples = 0;
	uint nPFormats;
	if (wgl_ext_ARB_pixel_format && wglChoosePixelFormatARB(hdc, iAttribs, NULL, elementsOf(pixelFormats), pixelFormats, &nPFormats) && nPFormats > 0){
		int minDiff = 0x7FFFFFFF;
		int attrib = WGL_SAMPLES_ARB;
		int samples;

		// Find a multisample format as close as possible to the requested
		for (uint i = 0; i < nPFormats; i++){
			wglGetPixelFormatAttribivARB(hdc, pixelFormats[i], 0, 1, &attrib, &samples);
			int diff = abs(antiAliasSamples - samples);
			if (diff < minDiff){
				minDiff = diff;
				bestFormat = i;
				bestSamples = samples;
			}
		}
	} else {
		pixelFormats[0] = ChoosePixelFormat(hdc, &pfd);
	}
	antiAliasSamples = bestSamples;

	SetPixelFormat(hdc, pixelFormats[bestFormat], &pfd);

  if(wgl_ext_ARB_create_context)
  {
    glContext = wglCreateContextAttribsARB(hdc, 0, 0);
  }
  else
  {
    glContext = wglCreateContext(hdc);
  }
	wglMakeCurrent(hdc, glContext);

  ogl_LoadFunctions();
	wgl_LoadFunctions(hdc);

	if (wgl_ext_ARB_multisample && antiAliasSamples > 0){
		glEnable(GL_MULTISAMPLE);
	}

	if (fullscreen) captureMouse(!configDialog->isVisible());

	renderer = new OpenGLRenderer(hdc, glContext);
	renderer->setViewport(width, height);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Esempio n. 22
0
	bool cPBuffer::Init(unsigned int alWidth,unsigned int alHeight, cColor aCol)
	{
		#ifdef WIN32
		unsigned int lFormatNum=0;
		int lFormat=0;

		mlWidth = alWidth;
		mlHeight = alHeight;

		HDC CurrentHdc = wglGetCurrentDC();
		HGLRC CurrentGGlRc = wglGetCurrentContext();

		//Set the pixel format:
		wglChoosePixelFormatARB(CurrentHdc, &mvAttribFormat[0], NULL, 1, &lFormat, &lFormatNum);
		if(lFormatNum==0){
			Error("Couldn't find any pixel format!\n");
			return false;
		}
				
		//Create the buffer
		mPBuffer = wglCreatePbufferARB(CurrentHdc, lFormat, mlWidth, mlHeight, &mvAttribBuffer[0]);
		if (!mPBuffer)
		{
			int err = GetLastError();
			Error("pbuffer creation error!\n");
			return false;
		}

		//Get the Device Context
		mDeviceContext = wglGetPbufferDCARB(mPBuffer);
		if(!mDeviceContext){
			Error("Some DC error!\n");
		}

		//Get the GL Context
		mGLContext = wglCreateContext(mDeviceContext);
		if(!mGLContext){
			Error("Some GLRC error!\n");
		}

		if(mbShareObjects){
			if(!wglShareLists(CurrentGGlRc, mGLContext))
			{
				Error("Error sharing lists.\n");
			}
		}
		
		//Check the real dimensions of the PBuffer
		wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &mlWidth);
		wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &mlHeight);
			
		//Init some GL stuff with the Buffer.
		#ifdef WIN32
		HDC OldHDC = wglGetCurrentDC();
		HGLRC OldGLRC = wglGetCurrentContext();
		#endif
		MakeCurrentContext();
				
		if(mbShareObjects)
		{
			cLowLevelGraphicsSDL* pSDLGfx = static_cast<cLowLevelGraphicsSDL*>(mpLowLevelGraphics);
			pSDLGfx->SetupGL();
		}
		
		mpLowLevelGraphics->SetClearColor(aCol);
		mpLowLevelGraphics->ClearScreen();

		wglMakeCurrent(OldHDC,OldGLRC);
		#elif defined(__linux__)
		return false;
		#endif
	
		return true;
	}
Esempio n. 23
0
bool PBUFFER::Init(	int newWidth, int newHeight,
					const int * attribIList, const float * attribFList, const int * flags)
{
	//Check for pbuffer support
	if(	!GLEE_WGL_ARB_extensions_string	||
		!GLEE_WGL_ARB_pixel_format		||
		!GLEE_WGL_ARB_pbuffer)
	{
		LOG::Instance()->OutputError("Extension required for pBuffer unsupported");
		return false;
	}

	//set class's member variables
	width=newWidth;
	height=newHeight;
	
	//Get the current device context
	HDC hCurrentDC=wglGetCurrentDC();
	if(!hCurrentDC)
	{
		LOG::Instance()->OutputError("Unable to get current Device Context");
		return false;
	}
	
	
	//choose pixel format
	GLint pixelFormat;
	unsigned int numFormats;

	if(!wglChoosePixelFormatARB(hCurrentDC, attribIList, attribFList, 1,
								&pixelFormat, &numFormats))
	{
		LOG::Instance()->OutputError("Unable to find a pixel format for the pbuffer");
		return false;
	}

	//Create the pbuffer
	hBuffer=wglCreatePbufferARB(hCurrentDC, pixelFormat, width, height, flags);
	if(!hBuffer)
	{
		LOG::Instance()->OutputError("Unable to create pbuffer");
		return false;
	}

	//Get the pbuffer's device context
	hDC=wglGetPbufferDCARB(hBuffer);
	if(!hDC)
	{
		LOG::Instance()->OutputError("Unable to get pbuffer's device context");
		return false;
	}

	//Create a rendering context for the pbuffer
	hRC=wglCreateContext(hDC);
	if(!hRC)
	{
		LOG::Instance()->OutputError("Unable to create pbuffer's rendering context");
		return false;
	}

	//Set and output the actual pBuffer dimensions
	wglQueryPbufferARB(hBuffer, WGL_PBUFFER_WIDTH_ARB, &width);
	wglQueryPbufferARB(hBuffer, WGL_PBUFFER_HEIGHT_ARB, &height);
	LOG::Instance()->OutputSuccess("Pbuffer Created: (%d x %d)", width, height);
	
	return TRUE;										//success!
}
int CmnOGLOffscreen::init(void)
{
  /* Fehlercodes:
  -1 = Unable to get address for wglGetExtensionsStringARB
  -2 = WGL_ARB_pbuffer extension was not found
  -3 = One or more WGL_ARB_pbuffer functions were not found
  -4 = WGL_ARB_pixel_format extension was not found
  -5 = One or more WGL_ARB_pixel_format functions were not found
  -6 = WGL_ARB_render_texture extension was not found
  -7 = One or more WGL_ARB_render_texture functions were not found
  -8 = Could not find an acceptable pixel format
  -9 = Could not create the p-buffer
  */
  wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
	char *ext = NULL;
	
	if( wglGetExtensionsStringARB ) ext = (char*)wglGetExtensionsStringARB( wglGetCurrentDC() ); else return -1;
	
  if( strstr( ext, "WGL_ARB_pbuffer" ) == NULL ) return -2;
  
  wglCreatePbufferARB    = (PFNWGLCREATEPBUFFERARBPROC)wglGetProcAddress("wglCreatePbufferARB");
  wglGetPbufferDCARB     = (PFNWGLGETPBUFFERDCARBPROC)wglGetProcAddress("wglGetPbufferDCARB");
  wglReleasePbufferDCARB = (PFNWGLRELEASEPBUFFERDCARBPROC)wglGetProcAddress("wglReleasePbufferDCARB");
	wglDestroyPbufferARB   = (PFNWGLDESTROYPBUFFERARBPROC)wglGetProcAddress("wglDestroyPbufferARB");
	wglQueryPbufferARB     = (PFNWGLQUERYPBUFFERARBPROC)wglGetProcAddress("wglQueryPbufferARB");
  
  if( !wglCreatePbufferARB || !wglGetPbufferDCARB || !wglReleasePbufferDCARB ||!wglDestroyPbufferARB || !wglQueryPbufferARB ) return -3;
	
  if( strstr( ext, "WGL_ARB_pixel_format" ) == NULL ) return -4;
	
  wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");

  if( !wglChoosePixelFormatARB ) return -5;

	g_pbuffer.hPBuffer = NULL;
	g_pbuffer.nWidth   = iWidth;
	g_pbuffer.nHeight  = iHeight;

	int pf_attr[] =
	{
		WGL_SUPPORT_OPENGL_ARB, TRUE,       // P-buffer will be used with OpenGL
		WGL_DRAW_TO_PBUFFER_ARB, TRUE,      // Enable render to p-buffer
		WGL_BIND_TO_TEXTURE_RGBA_ARB, TRUE, // P-buffer will be used as a texture
		WGL_RED_BITS_ARB, 8,                // At least 8 bits for RED channel
		WGL_GREEN_BITS_ARB, 8,              // At least 8 bits for GREEN channel
		WGL_BLUE_BITS_ARB, 8,               // At least 8 bits for BLUE channel
		WGL_ALPHA_BITS_ARB, 8,              // At least 8 bits for ALPHA channel
		WGL_DEPTH_BITS_ARB, 16,             // At least 16 bits for depth buffer
		WGL_DOUBLE_BUFFER_ARB, FALSE,       // We don't require double buffering
		0                                   // Zero terminates the list
	};

	unsigned int count = 0;
  int pixelFormat;
	wglChoosePixelFormatARB( m_hgldc,(const int*)pf_attr, NULL, 1, &pixelFormat, &count);

  if( count == 0 ) return -8;
	
	g_pbuffer.hPBuffer = wglCreatePbufferARB( m_hgldc, pixelFormat, g_pbuffer.nWidth, g_pbuffer.nHeight, NULL/*pb_attr*/ );
	g_pbuffer.hDC      = wglGetPbufferDCARB( g_pbuffer.hPBuffer );
	g_pbuffer.hRC      = wglCreateContext( g_pbuffer.hDC );
	if( !g_pbuffer.hPBuffer ) return -9;


  enable();

  glShadeModel(GL_SMOOTH);						
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);			
	glClearDepth(1.0f);							
	glEnable(GL_DEPTH_TEST);					
	glDepthFunc(GL_LEQUAL);						
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  glViewport(0,0,iWidth,iHeight);	
  glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	double m_dAspect = (iHeight == 0) ? (double)iWidth : (double)iWidth/(double)iHeight;
  double m_dNearPlane   = 0.0; 
	double m_dFarPlane    = 15.0; 
  gluPerspective(45.0, m_dAspect, m_dNearPlane, m_dFarPlane); 
	glMatrixMode(GL_MODELVIEW);

  disable();


  return 1;
}
bool COpenGLControl::InitOpenGL(HINSTANCE hInstance, HWND* a_hWnd, int iMajorVersion, int iMinorVersion, void (*a_ptrInitScene)(LPVOID), void (*a_ptrRenderScene)(LPVOID), void(*a_ptrReleaseScene)(LPVOID), LPVOID lpParam)
{
	if(!InitGLEW(hInstance))return false;

	hWnd = a_hWnd;
	hDC = GetDC(*hWnd);

	bool bError = false;
	PIXELFORMATDESCRIPTOR pfd;

	if(iMajorVersion <= 2)
	{
		memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
		pfd.nSize		= sizeof(PIXELFORMATDESCRIPTOR);
		pfd.nVersion   = 1;
		pfd.dwFlags    = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.cColorBits = 32;
		pfd.cDepthBits = 32;
		pfd.iLayerType = PFD_MAIN_PLANE;
 
		int iPixelFormat = ChoosePixelFormat(hDC, &pfd);
		if (iPixelFormat == 0)return false;

		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false;

		// Create the old style context (OpenGL 2.1 and before)
		hRC = wglCreateContext(hDC);
		if(hRC)wglMakeCurrent(hDC, hRC);
		else bError = true;
	}
	else if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format)
	{
		const int iPixelFormatAttribList[] =
		{
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
			WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
			WGL_COLOR_BITS_ARB, 32,
			WGL_DEPTH_BITS_ARB, 24,
			WGL_STENCIL_BITS_ARB, 8,
			0 // End of attributes list
		};
		int iContextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion,
			WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion,
			WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			0 // End of attributes list
		};

		int iPixelFormat, iNumFormats;
		wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats);

		// PFD seems to be only redundant parameter now
		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false;

		hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs);
		// If everything went OK
		if(hRC) wglMakeCurrent(hDC, hRC);
		else bError = true;

	}
	else bError = true;
	
	if(bError)
	{
		// Generate error messages
		char sErrorMessage[255], sErrorTitle[255];
		sprintf_s(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion); //_s
		sprintf_s(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion); //_s
		MessageBox(*hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION);
		return false;
	}

	ptrRenderScene = a_ptrRenderScene;
	ptrInitScene = a_ptrInitScene;
	ptrReleaseScene = a_ptrReleaseScene;

	if(ptrInitScene != NULL)ptrInitScene(lpParam);

	return true;
}
// Initializes OpenGL rendering context. If succeeds, returns true.
// hInstance - application instance
// a_hWnd - window to init OpenGL into
// a_initScene - pointer to init function
// a_renderScene - pointer to render function
// a_releaseScene - optional parameter of release function
bool COpenGLControl::InitOpenGL(HINSTANCE hInstance, HWND* a_hWnd, void (*a_InitScene)(LPVOID), void (*a_RenderScene)(LPVOID), void(*a_ReleaseScene)(LPVOID), LPVOID lpParam)
{
	if(!InitGLEW(hInstance))return false;

	hWnd = a_hWnd;
	hDC = GetDC(*hWnd);

	bool bError = false;
	PIXELFORMATDESCRIPTOR pfd;

	// if we have access to these functions
	if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format)
	{
		const int iPixelFormatAttribList[] =
		{
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE, // Enable OpenGL support
			WGL_DOUBLE_BUFFER_ARB, GL_TRUE,  // and double buffer
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
			WGL_COLOR_BITS_ARB, 32,
			WGL_DEPTH_BITS_ARB, 24, // Depth buffer size
			WGL_STENCIL_BITS_ARB, 8,
			0 // End of attributes list
		};
		int iContextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, 3, // OpenGL 
			WGL_CONTEXT_MINOR_VERSION_ARB, 3, // version 3.3
			WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			0 // End of attributes list
		};

		int iPixelFormat, iNumFormats;
		wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats);

		// PFD seems to be only redundant parameter now
		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false;

		hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs);
		// If everything went OK
		if(hRC) wglMakeCurrent(hDC, hRC);
		else bError = true;

	}
	else bError = true;
	
	if(bError)
	{
		// Generate error messages
		char sErrorMessage[255], sErrorTitle[255];
		sprintf(sErrorMessage, "OpenGL 3.3 is not supported! Please download latest GPU drivers!");
		sprintf(sErrorTitle, "OpenGL 3.3 Not Supported");
		MessageBox(*hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION);
		return false;
	}

	RenderScene = a_RenderScene;
	InitScene = a_InitScene;
	ReleaseScene = a_ReleaseScene;

	if(InitScene != NULL)InitScene(lpParam);

	return true;
}
Esempio n. 27
0
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);
}
Esempio n. 28
0
	void GlContext::create(uint32_t /*_width*/, uint32_t /*_height*/)
	{
		m_opengl32dll = bx::dlopen("opengl32.dll");
		BGFX_FATAL(NULL != m_opengl32dll, Fatal::UnableToInitialize, "Failed to load opengl32.dll.");

		wglGetProcAddress = (PFNWGLGETPROCADDRESSPROC)bx::dlsym(m_opengl32dll, "wglGetProcAddress");
		BGFX_FATAL(NULL != wglGetProcAddress, Fatal::UnableToInitialize, "Failed get wglGetProcAddress.");

		// If g_bgfxHwnd is NULL, the assumption is that GL context was created
		// by user (for example, using SDL, GLFW, etc.)
		BX_WARN(NULL != g_bgfxHwnd
			, "bgfx::winSetHwnd with valid window is not called. This might "
			  "be intentional when GL context is created by the user."
			);

		if (NULL != g_bgfxHwnd)
		{
			wglMakeCurrent = (PFNWGLMAKECURRENTPROC)bx::dlsym(m_opengl32dll, "wglMakeCurrent");
			BGFX_FATAL(NULL != wglMakeCurrent, Fatal::UnableToInitialize, "Failed get wglMakeCurrent.");

			wglCreateContext = (PFNWGLCREATECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglCreateContext");
			BGFX_FATAL(NULL != wglCreateContext, Fatal::UnableToInitialize, "Failed get wglCreateContext.");

			wglDeleteContext = (PFNWGLDELETECONTEXTPROC)bx::dlsym(m_opengl32dll, "wglDeleteContext");
			BGFX_FATAL(NULL != wglDeleteContext, Fatal::UnableToInitialize, "Failed get wglDeleteContext.");

			m_hdc = GetDC(g_bgfxHwnd);
			BGFX_FATAL(NULL != m_hdc, Fatal::UnableToInitialize, "GetDC failed!");

			// Dummy window to peek into WGL functionality.
			//
			// An application can only set the pixel format of a window one time.
			// Once a window's pixel format is set, it cannot be changed.
			// MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/dd369049%28v=vs.85%29.aspx
			HWND hwnd = CreateWindowA("STATIC"
				, ""
				, WS_POPUP|WS_DISABLED
				, -32000
				, -32000
				, 0
				, 0
				, NULL
				, NULL
				, GetModuleHandle(NULL)
				, 0
				);

			HDC hdc = GetDC(hwnd);
			BGFX_FATAL(NULL != hdc, Fatal::UnableToInitialize, "GetDC failed!");

			HGLRC context = createContext(hdc);

			wglGetExtensionsStringARB  = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
			wglChoosePixelFormatARB    = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
			wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
			wglSwapIntervalEXT         = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");

			if (NULL != wglGetExtensionsStringARB)
			{
				const char* extensions = (const char*)wglGetExtensionsStringARB(hdc);
				BX_TRACE("WGL extensions:");
				dumpExtensions(extensions);
			}

			if (NULL != wglChoosePixelFormatARB
			&&  NULL != wglCreateContextAttribsARB)
			{
				int32_t attrs[] =
				{
					WGL_SAMPLE_BUFFERS_ARB, 0,
					WGL_SAMPLES_ARB, 0,
					WGL_SUPPORT_OPENGL_ARB, true,
					WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
					WGL_DRAW_TO_WINDOW_ARB, true,
					WGL_DOUBLE_BUFFER_ARB, true,
					WGL_COLOR_BITS_ARB, 32,
					WGL_DEPTH_BITS_ARB, 24,
					WGL_STENCIL_BITS_ARB, 8,
					0
				};

				int result;
				uint32_t numFormats = 0;
				do 
				{
					result = wglChoosePixelFormatARB(m_hdc, attrs, NULL, 1, &m_pixelFormat, &numFormats);
					if (0 == result
						||  0 == numFormats)
					{
						attrs[3] >>= 1;
						attrs[1] = attrs[3] == 0 ? 0 : 1;
					}

				} while (0 == numFormats);

				DescribePixelFormat(m_hdc, m_pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &m_pfd);

				BX_TRACE("Pixel format:\n"
					"\tiPixelType %d\n"
					"\tcColorBits %d\n"
					"\tcAlphaBits %d\n"
					"\tcDepthBits %d\n"
					"\tcStencilBits %d\n"
					, m_pfd.iPixelType
					, m_pfd.cColorBits
					, m_pfd.cAlphaBits
					, m_pfd.cDepthBits
					, m_pfd.cStencilBits
					);

				result = SetPixelFormat(m_hdc, m_pixelFormat, &m_pfd);
				// When window is created by SDL and SDL_WINDOW_OPENGL is set SetPixelFormat
				// will fail. Just warn and continue. In case it failed for some other reason
				// create context will fail and it will error out there.
				BX_WARN(result, "SetPixelFormat failed (last err: 0x%08x)!", GetLastError() );

				uint32_t flags = BGFX_CONFIG_DEBUG ? WGL_CONTEXT_DEBUG_BIT_ARB : 0;
				BX_UNUSED(flags);
				int32_t contextAttrs[9] =
				{
#if BGFX_CONFIG_RENDERER_OPENGL >= 31
					WGL_CONTEXT_MAJOR_VERSION_ARB, BGFX_CONFIG_RENDERER_OPENGL / 10,
					WGL_CONTEXT_MINOR_VERSION_ARB, BGFX_CONFIG_RENDERER_OPENGL % 10,
					WGL_CONTEXT_FLAGS_ARB, flags,
					WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
#else
					WGL_CONTEXT_MAJOR_VERSION_ARB, 2,
					WGL_CONTEXT_MINOR_VERSION_ARB, 1,
					0, 0,
					0, 0,
#endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
					0
				};

				m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs);
				if (NULL == m_context)
				{
					// nVidia doesn't like context profile mask for contexts below 3.2?
					contextAttrs[6] = WGL_CONTEXT_PROFILE_MASK_ARB == contextAttrs[6] ? 0 : contextAttrs[6];
					m_context = wglCreateContextAttribsARB(m_hdc, 0, contextAttrs);
				}
				BGFX_FATAL(NULL != m_context, Fatal::UnableToInitialize, "Failed to create context 0x%08x.", GetLastError() );

				BX_STATIC_ASSERT(sizeof(contextAttrs) == sizeof(m_contextAttrs) );
				memcpy(m_contextAttrs, contextAttrs, sizeof(contextAttrs) );
			}
Esempio n. 29
0
void RenderTexture::Init(int width, int height, bool fboMode)
{
	GLenum err;
	canvas_hDC = wglGetCurrentDC();
	canvas_hRC = wglGetCurrentContext();

	m_texID = 0;
	m_FBO = fboMode;

	if (width == 0 || height == 0)
	{
		int screenSize[4];
		glGetIntegerv(GL_VIEWPORT, screenSize);

		nWidth = screenSize[2];
		nHeight = screenSize[3];
	}
	else
	{
		nWidth = width;
		nHeight = height;
	}

	// Find the (easiest) format to use
	if (video.supportNPOT && video.supportTexRects && GL_TEXTURE_RECTANGLE_ARB)
	{
		m_texFormat = GL_TEXTURE_RECTANGLE_ARB;
	}
	else
	{
		// If non-power-of-two textures aren't supported, force them to be power-of-two of the max texture size.
		m_texFormat = GL_TEXTURE_2D;

		GLint texSize; 
		glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); 

		bool end=false;
		int curMax=0;

		// Make sure its square and a power-of-two
		for (size_t i=5; !end; i++)
		{
			int iSize = powf(2,(float)i);
			if (iSize < texSize)
				curMax = iSize;
			else
				end = true;
		}

		// Divide by 2 to make sure they're no where near their max texture size
		nWidth = nHeight = (curMax/2);
	}

	// Hmm... why was this here?
	//m_texFormat = GL_TEXTURE_2D;


	if (m_FBO)
	{ // Frame Buffer OBject mode (newer, better, only supported by newer cards and drivers though)
		
		// Reported crash in this section of the code by a user
		// add exception handling to try and capture it for future versions.
		try
		{
			LOG_INFO << "GFX Info: Initialising FrameBufferObject.";

			// Generate our buffers and texture
			glGenFramebuffers(1, &m_frameBuffer );
			glGenRenderbuffers(1, &m_depthRenderBuffer );
			glGenTextures(1, &m_texID);

			// --
			// Bind frame buffer and texture
			glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_frameBuffer);
			glBindTexture(m_texFormat, m_texID);

			// This is our dynamic texture, which will be loaded with new pixel data
			// after we're finshed rendering to the p-buffer.
			glTexImage2D(m_texFormat, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
			glTexParameteri(m_texFormat, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
			glTexParameteri(m_texFormat, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

			// And attach it to the FBO so we can render to it
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, m_texFormat, m_texID, 0);

			// attach a depth buffer to the Frame buffer
			glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthRenderBuffer );
			glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, nWidth, nHeight);
			glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthRenderBuffer);

			CHECK_FRAMEBUFFER_STATUS();

			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);	// Unbind the FBO for now
		}
		catch (...)
		{
			LOG_ERROR << "FrameBuffer Error:" << __FILE__ << ": line #" << __LINE__ << ":" << __FUNCTION__;
		}

	}
	else
	{ // Pixel Buffer Mode
		LOG_INFO << "Attempting to create a PixelBuffer.";

		//-------------------------------------------------------------------------
		// Create a p-buffer for off-screen rendering.
		//-------------------------------------------------------------------------
		
		// Define the minimum pixel format requirements we will need for our 
		// p-buffer. A p-buffer is just like a frame buffer, it can have a depth 
		// buffer associated with it and it can be double buffered.
		int pf_attr[] =
		{
			WGL_SUPPORT_OPENGL_ARB, TRUE,       // P-buffer will be used with OpenGL
			WGL_DRAW_TO_PBUFFER_ARB, TRUE,      // Enable render to p-buffer
			WGL_BIND_TO_TEXTURE_RGBA_ARB, TRUE, // P-buffer will be used as a texture
			WGL_RED_BITS_ARB, 8,                // At least 8 bits for RED channel
			WGL_GREEN_BITS_ARB, 8,              // At least 8 bits for GREEN channel
			WGL_BLUE_BITS_ARB, 8,               // At least 8 bits for BLUE channel
			WGL_ALPHA_BITS_ARB, 8,              // At least 8 bits for ALPHA channel
			WGL_DEPTH_BITS_ARB, 16,             // At least 16 bits for depth buffer
			WGL_DOUBLE_BUFFER_ARB, FALSE,       // We don't require double buffering
			0                                   // Zero terminates the list
		};

		unsigned int iCount = 0;
		int iPixelFormat = 0;
		// g_hdc = wxglcanvas hdc

		wglChoosePixelFormatARB(canvas_hDC, (const int*)pf_attr, NULL, 1, &iPixelFormat, &iCount);

		if (iCount == 0)
		{
			LOG_ERROR << "wglChoosePixelFormatARB() Failed! PixelBuffer could not find an acceptable pixel format!" << glGetError();
			return;
		}

		// Set some p-buffer attributes so that we can use this p-buffer as a
		// 2D RGBA texture target.
		int pb_attr[] =
		{
			WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB, // Our p-buffer will have a texture format of RGBA
			WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,   // Of texture target will be GL_TEXTURE_2D
			0                                             // Zero terminates the list
		};

		// Create the p-buffer...
		m_hPBuffer = wglCreatePbufferARB(canvas_hDC, iPixelFormat, nWidth, nHeight, pb_attr );

		// Error check
		err = glGetError();
		if (!m_hPBuffer)
		{
			LOG_ERROR << "Could not create the PixelBuffer." << err;
			return;
		}
		else if (err==GL_NO_ERROR)
		{
			LOG_INFO << "Successfully created the PixelBuffer.";
		}
		else if (err==GL_INVALID_ENUM)
		{
			LOG_ERROR << "Invalid Enum during PixelBuffer creation.";
		}
		else if (err==GL_INVALID_VALUE)
		{
			LOG_ERROR << "Invalid Value during PixelBuffer creation.";
		}
		else if (err==GL_INVALID_OPERATION)
		{
			LOG_ERROR << "Invalid Operation during PixelBuffer creation.";
		}
		else if (err==GL_OUT_OF_MEMORY)
		{
			LOG_ERROR << "Critical error!  Out-of-Memory during PixelBuffer creation. PixelBuffer could not be created.";
			return;
		}
		else
		{
			LOG_ERROR << "PixelBuffer created, but an unknown error occured :" << err;
		}

		m_hDC = wglGetPbufferDCARB( m_hPBuffer );
		m_hRC = wglCreateContext( m_hDC );

		int h=0, w=0;
		wglQueryPbufferARB( m_hPBuffer, WGL_PBUFFER_HEIGHT_ARB, &h );
		wglQueryPbufferARB( m_hPBuffer, WGL_PBUFFER_WIDTH_ARB, &w );

		if (h!=nHeight || w!=nWidth)
		{
			LOG_ERROR << "The width and height of the created PixelBuffer don't match the requirements. Image likely to come out distorted.";
			nHeight = h;
			nWidth = w;
		}

		if (!wglShareLists(canvas_hRC, m_hRC))
		{
			err = glGetError();
			LOG_ERROR << "Call to wglShareLists() failed for our PixelBuffer.";
		}

		// We were successful in creating a p-buffer. We can now make its context 
		// current and set it up just like we would a regular context 
		// attached to a window.
		if (!wglMakeCurrent(m_hDC, m_hRC))
		{
			err = glGetError();
			LOG_ERROR << "wglMakeCurrent() Failed! Could not make the PBuffer's context current!" << err;
		}

		// Setup OpenGL RenderState
		InitGL();

		// This is our dynamic texture, which will be loaded with new pixel data
		// after we're finshed rendering to the p-buffer.
		glGenTextures(1, &m_texID);
		glBindTexture(m_texFormat, m_texID);
		glTexImage2D(m_texFormat, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); //GL_FLOAT
		glTexParameteri(m_texFormat, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		glTexParameteri(m_texFormat, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		//glTexParameteri(texFormat, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
		//glTexParameteri(texFormat, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

		// Now set the current context back to original.
		if (!wglMakeCurrent(canvas_hDC, canvas_hRC))
		{
			err = glGetError();
			LOG_ERROR << "wglMakeCurrent() Failed! Could not return the context back to the wxGLCanvas!" << err;
		}
	}
}
Esempio n. 30
0
void
VisualInfoARB (GLContext* ctx)
{
  int attrib[32], value[32], n_attrib, n_pbuffer=0, n_float=0;
  int i, pf, maxpf;
  unsigned int c;

  /* to get pbuffer capable pixel formats */
  attrib[0] = WGL_DRAW_TO_PBUFFER_ARB;
  attrib[1] = GL_TRUE;
  attrib[2] = 0;
  wglChoosePixelFormatARB(ctx->dc, attrib, 0, 1, &pf, &c);
  /* query number of pixel formats */
  attrib[0] = WGL_NUMBER_PIXEL_FORMATS_ARB;
  wglGetPixelFormatAttribivARB(ctx->dc, 0, 0, 1, attrib, value);
  maxpf = value[0];
  for (i=0; i<32; i++)
    value[i] = 0;

  attrib[0] = WGL_SUPPORT_OPENGL_ARB;
  attrib[1] = WGL_DRAW_TO_WINDOW_ARB;
  attrib[2] = WGL_DRAW_TO_BITMAP_ARB;
  attrib[3] = WGL_ACCELERATION_ARB;
  /* WGL_NO_ACCELERATION_ARB, WGL_GENERIC_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB */
  attrib[4] = WGL_SWAP_METHOD_ARB;
  /* WGL_SWAP_EXCHANGE_ARB, WGL_SWAP_COPY_ARB, WGL_SWAP_UNDEFINED_ARB */
  attrib[5] = WGL_DOUBLE_BUFFER_ARB;
  attrib[6] = WGL_STEREO_ARB;
  attrib[7] = WGL_PIXEL_TYPE_ARB;
  /* WGL_TYPE_RGBA_ARB, WGL_TYPE_COLORINDEX_ARB,
     WGL_TYPE_RGBA_FLOAT_ATI (WGL_ATI_pixel_format_float) */
  /* Color buffer information */
  attrib[8] = WGL_COLOR_BITS_ARB;
  attrib[9] = WGL_RED_BITS_ARB;
  attrib[10] = WGL_GREEN_BITS_ARB;
  attrib[11] = WGL_BLUE_BITS_ARB;
  attrib[12] = WGL_ALPHA_BITS_ARB;
  /* Accumulation buffer information */
  attrib[13] = WGL_ACCUM_BITS_ARB;
  attrib[14] = WGL_ACCUM_RED_BITS_ARB;
  attrib[15] = WGL_ACCUM_GREEN_BITS_ARB;
  attrib[16] = WGL_ACCUM_BLUE_BITS_ARB;
  attrib[17] = WGL_ACCUM_ALPHA_BITS_ARB;
  /* Depth, stencil, and aux buffer information */
  attrib[18] = WGL_DEPTH_BITS_ARB;
  attrib[19] = WGL_STENCIL_BITS_ARB;
  attrib[20] = WGL_AUX_BUFFERS_ARB;
  /* Layer information */
  attrib[21] = WGL_NUMBER_OVERLAYS_ARB;
  attrib[22] = WGL_NUMBER_UNDERLAYS_ARB;
  attrib[23] = WGL_SWAP_LAYER_BUFFERS_ARB;
  attrib[24] = WGL_SAMPLES_ARB;
  attrib[25] = WGL_SUPPORT_GDI_ARB;
  n_attrib = 26;
  if (WGLEW_ARB_pbuffer)
  {
    attrib[n_attrib] = WGL_DRAW_TO_PBUFFER_ARB;
    n_pbuffer = n_attrib;
    n_attrib++;
  }
  if (WGLEW_NV_float_buffer)
  {
    attrib[n_attrib] = WGL_FLOAT_COMPONENTS_NV;
    n_float = n_attrib;
    n_attrib++;
  }

  if (!verbose)
  {
    /* print table header */
    fprintf(file, " +-----+-------------------------+-----------------+----------+-----------------+----------+\n");
    fprintf(file, " |     |          visual         |      color      | ax dp st |      accum      |   layer  |\n");
    fprintf(file, " |  id | tp ac gd fm db sw st ms |  sz  r  g  b  a | bf th cl |  sz  r  g  b  a | ov un sw |\n");
    fprintf(file, " +-----+-------------------------+-----------------+----------+-----------------+----------+\n");
    /* loop through all the pixel formats */
    for(i = 1; i <= maxpf; i++)
    {
      wglGetPixelFormatAttribivARB(ctx->dc, i, 0, n_attrib, attrib, value);
      /* only describe this format if it supports OpenGL */
      if (!value[0]) continue;
      /* by default show only fully accelerated window or pbuffer capable visuals */
      if (!showall
      && ((value[2] && !value[1])
      || (!WGLEW_ARB_pbuffer || !value[n_pbuffer])
      || (value[3] != WGL_FULL_ACCELERATION_ARB))) continue;
      /* print out the information for this visual */
      /* visual id */
      fprintf(file, " |% 4d | ", i);
      /* visual type */
      if (value[1])
      {
    if (WGLEW_ARB_pbuffer && value[n_pbuffer]) fprintf(file, "wp ");
    else fprintf(file, "wn ");
      }
      else
      {
    if (value[2]) fprintf(file, "bm ");
    else if (WGLEW_ARB_pbuffer && value[n_pbuffer]) fprintf(file, "pb ");
      }
      /* acceleration */
      fprintf(file, "%s ", value[3] == WGL_FULL_ACCELERATION_ARB ? "fu" :
          value[3] == WGL_GENERIC_ACCELERATION_ARB ? "ge" :
          value[3] == WGL_NO_ACCELERATION_ARB ? "no" : ". ");
      /* gdi support */
      fprintf(file, " %c ", value[25] ? 'y' : '.');
      /* format */
      if (WGLEW_NV_float_buffer && value[n_float]) fprintf(file, " f ");
      else if (WGLEW_ATI_pixel_format_float && value[7] == WGL_TYPE_RGBA_FLOAT_ATI) fprintf(file, " f ");
      else if (value[7] == WGL_TYPE_RGBA_ARB) fprintf(file, " i ");
      else if (value[7] == WGL_TYPE_COLORINDEX_ARB) fprintf(file, " c ");
      /* double buffer */
      fprintf(file, " %c ", value[5] ? 'y' : '.');
      /* swap method */
      if (value[4] == WGL_SWAP_EXCHANGE_ARB) fprintf(file, " x ");
      else if (value[4] == WGL_SWAP_COPY_ARB) fprintf(file, " c ");
      else if (value[4] == WGL_SWAP_UNDEFINED_ARB) fprintf(file, " . ");
      else fprintf(file, " . ");
      /* stereo */
      fprintf(file, " %c ", value[6] ? 'y' : '.');
      /* multisample */
      if (value[24] > 0)
    fprintf(file, "%2d | ", value[24]);
      else
    fprintf(file, " . | ");
      /* color size */
      if (value[8]) fprintf(file, "%3d ", value[8]);
      else fprintf(file, "  . ");
      /* red */
      if (value[9]) fprintf(file, "%2d ", value[9]);
      else fprintf(file, " . ");
      /* green */
      if (value[10]) fprintf(file, "%2d ", value[10]);
      else fprintf(file, " . ");
      /* blue */
      if (value[11]) fprintf(file, "%2d ", value[11]);
      else fprintf(file, " . ");
      /* alpha */
      if (value[12]) fprintf(file, "%2d | ", value[12]);
      else fprintf(file, " . | ");
      /* aux buffers */
      if (value[20]) fprintf(file, "%2d ", value[20]);
      else fprintf(file, " . ");
      /* depth */
      if (value[18]) fprintf(file, "%2d ", value[18]);
      else fprintf(file, " . ");
      /* stencil */
      if (value[19]) fprintf(file, "%2d | ", value[19]);
      else fprintf(file, " . | ");
      /* accum size */
      if (value[13]) fprintf(file, "%3d ", value[13]);
      else fprintf(file, "  . ");
      /* accum red */
      if (value[14]) fprintf(file, "%2d ", value[14]);
      else fprintf(file, " . ");
      /* accum green */
      if (value[15]) fprintf(file, "%2d ", value[15]);
      else fprintf(file, " . ");
      /* accum blue */
      if (value[16]) fprintf(file, "%2d ", value[16]);
      else fprintf(file, " . ");
      /* accum alpha */
      if (value[17]) fprintf(file, "%2d | ", value[17]);
      else fprintf(file, " . | ");
      /* overlay */
      if (value[21]) fprintf(file, "%2d ", value[21]);
      else fprintf(file, " . ");
      /* underlay */
      if (value[22]) fprintf(file, "%2d ", value[22]);
      else fprintf(file, " . ");
      /* layer swap */
      if (value[23]) fprintf(file, "y ");
      else fprintf(file, " . ");
      fprintf(file, "|\n");
    }
    /* print table footer */
    fprintf(file, " +-----+-------------------------+-----------------+----------+-----------------+----------+\n");
    fprintf(file, " |     |          visual         |      color      | ax dp st |      accum      |   layer  |\n");
    fprintf(file, " |  id | tp ac gd fm db sw st ms |  sz  r  g  b  a | bf th cl |  sz  r  g  b  a | ov un sw |\n");
    fprintf(file, " +-----+-------------------------+-----------------+----------+-----------------+----------+\n");
  }
  else /* verbose */
  {
#if 0
    fprintf(file, "\n");
    /* loop through all the pixel formats */
    for(i = 1; i <= maxpf; i++)
    {
      DescribePixelFormat(ctx->dc, i, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
      /* only describe this format if it supports OpenGL */
      if(!(pfd.dwFlags & PFD_SUPPORT_OPENGL)
     || (drawableonly && !(pfd.dwFlags & PFD_DRAW_TO_WINDOW))) continue;
      fprintf(file, "Visual ID: %2d  depth=%d  class=%s\n", i, pfd.cDepthBits,
         pfd.cColorBits <= 8 ? "PseudoColor" : "TrueColor");
      fprintf(file, "    bufferSize=%d level=%d renderType=%s doubleBuffer=%d stereo=%d\n", pfd.cColorBits, pfd.bReserved, pfd.iPixelType == PFD_TYPE_RGBA ? "rgba" : "ci", pfd.dwFlags & PFD_DOUBLEBUFFER, pfd.dwFlags & PFD_STEREO);
      fprintf(file, "    generic=%d generic accelerated=%d\n", (pfd.dwFlags & PFD_GENERIC_FORMAT) == PFD_GENERIC_FORMAT, (pfd.dwFlags & PFD_GENERIC_ACCELERATED) == PFD_GENERIC_ACCELERATED);
      fprintf(file, "    rgba: redSize=%d greenSize=%d blueSize=%d alphaSize=%d\n", pfd.cRedBits, pfd.cGreenBits, pfd.cBlueBits, pfd.cAlphaBits);
      fprintf(file, "    auxBuffers=%d depthSize=%d stencilSize=%d\n", pfd.cAuxBuffers, pfd.cDepthBits, pfd.cStencilBits);
      fprintf(file, "    accum: redSize=%d greenSize=%d blueSize=%d alphaSize=%d\n", pfd.cAccumRedBits, pfd.cAccumGreenBits, pfd.cAccumBlueBits, pfd.cAccumAlphaBits);
      fprintf(file, "    multiSample=%d multisampleBuffers=%d\n", 0, 0);
      fprintf(file, "    Opaque.\n");
    }
#endif
  }
}