Example #1
0
int
main (int argc, char **argv)
{

#ifdef WIN32
  HGLRC sdl_gl_context = 0;
  HDC sdl_dc = 0;
#else
  SDL_SysWMinfo info;
  Display *sdl_display = NULL;
  Window sdl_win = 0;
  GLXContext sdl_gl_context = NULL;
#endif

  GMainLoop *loop = NULL;
  GstPipeline *pipeline = NULL;
  GstBus *bus = NULL;
  GstElement *glfilter = NULL;
  GstElement *fakesink = NULL;
  GstState state;
  GAsyncQueue *queue_input_buf = NULL;
  GAsyncQueue *queue_output_buf = NULL;
  GstGLDisplay *display;
  GstGLContext *sdl_context;
  const gchar *platform;

  /* Initialize SDL for video output */
  if (SDL_Init (SDL_INIT_VIDEO) < 0) {
    fprintf (stderr, "Unable to initialize SDL: %s\n", SDL_GetError ());
    return -1;
  }

  /* Create a 640x480 OpenGL screen */
  if (SDL_SetVideoMode (640, 480, 0, SDL_OPENGL) == NULL) {
    fprintf (stderr, "Unable to create OpenGL screen: %s\n", SDL_GetError ());
    SDL_Quit ();
    return -1;
  }

  /* Set the title bar in environments that support it */
  SDL_WM_SetCaption ("SDL and gst-plugins-gl", NULL);


  /* Loop, drawing and checking events */
  InitGL (640, 480);

  gst_init (&argc, &argv);
  loop = g_main_loop_new (NULL, FALSE);

  /* retrieve and turn off sdl opengl context */
#ifdef WIN32
  sdl_gl_context = wglGetCurrentContext ();
  sdl_dc = wglGetCurrentDC ();
  wglMakeCurrent (0, 0);
  platform = "wgl";
  display = gst_gl_display_new ();
#else
  SDL_VERSION (&info.version);
  SDL_GetWMInfo (&info);
  /* FIXME: This display is different to the one that SDL uses to create the
   * GL context inside SDL_SetVideoMode() above which fails on Intel hardware
   */
  sdl_display = info.info.x11.display;
  sdl_win = info.info.x11.window;
  sdl_gl_context = glXGetCurrentContext ();
  glXMakeCurrent (sdl_display, None, 0);
  platform = "glx";
  display = (GstGLDisplay *) gst_gl_display_x11_new_with_display (sdl_display);
#endif

  sdl_context = gst_gl_context_new_wrapped (display, (guintptr) sdl_gl_context,
      gst_gl_platform_from_string (platform), GST_GL_API_OPENGL);

  pipeline =
      GST_PIPELINE (gst_parse_launch
      ("videotestsrc ! video/x-raw, width=320, height=240, framerate=(fraction)30/1 ! "
          "gleffects effect=5 ! fakesink sync=1", NULL));

  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  gst_bus_add_signal_watch (bus);
  g_signal_connect (bus, "message::error", G_CALLBACK (end_stream_cb), loop);
  g_signal_connect (bus, "message::warning", G_CALLBACK (end_stream_cb), loop);
  g_signal_connect (bus, "message::eos", G_CALLBACK (end_stream_cb), loop);
  gst_object_unref (bus);

  /* sdl_gl_context is an external OpenGL context with which gst-plugins-gl want to share textures */
  glfilter = gst_bin_get_by_name (GST_BIN (pipeline), "gleffects0");
  g_object_set (G_OBJECT (glfilter), "other-context", sdl_context, NULL);
  gst_object_unref (glfilter);

  /* NULL to PAUSED state pipeline to make sure the gst opengl context is created and
   * shared with the sdl one */
  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PAUSED);
  state = GST_STATE_PAUSED;
  if (gst_element_get_state (GST_ELEMENT (pipeline), &state, NULL,
          GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) {
    g_debug ("failed to pause pipeline\n");
    return -1;
  }

  /* turn on back sdl opengl context */
#ifdef WIN32
  wglMakeCurrent (sdl_dc, sdl_gl_context);
#else
  glXMakeCurrent (sdl_display, sdl_win, sdl_gl_context);
#endif

  /* append a gst-gl texture to this queue when you do not need it no more */
  fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "fakesink0");
  g_object_set (G_OBJECT (fakesink), "signal-handoffs", TRUE, NULL);
  g_signal_connect (fakesink, "handoff", G_CALLBACK (on_gst_buffer), NULL);
  queue_input_buf = g_async_queue_new ();
  queue_output_buf = g_async_queue_new ();
  g_object_set_data (G_OBJECT (fakesink), "queue_input_buf", queue_input_buf);
  g_object_set_data (G_OBJECT (fakesink), "queue_output_buf", queue_output_buf);
  g_object_set_data (G_OBJECT (fakesink), "loop", loop);
  gst_object_unref (fakesink);

  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);

  g_main_loop_run (loop);

  /* before to deinitialize the gst-gl-opengl context,
   * no shared context (here the sdl one) must be current
   */
#ifdef WIN32
  wglMakeCurrent (0, 0);
#else
  glXMakeCurrent (sdl_display, sdl_win, sdl_gl_context);
#endif

  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL);
  gst_object_unref (pipeline);

  /* turn on back sdl opengl context */
#ifdef WIN32
  wglMakeCurrent (sdl_dc, sdl_gl_context);
#else
  glXMakeCurrent (sdl_display, None, 0);
#endif

  SDL_Quit ();

  /* make sure there is no pending gst gl buffer in the communication queues 
   * between sdl and gst-gl
   */
  while (g_async_queue_length (queue_input_buf) > 0) {
    GstBuffer *buf = (GstBuffer *) g_async_queue_pop (queue_input_buf);
    gst_buffer_unref (buf);
  }

  while (g_async_queue_length (queue_output_buf) > 0) {
    GstBuffer *buf = (GstBuffer *) g_async_queue_pop (queue_output_buf);
    gst_buffer_unref (buf);
  }

  return 0;
}
Example #2
0
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC)
{
	wglMakeCurrent( NULL, NULL );
	wglDeleteContext( hRC );
	ReleaseDC( hWnd, hDC );
}
// 取消 OpenGL ,在程序结束前调用,释放渲染环境,设备环境以及最终窗口句柄。
void DisableOpenGL()
{
	wglMakeCurrent( NULL, NULL );
	wglDeleteContext( ghRC );
	ReleaseDC( ghWnd, ghDC );
}
	//TODO: cleanup code, replace message boxes
	bool WindowsPlatform::CreatePlatformWindow(const char* title, int width, int height, int bits, bool fullscreenflag)
	{
		const char *windowName = "Monocle Engine\0";
		unsigned int		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

		fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

		hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
		wc.style				= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
		wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
		wc.cbClsExtra		= 0;									// No Extra Window Data
		wc.cbWndExtra		= 0;									// No Extra Window Data
		wc.hInstance			= hInstance;							// Set The Instance
		wc.hIcon				= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
		wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
		wc.hbrBackground		= NULL;									// No Background Required For GL
		wc.lpszMenuName		= NULL;									// We Don't Want A Menu
		wc.lpszClassName		= windowName;								// Set The Class Name

		if(bits < 0)
		{
			DEVMODE dmScreenSettings;
			if(!EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &dmScreenSettings ))
			{
				Debug::Log("Could not get display settings");
				return false;
			}
			
			bits = dmScreenSettings.dmBitsPerPel;
		}

		if (!RegisterClass(&wc))									// Attempt To Register The Window Class
		{
			Debug::Log("Failed To Register The Window Class.");
			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	= bits;					// Selected Bits Per Pixel
			dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

			// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
			if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
			{
				Debug::Log("The Requested Fullscreen Mode Is Not Supported");
				return false;
				//TODO: fallback on windowed?
			}
		}

		if (fullscreen)												// Are We Still In Fullscreen Mode?
		{
			dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
			dwStyle=WS_POPUP;										// Windows Style
			//ShowCursor(FALSE);										// Hide Mouse Pointer
		}
		else
		{
			dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
			dwStyle=WS_OVERLAPPEDWINDOW;								// Windows Style
		}

		AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

		if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
									windowName,							// 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
									hInstance,							// Instance
									NULL)))								// Dont Pass Anything To WM_CREATE
		{
			KillPlatformWindow();								// Reset The 
			Debug::Log("Window Creation Error");
			return false;								// Return FALSE
		}

		static PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
		{
			sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
			1,											// Version Number
			PFD_DRAW_TO_WINDOW |						// Format Must Support Window
			PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
			PFD_DOUBLEBUFFER,							// Must Support Double Buffering
			PFD_TYPE_RGBA,								// Request An RGBA Format
			bits,										// Select Our Color Depth
			0, 0, 0, 0, 0, 0,							// Color Bits Ignored
			0,											// No Alpha Buffer
			0,											// Shift Bit Ignored
			0,											// No Accumulation Buffer
			0, 0, 0, 0,									// Accumulation Bits Ignored
			16,											// 16Bit Z-Buffer (Depth Buffer)  
			0,											// No Stencil Buffer
			0,											// No Auxiliary Buffer
			PFD_MAIN_PLANE,								// Main Drawing Layer
			0,											// Reserved
			0, 0, 0										// Layer Masks Ignored
		};
	
		if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
		{
			KillPlatformWindow();								// Reset The Display
			Debug::Log("Can't Create Device Context");
			return false;								// Return FALSE
		}

		if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
		{
			KillPlatformWindow();								// Reset The Display
			Debug::Log("Can't Find A Suitable PixelFormat");
			return false;								// Return FALSE
		}

		if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
		{
			KillPlatformWindow();								// Reset The Display
			Debug::Log("Can't Set The PixelFormat");
			return false;								// Return FALSE
		}

		if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
		{
			KillPlatformWindow();								// Reset The Display
			Debug::Log("Can't Create a GL Rendering Context");
			return false;								// Return FALSE
		}

		if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
		{
			KillPlatformWindow();								// Reset The Display
			Debug::Log("Can't Activate The GL Rendering Context");
			return FALSE;								// Return FALSE
		}

		ShowWindow(hWnd,SW_SHOW);						// Show The Window

		CenterWindow();

		SetForegroundWindow(hWnd);
		SetFocus(hWnd);

		

		/*
		if (fullscreen)
		{
			DEVMODE settings;
			settings.dmBitsPerPel = bits;
			settings.dmPelsWidth = width;
			settings.dmPelsHeight = height;
			settings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
			bool changed = (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL);
		}
		*/

		return true;
	}
static bool InitializeOpenGL ()
{
	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 );

#else
	GLint attributes[16];
	int i = 0;
	attributes[i++]=AGL_RGBA;
	attributes[i++]=AGL_PIXEL_SIZE;
	attributes[i++]=32;
	attributes[i++]=AGL_NO_RECOVERY;
	attributes[i++]=AGL_NONE;
	
	AGLPixelFormat pixelFormat = aglChoosePixelFormat(NULL,0,attributes);
	AGLContext agl = aglCreateContext(pixelFormat, NULL);
	aglSetCurrentContext (agl);

#endif
	
	// check if we have GLSL
	const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
	hasGLSL = strstr(extensions, "GL_ARB_shader_objects") && strstr(extensions, "GL_ARB_vertex_shader") && strstr(extensions, "GL_ARB_fragment_shader");
	
#ifdef _MSC_VER
	if (hasGLSL)
	{
		glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)wglGetProcAddress("glDeleteObjectARB");
		glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB");
		glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB");
		glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB");
		glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB");
		glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)wglGetProcAddress("glGetObjectParameterivARB");
	}
#endif
	
	return hasGLSL;
}
Example #6
0
GLvoid drawScene(GLvoid) 
{ 
	wglMakeCurrent(g_hDC, g_hGLRC);

    glClear(GL_COLOR_BUFFER_BIT); 
 
    glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
	glColor4ub(255, 255, 255, 255);
		
	
	GLfloat maxU = (GLfloat) ((g_windowWidth * 1.0) / g_vTextures[0].nWidth);
	GLfloat maxV = (GLfloat) ((g_windowHeight * 1.0) / g_vTextures[0].nHeight);
	
	glBindTexture(GL_TEXTURE_2D, g_vTextureIDs[0]);
	
	glBegin(GL_QUADS);
	glTexCoord2f(0.0f, maxV); glVertex2i(0, 0);
	glTexCoord2f(maxU, maxV); glVertex2i(g_windowWidth, 0);
	glTexCoord2f(maxU, 0.0f); glVertex2i(g_windowWidth, g_windowHeight);
	glTexCoord2f(0.0f, 0.0f); glVertex2i(0, g_windowHeight);
	glEnd();
	
	glBindTexture(GL_TEXTURE_2D, g_vTextureIDs[1]);
	
	glBegin(GL_QUADS);
	
	glTexCoord2f(0.0f, g_vTextures[1].nMaxV);	glVertex2i(100, 100);
	
	glTexCoord2f(g_vTextures[1].nMaxU, 
		g_vTextures[1].nMaxV);					glVertex2i(171, 100); 
	glTexCoord2f(g_vTextures[1].nMaxU, 0.0f); 	glVertex2i(171, 196);
	glTexCoord2f(0.0f, 0.0f); 					glVertex2i(100, 196);
	
	glEnd();
 	
	glDisable(GL_TEXTURE_2D);

	
	glBegin(GL_QUADS);
	glColor4ub(0, 200, 0, 255);
	glVertex2i(200, 100);
	glVertex2i(350, 100);
	glVertex2i(350, 200);
	glVertex2i(200, 200);
	glEnd();

	glBegin(GL_LINE_LOOP);
	glColor4ub(0, 0, 0, 255);
	glVertex2i(200, 100);
	glVertex2i(350, 100);
	glVertex2i(350, 200);
	glVertex2i(200, 200);
	glEnd();

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, g_vTextureIDs[2]);

	glBegin(GL_QUADS);
	glColor4ub(255, 0, 0, 255);
	glTexCoord2f(0.0f, g_vTextures[2].nMaxV);	glVertex2i(10, 10);

	glTexCoord2f(g_vTextures[2].nMaxU, 
		g_vTextures[2].nMaxV);					glVertex2i(20, 10); 
	glTexCoord2f(g_vTextures[2].nMaxU, 0.0f); 	glVertex2i(20, 20);
	glTexCoord2f(0.0f, 0.0f);					glVertex2i(10, 20);
	glEnd();

	glDisable(GL_TEXTURE_2D);

	glFlush();

	
 
    SwapBuffers(g_hDC); 
}
Example #7
0
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};

    pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(),
                               has_render_texture ? pb_attribs : 0);
    if (!pbuf) {
        // try again without the render_texture extension
        pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(), 0);
        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;
}
Example #8
0
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE ignoreMe0, LPSTR ignoreMe1, INT ignoreMe2)
{
	HRESULT hr = S_OK;
	HWND hWnd = NULL;
	HDC hDC = NULL;
	HGLRC hRC = NULL;
	MSG msg = {};
	PIXELFORMATDESCRIPTOR pfd;
	
    LARGE_INTEGER previousTime;
    LARGE_INTEGER freqTime;
	double aveDeltaTime = 0.0;

    LPCSTR wndName = "Flow Snake";

	IFC( InitWindow(hWnd, g_width, g_height, wndName) );
    hDC = GetDC(hWnd);

    // Create the GL context.
    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 = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;
    int pixelFormat = ChoosePixelFormat(hDC, &pfd);
	SetPixelFormat(hDC, pixelFormat, &pfd);
    
	hRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hRC);

	IFC( Init() );

    QueryPerformanceFrequency(&freqTime);
    QueryPerformanceCounter(&previousTime);
	
	// -------------------
    // Start the Game Loop
    // -------------------
    while (msg.message != WM_QUIT)
    {
        if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg);
        }
        else
        {
            LARGE_INTEGER currentTime;
            __int64 elapsed;
            double deltaTime;

            QueryPerformanceCounter(&currentTime);
            elapsed = currentTime.QuadPart - previousTime.QuadPart;
            deltaTime = double(elapsed) / freqTime.QuadPart;
			aveDeltaTime = aveDeltaTime * 0.9 + 0.1 * deltaTime;
            previousTime = currentTime;

			IFC( Update(deltaTime) );

			Render();
            SwapBuffers(hDC);
            if (glGetError() != GL_NO_ERROR)
            {
                Error("OpenGL error.\n");
            }
        }
    }

Cleanup:
	if(hRC)  wglDeleteContext(hRC);
	if(hDC)  ReleaseDC(hWnd, hDC);
	if(hWnd) DestroyWindow(hWnd);

	char strBuf[256];
	sprintf_s(strBuf, "Average frame duration = %.3f ms\n", aveDeltaTime*1000.0f); 
	OutputDebugString(strBuf);

    return FAILED(hr);
}
Example #9
0
//-----------------------------------------------------------------------------
// Name: InitOpenGL()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT
COpenGL::InitOpenGL( COscillDlg *pCWnd )
{
    PIXELFORMATDESCRIPTOR   pfd;
    
    m_pCDrawWnd = pCWnd->GetDlgItem( IDC_DRAWFRAME );

    m_pDC = new CClientDC( m_pCDrawWnd );
    if( NULL == m_pDC )
    {
        return RptError( pCWnd->m_hWnd, FALSE, "GetDC Failed" );
    }
    
    if( !SetupPixelFormat( pCWnd->m_hWnd ) )
        return FALSE;

    int nIndex = GetPixelFormat( m_pDC->GetSafeHdc() );
    DescribePixelFormat( m_pDC->GetSafeHdc(), nIndex, sizeof(pfd), &pfd );

    m_hDC = m_pDC->GetSafeHdc();
    m_hRC1 = wglCreateContext( m_pDC->GetSafeHdc() );
//	m_hRC2 = wglCreateContext( m_pDC->GetSafeHdc() );
	wglMakeCurrent( m_hDC, m_hRC1 );
//	wglShareLists( m_hRC2, m_hRC1 );

    glClearDepth( 1.0f );
    glEnable( GL_DEPTH_TEST );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    
	glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	gluOrtho2D( GLLEFT, GLRIGHT, GLBOTTOM, GLTOP );
    
    CRect   rcDrawFrame;
    GetWindowRect( m_pCDrawWnd->m_hWnd, &rcDrawFrame );

// 	TRACE( "%d,%d,%d,%d\r\n", rcDrawFrame.left,
// 							  rcDrawFrame.top, 
// 							  rcDrawFrame.right,
// 							  rcDrawFrame.bottom );

    rcDrawFrame.SetRect( rcDrawFrame.left + 3,
                         rcDrawFrame.top + 3,
                         rcDrawFrame.right - 3,
                         rcDrawFrame.bottom - 3 );
	
	int nWidth = (int)( ( rcDrawFrame.Height() - 16 ) * 2.3 );

	if ( nWidth > rcDrawFrame.Width() - 20 )
	{
		nWidth = rcDrawFrame.Width() - 20;
	}

	int xMargin = ( rcDrawFrame.Width() - nWidth ) / 2;

    glViewport(  xMargin, 5, nWidth, rcDrawFrame.Height() - 17 );


    glEnable( GL_SCISSOR_TEST );
    glScissor( xMargin, 5, nWidth, rcDrawFrame.Height() - 17 );
    
	wglMakeCurrent( NULL, NULL );

	m_bDspyThreadRunning = true;
	m_pDspyThread = AfxBeginThread( DspyThreadFunc, &m_sDspyThreadPara/*, THREAD_PRIORITY_HIGHEST*/ );

    return TRUE;
}
Example #10
0
bool CreateGLWindow(const char* title, int width, int height, int bits, bool fullscreenFlag)
{
    int pixelFormat = 0;
    DWORD windowExStyle;
    DWORD windowStyle;
    RECT windowRect;

    windowRect.left = 0;
    windowRect.right = width;
    windowRect.top = 0;
    windowRect.bottom = height;

    g_Params.m_Fullscreen = fullscreenFlag;
    g_Params.m_Instance = GetModuleHandle(NULL);

    WNDCLASS wc;
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = g_Params.m_Instance;
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = NULL;
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "SeleneWindow";

    if (!RegisterClass(&wc))
    {
        MessageBox(NULL, "Could not register class!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    if (g_Params.m_Fullscreen)
    {
        DEVMODE screenSettings;
        memset(&screenSettings, 0, sizeof(screenSettings));
        screenSettings.dmSize = sizeof(screenSettings);
        screenSettings.dmPelsWidth = width;
        screenSettings.dmPelsHeight = height;
        screenSettings.dmBitsPerPel = bits;
        screenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
        if (ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
        {
            if (MessageBox(NULL, "Could not switch to fullscreen! Run in window?",
                           "Error",
                           MB_YESNO | MB_ICONEXCLAMATION) == MB_YESNO)
            {
                g_Params.m_Fullscreen = false;
            }
            else
            {
                MessageBox(NULL, "Progam will quit.", "Error", MB_OK | MB_ICONEXCLAMATION);
                return false;
            }
        }
    }

    if (g_Params.m_Fullscreen)
    {
        windowExStyle = WS_EX_APPWINDOW;
        windowStyle = WS_POPUP;
        ShowCursor(false);
    }
    else
    {
        windowExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
        windowStyle = WS_OVERLAPPEDWINDOW;
    }

    AdjustWindowRectEx(&windowRect, windowStyle, false, windowExStyle);

    g_Params.m_Wnd = CreateWindowEx(windowExStyle,
                                    "SeleneWindow",
                                    title,
                                    windowStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
                                    0,
                                    0,
                                    windowRect.right - windowRect.left,
                                    windowRect.bottom - windowRect.top,
                                    NULL,
                                    NULL,
                                    g_Params.m_Instance,
                                    NULL);
    if (g_Params.m_Wnd == NULL)
    {
        KillGLWindow();
        MessageBox(NULL, "Window creation failed!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    static PIXELFORMATDESCRIPTOR pfd =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        bits,
        0, 0, 0, 0, 0, 0,
        0,
        0,
        0,
        0, 0, 0, 0,
        32,
        0,
        0,
        PFD_MAIN_PLANE,
        0,
        0, 0, 0
    };

    g_Params.m_DC = GetDC(g_Params.m_Wnd);
    if (g_Params.m_DC == NULL)
    {
        KillGLWindow();
        MessageBox(NULL, "Could not get DC!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    pixelFormat = ChoosePixelFormat(g_Params.m_DC, &pfd);
    if (pixelFormat == 0)
    {
        KillGLWindow();
        MessageBox(NULL, "Could not find requested pixel format!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    if (!SetPixelFormat(g_Params.m_DC, pixelFormat, &pfd))
    {
        KillGLWindow();
        MessageBox(NULL, "Could not set pixel format!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    g_Params.m_RC = wglCreateContext(g_Params.m_DC);
    if (g_Params.m_RC == NULL)
    {
        KillGLWindow();
        MessageBox(NULL, "Could not create RC!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    if (!wglMakeCurrent(g_Params.m_DC, g_Params.m_RC))
    {
        KillGLWindow();
        MessageBox(NULL, "Could not activate RC!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    ShowWindow(g_Params.m_Wnd, SW_SHOW);
    SetForegroundWindow(g_Params.m_Wnd);
    SetFocus(g_Params.m_Wnd);

    ASSERT(g_Params.m_pApp != NULL, "App is null!");
    CGraphics* pGraphics = g_Params.m_pApp->GetGraphics();
    ASSERT(pGraphics != NULL, "Graphics is null!");
    pGraphics->PrepareView(width, height);

    if (!pGraphics->Init())
    {
        KillGLWindow();
        MessageBox(NULL, "Could not init Graphics!", "Error", MB_OK | MB_ICONERROR);
        return false;
    }

    return true;
}
Example #11
0
	Window::Window(const char* _name, int32_t _width, int32_t _height, int32_t _xpos, int32_t _ypos, uint32_t _options)
		: m_inputHandler(new InputHandler())
		, m_initialized(false)
		, m_active(false){
		TCHAR* windowName = 0;
		m_windowPlacement.length = sizeof(WINDOWPLACEMENT);

		windowName = (TCHAR*)_strdup(_name);
		WNDCLASSEX windowClass = {
			sizeof(WNDCLASSEX),
			CS_CLASSDC,
			(WNDPROC)WndProc,
			0, 0,
			GetModuleHandle(nullptr),
			LoadIcon(NULL, IDI_WINLOGO),
			LoadCursor(0, IDC_ARROW),
			nullptr,
			nullptr,
			windowName
		};

		if (!RegisterClassEx(&windowClass)){
			std::cerr << "Failed to register Window class. RegisterClassEx returned FALSE\n";
			return;
		}

		auto btst = [](uint32_t _reg, uint32_t _mask) { return (_reg & _mask) != 0; };

		int32_t multisample = (btst(_options, MULTISAMPLE2) ? 2 :
			(btst(_options, MULTISAMPLE4) ? 4 :
			(btst(_options, MULTISAMPLE8) ? 8 :
			(btst(_options, MULTISAMPLE16) ? 16 :
			(btst(_options, MULTISAMPLE32) ? 32 : 0)))));

		const int32_t rgbbits = (btst(_options, RGB16) ? 16 :
			(btst(_options, RGB24) ? 24 :
			(btst(_options, RGB32) ? 32 :
			(btst(_options, RGB64) ? 64 : 32))));

		const int32_t alphabits = (btst(_options, ALPHA4) ? 4 :
			(btst(_options, ALPHA8) ? 8 :
			(btst(_options, ALPHA12) ? 12 :
			(btst(_options, ALPHA16) ? 16 : 0))));

		const int32_t depthbits = (btst(_options, DEPTH8) ? 8 :
			(btst(_options, DEPTH16) ? 16 :
			(btst(_options, DEPTH24) ? 24 :
			(btst(_options, DEPTH32) ? 32 : 24))));

		const int32_t stencilbits = (btst(_options, STENCIL4) ? 4 :
			(btst(_options, STENCIL8) ? 8 :
			(btst(_options, STENCIL16) ? 16 : 8)));

		if (!createWindow(windowName, windowName, WS_OVERLAPPEDWINDOW, _xpos, _ypos, _width, _height)){
			std::cerr << "Failed to create Window CreateWindowEx returned FALSE\n";
			return;
		}
		m_active = true;

		PIXELFORMATDESCRIPTOR pfd = {
			sizeof(PIXELFORMATDESCRIPTOR),  //  size of this pfd  
			1,                     // version number  
			PFD_DRAW_TO_WINDOW |   // support window  
			PFD_SUPPORT_OPENGL |   // support OpenGL  
			(btst(_options, DOUBLE_BUFFER) ? PFD_DOUBLEBUFFER : 0) |   // double buffered
			PFD_GENERIC_ACCELERATED,
			PFD_TYPE_RGBA,         // RGBA type  
			rgbbits,               // 24-bit color depth  
			0, 0, 0, 0, 0, 0,      // color bits ignored  
			alphabits,             // no alpha buffer  
			0,                     // shift bit ignored  
			0,                     // no accumulation buffer  
			0, 0, 0, 0,            // accum bits ignored  
			depthbits,             // 32-bit z-buffer      
			stencilbits,           // no stencil buffer  
			0,                     // no auxiliary buffer  
			PFD_MAIN_PLANE,        // main layer  
			0,                     // reserved  
			0, 0, 0                // layer masks ignored  
		};

		int32_t nPixelFormat = ChoosePixelFormat(m_hdc, &pfd);
		if (nPixelFormat == 0 || SetPixelFormat(m_hdc, nPixelFormat, &pfd) <= 0){
			GetLastError();
			std::cerr << "Error " << GetLastError() << ": Cannot find hardware accelerated OpenGL pixel format \n";
			return;
		}

		int32_t majorVersion = -1, minorVersion = -1;

		HGLRC dummyContext = wglCreateContext(m_hdc);
		if (dummyContext == 0){
			std::cerr << "Cannot create basic OpenGL context\n";
			return;
		}

		wglMakeCurrent(m_hdc, dummyContext);

		const GLubyte*(GL_FUNCPTR*_tempglGetString)(GLenum) = (const GLubyte*(GL_FUNCPTR*)(GLenum))GetGLProcAddress("glGetString");
		const GLubyte* str = _tempglGetString(GL_VERSION);
		sscanf_s((char*)str, "%d.%d", &majorVersion, &minorVersion);

		int32_t fails = LoadOpenGLFunctions(btst(_options, CORE_PROFILE));


		DeleteDC(m_hdc);
		DestroyWindow(m_hwnd);
		if (!createWindow(windowName, windowName, WS_OVERLAPPEDWINDOW, _xpos, _ypos, _width, _height)){
			std::cerr << "Cannot re-create the Window.\n";
			return;
		}

		//Check Extensions

		typedef BOOL(WINAPI *FPCPFARB)(HDC, const int32_t*, const float*, uint32_t, int32_t*, uint32_t*);
		typedef BOOL(WINAPI *FPGPFARB)(HDC, int32_t, int32_t, uint32_t, const int32_t*, int32_t*);

		FPCPFARB wglChoosePixelFormatARB = (FPCPFARB)wglGetProcAddress("wglChoosePixelFormatARB");
		FPGPFARB wglGetPixelFormatAttribivARB = (FPGPFARB)wglGetProcAddress("wglGetPixelFormatAttribivARB");

		int32_t pixelFormatAttribList[] = {
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
			WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
			WGL_DOUBLE_BUFFER_ARB, btst(_options, DOUBLE_BUFFER),
			WGL_STEREO_ARB, btst(_options, STEREO),
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
			WGL_COLOR_BITS_ARB, rgbbits,
			WGL_DEPTH_BITS_ARB, depthbits,
			WGL_STENCIL_BITS_ARB, stencilbits,
			WGL_SAMPLE_BUFFERS_ARB, ((multisample > 0) ? 1 : 0),
			WGL_SAMPLES_ARB, multisample,
			0
		};

		const int32_t pixelFormatAttribListSize = sizeof(pixelFormatAttribList) / sizeof(int32_t);
		int32_t pixelFormats[255];
		UINT numFormats = 0;

		wglChoosePixelFormatARB(m_hdc, pixelFormatAttribList, nullptr, 255, &pixelFormats[0], &numFormats);
		while (numFormats <= 0 && multisample > 0){
			multisample >>= 1;
			pixelFormatAttribList[pixelFormatAttribListSize - 2] = multisample;
			pixelFormatAttribList[pixelFormatAttribListSize - 4] = (multisample > 0 ? 1 : 0);
			std::cout << "Unable to set pixel format. Trying: MSAAx" << multisample << "...";
			wglChoosePixelFormatARB(m_hdc, pixelFormatAttribList, nullptr, 255, &pixelFormats[0], &numFormats);
			std::cout << (numFormats <= 0 ? "failed\n" : "ok\n");
		}

		if (numFormats <= 0){
			std::cout << "Cannot find pixel format \n";
			return;
		}


		PIXELFORMATDESCRIPTOR dummy;
		memset(&dummy, 0, sizeof(PIXELFORMATDESCRIPTOR));
		dummy.nSize = sizeof(PIXELFORMATDESCRIPTOR);
		if (SetPixelFormat(m_hdc, pixelFormats[0], &dummy) <= 0){
			std::cout << "Cannot set the desired pixel format \n " << GetLastError() << std::endl;
			return;
		}


		if (multisample){
			glEnable(GL_MULTISAMPLE);
		}


		ShowWindow(m_hwnd, SW_SHOW);

		/*if (!CheckWGLExtension("WGL_ARB_create_context")){

		}*/

		typedef HGLRC(WINAPI * FPCCAARB)(HDC, HGLRC, const int32_t*);
		FPCCAARB wglCreateContextAttribsARB = (FPCCAARB)wglGetProcAddress("wglCreateContextAttribsARB");


		std::vector<int32_t> attribs;
		attribs.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
		attribs.push_back(majorVersion);
		attribs.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
		attribs.push_back(minorVersion);
		if (btst(_options, DEBUG_CONTEXT)){
			attribs.push_back(WGL_CONTEXT_FLAGS_ARB);
			attribs.push_back(WGL_CONTEXT_DEBUG_BIT_ARB);
		}
		if (btst(_options, CORE_PROFILE)){
			//if (CheckWGLExtension("WGL_ARB_create_context_profile")){
			    attribs.push_back(WGL_CONTEXT_FLAGS_ARB);
			    attribs.push_back(WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB);
			    attribs.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
			    attribs.push_back(WGL_CONTEXT_CORE_PROFILE_BIT_ARB);
			//}
		}
		else{
			attribs.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
			attribs.push_back(WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB);
		}
		attribs.push_back(0);

		HGLRC hrc = wglCreateContextAttribsARB(m_hdc, nullptr, &attribs[0]);
		if (hrc <= 0){
			std::cerr << "Cannot create OpenGL context.. \n";
			return;
		}

		wglMakeCurrent(nullptr, nullptr);
		wglDeleteContext(dummyContext);
		wglMakeCurrent(m_hdc, hrc);

		if (fails == 0){
			std::cout << "OpenGL Context successfully initialized. Version " << majorVersion << "." << minorVersion << std::endl;
		}
		else{
			std::cout << "OpenGL Context Created, but failed to load " << fails << " functions. Version " << majorVersion << "." << minorVersion << std::endl;
		}
		//list of OpenGL Extensions
		static const char * (WINAPI *wglGetExtensionsStringARB)(HDC) = NULL;
		wglGetExtensionsStringARB = (const char * (WINAPI *)(HDC))GetGLProcAddress("wglGetExtensionsStringARB");
		std::cout << wglGetExtensionsStringARB(GetDC(GetDesktopWindow())) << std::endl;

		typedef BOOL(WINAPI* FPWGLSIEXT)(int);
		static FPWGLSIEXT wglSwapIntervalEXT = (FPWGLSIEXT)wglGetProcAddress("wglSwapIntervalEXT");

		if (wglSwapIntervalEXT){
			if (btst(_options, FRAME_SYNC))
				wglSwapIntervalEXT(1);
			else if (btst(_options, ADAPTIVE_FRAME_SYNC))
				wglSwapIntervalEXT(-1);
			else
				wglSwapIntervalEXT(0);
		}
		else{
			std::cout << "WARNING: Cannot set the FrameSync option. Using default Driver settings. \n";
		}


		SetWindowLong(m_hwnd, GWLP_USERDATA, (long)this);
		m_initialized = true;

//        setFullscreen(btst(_options, FULLSCREEN));
		delete[] windowName;
	}
	void Win32Context::endCurrent()
	{
		wglMakeCurrent(NULL, NULL);
	}
 void Win32Context::setCurrent()
 {
      wglMakeCurrent(mHDC, mGlrc);      
 }
Example #14
0
GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
                              unsigned char layer_type )
{
#if defined(_WIN32_WCE)
    return GL_TRUE;
#else
    PIXELFORMATDESCRIPTOR pfd;
    PIXELFORMATDESCRIPTOR* ppfd = &pfd;
    int pixelformat;
    HDC current_hDC;
    GLboolean success;

    if (checkOnly)
      current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL);
    else
      current_hDC = window->Window.pContext.Device;

    fghFillPFD( ppfd, current_hDC, layer_type );
    pixelformat = ChoosePixelFormat( current_hDC, ppfd );

    /* windows hack for multismapling/sRGB */
    if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) ||
         ( fgState.DisplayMode & GLUT_SRGB ) )
    {        
        HGLRC rc, rc_before=wglGetCurrentContext();
        HWND hWnd;
        HDC hDC, hDC_before=wglGetCurrentDC();
        WNDCLASS wndCls;

        /* create a dummy window */
        ZeroMemory(&wndCls, sizeof(wndCls));
        wndCls.lpfnWndProc = DefWindowProc;
        wndCls.hInstance = fgDisplay.pDisplay.Instance;
        wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
        wndCls.lpszClassName = _T("FREEGLUT_dummy");
        RegisterClass( &wndCls );

        hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.pDisplay.Instance, 0 );
        hDC=GetDC(hWnd);
        SetPixelFormat( hDC, pixelformat, ppfd );

        rc = wglCreateContext( hDC );
        wglMakeCurrent(hDC, rc);

        if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) )
        {
            PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc =
              (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
            if ( wglChoosePixelFormatARBProc )
            {
                int attributes[100];
                int iPixelFormat;
                BOOL bValid;
                float fAttributes[] = { 0, 0 };
                UINT numFormats;
                fghFillPixelFormatAttributes( attributes, ppfd );
                bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats);

                if ( bValid && numFormats > 0 )
                {
                    pixelformat = iPixelFormat;
                }
            }
        }

        wglMakeCurrent( hDC_before, rc_before);
        wglDeleteContext(rc);
        ReleaseDC(hWnd, hDC);
        DestroyWindow(hWnd);
        UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.pDisplay.Instance);
    }

    success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) );

    if (checkOnly)
        DeleteDC(current_hDC);

    return success;
#endif /* defined(_WIN32_WCE) */
}
Example #15
0
void ContextGL_Win::release_current() {


	wglMakeCurrent(hDC,NULL);

}
Example #16
0
void EnableDrawing (HGLRC *hRC)
{
    WindowResizedCallback = &WindowResized;
    /**
     * Edited by Cool Breeze on 16th October 2013
     * + Updated the Pixel Format to support 24-bitdepth buffers
     * + Correctly create a GL 3.x compliant context
     */
    HGLRC LegacyRC;
    PIXELFORMATDESCRIPTOR pfd;
    int iFormat;

    enigma::window_hDC = GetDC (hWnd);
    ZeroMemory (&pfd, sizeof (pfd));
    pfd.nSize = sizeof (pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 24;
    pfd.cDepthBits = 24;
    pfd.iLayerType = PFD_MAIN_PLANE;
    iFormat = ChoosePixelFormat (enigma::window_hDC, &pfd);

    if (iFormat==0) {
        show_error("Failed to set the format of the OpenGL graphics device.",1);
    }

    SetPixelFormat ( enigma::window_hDC, iFormat, &pfd );
    LegacyRC = wglCreateContext( enigma::window_hDC );
    wglMakeCurrent( enigma::window_hDC, LegacyRC );

    // -- Initialise GLEW
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        return;
    }

    // -- Define an array of Context Attributes
    int attribs[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
#ifdef DEBUG_MODE
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB,
#else
        WGL_CONTEXT_FLAGS_ARB, 0,
#endif
        0
    };

    if ( wglewIsSupported("WGL_ARB_create_context") )
    {
        *hRC = wglCreateContextAttribsARB( enigma::window_hDC,0, attribs );
        wglMakeCurrent( NULL,NULL );
        wglDeleteContext( LegacyRC );
        wglMakeCurrent(enigma::window_hDC, *hRC );
    }
    else // Unable to get a 3.3 Core Context, use the Legacy 1.x context
    {
        *hRC = LegacyRC;
    }

#ifdef DEBUG_MODE
    glDebugMessageCallbackARB((GLDEBUGPROCARB)&DebugCallbackARB, 0);
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
    printf("OpenGL version supported by this platform (%s): \n", glGetString(GL_VERSION));

    GLuint ids[] = { 131185 };
    glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DONT_CARE, 1, ids, GL_FALSE); //Disable notification about rendering HINTS like so:
    //OpenGL: Buffer detailed info: Buffer object 1 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations. [source=API type=OTHER severity=UNDEFINED (33387) id=131185]
#endif

    //TODO: This never reports higher than 8, but display_aa should be 14 if 2,4,and 8 are supported and 8 only when only 8 is supported
    glGetIntegerv(GL_MAX_SAMPLES_EXT, &enigma_user::display_aa);
}
Example #17
0
void ContextGL_Win::make_current() {

	wglMakeCurrent(hDC,hRC);
}
Example #18
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
int main()
{
	InitWindow();
	
	// 描画用インスタンスの生成
	g_renderer = ::EffekseerRendererGL::Renderer::Create( 2000 );
	
	// エフェクト管理用インスタンスの生成
	g_manager = ::Effekseer::Manager::Create( 2000 );

	// 描画用インスタンスから描画機能を設定
	g_manager->SetSpriteRenderer( g_renderer->CreateSpriteRenderer() );
	g_manager->SetRibbonRenderer( g_renderer->CreateRibbonRenderer() );
	g_manager->SetRingRenderer( g_renderer->CreateRingRenderer() );
	g_manager->SetModelRenderer( g_renderer->CreateModelRenderer() );

	// 描画用インスタンスからテクスチャの読込機能を設定
	// 独自拡張可能、現在はファイルから読み込んでいる。
	g_manager->SetTextureLoader( g_renderer->CreateTextureLoader() );
	g_manager->SetModelLoader( g_renderer->CreateModelLoader() );

	// 音再生用インスタンスの生成
	g_sound = EffekseerSound::Sound::Create( 32 );

	// 音再生用インスタンスから再生機能を指定
	g_manager->SetSoundPlayer( g_sound->CreateSoundPlayer() );
	
	// 音再生用インスタンスからサウンドデータの読込機能を設定
	// 独自拡張可能、現在はファイルから読み込んでいる。
	g_manager->SetSoundLoader( g_sound->CreateSoundLoader() );

	// 視点位置を確定
	g_position = ::Effekseer::Vector3D( 10.0f, 5.0f, 20.0f );

	// 投影行列を設定
	g_renderer->SetProjectionMatrix(
		::Effekseer::Matrix44().PerspectiveFovRH_OpenGL( 90.0f / 180.0f * 3.14f, (float)g_window_width / (float)g_window_height, 1.0f, 50.0f ) );

	// カメラ行列を設定
	g_renderer->SetCameraMatrix(
		::Effekseer::Matrix44().LookAtRH( g_position, ::Effekseer::Vector3D( 0.0f, 0.0f, 0.0f ), ::Effekseer::Vector3D( 0.0f, 1.0f, 0.0f ) ) );
	
	// エフェクトの読込
	g_effect = Effekseer::Effect::Create( g_manager, (const EFK_CHAR*)L"test.efk" );

	// エフェクトの再生
	g_handle = g_manager->Play( g_effect, 0, 0, 0 );

	MainLoop();
	
	// エフェクトの停止
	g_manager->StopEffect( g_handle );

	// エフェクトの破棄
	ES_SAFE_RELEASE( g_effect );

	// 先にエフェクト管理用インスタンスを破棄
	g_manager->Destroy();

	// 次に音再生用インスタンスを破棄
	g_sound->Destory();

	// 次に描画用インスタンスを破棄
	g_renderer->Destory();

	// OpenALの解放
	alcDestroyContext(g_alcctx);
	alcCloseDevice(g_alcdev);
	
	g_alcctx = NULL;
	g_alcdev = NULL;

	// OpenGLの解放
	wglMakeCurrent( 0, 0 );
	wglDeleteContext( g_hGLRC );
	timeEndPeriod(1);

	// COMの終了処理
	CoUninitialize();

	return 0;
}
Example #19
0
void GLContext::Create( void* hwnd, const GLContextParam& param )
{
	this->hwnd = hwnd;
	hdc = (void*)GetDC((HWND)hwnd);

	// ------------------------------------------------------------

	// Create a dummy window

	WNDCLASSEX wc;
	const TCHAR* className = _T("DummyWindow");

	wc.cbSize        = sizeof(WNDCLASSEX);
	wc.style         = 0;
	wc.lpfnWndProc   = FakeWindowProcedure;
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = GetModuleHandle(NULL);
	wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wc.lpszMenuName  = NULL;
	wc.lpszClassName = className;
	wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

	if (!RegisterClassEx(&wc))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "RegisterClassEx");
	}

	HWND dummyHwnd = CreateWindowEx(
		WS_EX_CLIENTEDGE,
		className,
		_T("Dummy"),
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
		NULL, NULL, GetModuleHandle(NULL), NULL);

	if (dummyHwnd == NULL)
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "CreateWindowEx");
	}

	HDC dummyHdc = GetDC(dummyHwnd);

	// ------------------------------------------------------------

	// Setup pixel format for dummy context

	PIXELFORMATDESCRIPTOR pfd;

	memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));

	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 32;
	pfd.cDepthBits = 24;
	pfd.cStencilBits = 8;
	pfd.iLayerType = PFD_MAIN_PLANE;

	int pixelformat = ChoosePixelFormat(dummyHdc, &pfd);

	if (pixelformat == 0)
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "ChoosePixelFormat");
	}

	if (!SetPixelFormat(dummyHdc, pixelformat, &pfd))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "SetPixelFormat");
	}

	// ------------------------------------------------------------

	// Create a dummy context
	HGLRC dummyContext = wglCreateContext(dummyHdc);

	if (dummyContext == NULL)
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError,
			(boost::format("Failed to create context: wglCreateContext: %s") % GetLastError()).str());		
	}

	wglMakeCurrent(dummyHdc, dummyContext); 

	// Load extensions
	GLUtil::InitializeGlew(false);

	// Destroy the dummy window
	if (!DestroyWindow((HWND)dummyHwnd))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "DestroyWindow");
	}

	if (!UnregisterClass(className, GetModuleHandle(NULL)))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "UnregisterClass");
	}

	// ------------------------------------------------------------

	// Get version

	int major;
	int minor;

	if (param.MajorVersion == 0)
	{
		// Get version
		glGetIntegerv(GL_MAJOR_VERSION, &major);
		glGetIntegerv(GL_MINOR_VERSION, &minor);
	}
	else
	{
		major = param.MajorVersion;
		minor = param.MinorVersion;
	}

	// ------------------------------------------------------------

	// Setup pixel format for main context

	int pixelFormatAttr[] =
	{
		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, param.ColorBits,
		WGL_DEPTH_BITS_ARB, param.DepthBits,
		WGL_STENCIL_BITS_ARB, param.StencilBits,
		WGL_SAMPLE_BUFFERS_ARB, param.Multisample > 0 ? GL_TRUE : GL_FALSE,
		WGL_SAMPLES_ARB, param.Multisample,
		0
	};

	unsigned int numformats;

	if (!wglChoosePixelFormatARB((HDC)hdc, pixelFormatAttr, NULL, 1, &pixelformat, &numformats))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "wglChoosePixelFormatARB");
	}

	if (!SetPixelFormat((HDC)hdc, pixelformat, NULL))
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "SetPixelFormat");
	}

	// ------------------------------------------------------------

	// Create GL context

	int flags = 0;

	flags |= param.ForwardCompatible ? WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB : 0;
	flags |= param.DebugMode ? WGL_CONTEXT_DEBUG_BIT_ARB : 0;

	int contextAttr[] =
	{
		WGL_CONTEXT_MAJOR_VERSION_ARB, major,
		WGL_CONTEXT_MINOR_VERSION_ARB, minor,
		WGL_CONTEXT_FLAGS_ARB, flags,
		WGL_CONTEXT_PROFILE_MASK_ARB, (param.UseCoreProfile ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB),
		0
	};

	hglrc = (void*)wglCreateContextAttribsARB((HDC)hdc, 0, contextAttr);

	if (hglrc == NULL)
	{
		THROW_GL_EXCEPTION(GLException::RunTimeError, "wglCreateContextAttribsARB");
	}

	// ------------------------------------------------------------

	// Delete the dummy resources
	wglMakeCurrent(NULL, NULL);
	wglDeleteContext(dummyContext);

	// Enable current GL context
	wglMakeCurrent((HDC)hdc, (HGLRC)hglrc);

	// Initialize GLEW
	GLUtil::InitializeGlew(true);
}
Example #20
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InitWindow()
{
	WNDCLASS wndClass;
	wchar_t szClassNme[]      =  L"RuntimeSample";
	wndClass.style         = CS_HREDRAW | CS_VREDRAW;
	wndClass.lpfnWndProc   = WndProc;
	wndClass.cbClsExtra    = 0;
	wndClass.cbWndExtra    = 0;
	wndClass.hInstance     = GetModuleHandle(0);
	wndClass.hIcon         = NULL;
	wndClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wndClass.lpszMenuName  = NULL;
	wndClass.lpszClassName = szClassNme;
	RegisterClass(&wndClass);
	g_window_handle = CreateWindow(
		szClassNme,
		L"RuntimeSample",
		WS_SYSMENU,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		g_window_width,
		g_window_height,
		NULL,
		NULL,
		GetModuleHandle(0),
		NULL);
	ShowWindow( g_window_handle, true );
	UpdateWindow( g_window_handle );
	
	// COMの初期化
	CoInitializeEx( NULL, NULL );

	// OpenGLの初期化を行う
	g_hDC = GetDC( g_window_handle );

	PIXELFORMATDESCRIPTOR pfd =
	{
		sizeof(PIXELFORMATDESCRIPTOR), 1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,
		PFD_TYPE_RGBA, 24,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32,
		0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0
	};

	int pxfm = ChoosePixelFormat( g_hDC, &pfd );

	SetPixelFormat( g_hDC, pxfm, &pfd );

	g_hGLRC = wglCreateContext( g_hDC );

	wglMakeCurrent( g_hDC, g_hGLRC );

	GLenum glewIniterr = glewInit();
    assert ( glewIniterr == GLEW_OK );

	wglSwapIntervalEXT(1);
	glViewport( 0, 0, g_window_width, g_window_height );
	
	// OpenALデバイスを作成
	g_alcdev = alcOpenDevice(NULL);

	// OpenALコンテキストを作成
	g_alcctx = alcCreateContext(g_alcdev, NULL);

	alcMakeContextCurrent(g_alcctx);
}
Example #21
0
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
    unsigned int		PixelFormat;			// 保存查找匹配的结果
    WNDCLASS	wc;						// 窗口类结构
    DWORD		dwExStyle;				// 扩展窗口风格
    DWORD		dwStyle;				// 窗口风格
    RECT		WindowRect;				// 取得矩形的左上角和右下角的坐标值
    WindowRect.left=(long)0;			// 将Left   设为 0
    WindowRect.right=(long)width;		// 将Right  设为要求的宽度
    WindowRect.top=(long)0;				// 将Top    设为 0
    WindowRect.bottom=(long)height;		// 将Bottom 设为要求的高度

    fullscreen=fullscreenflag;			// 设置全局全屏标志

    hInstance			= GetModuleHandle(NULL);				// 取得我们窗口的实例
    wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// 移动时重画,并为窗口取得DC
    wc.lpfnWndProc		= (WNDPROC) WndProc;					// 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;									// GL不需要背景
    wc.lpszMenuName		= NULL;									// 不需要菜单
    wc.lpszClassName	= "OpenG";								// 设定类名字

    if (!RegisterClass(&wc))									// 尝试注册窗口类
    {
        MessageBox(NULL,"注册窗口失败","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;											// 退出并返回FALSE
    }

    if (fullscreen)												// 要尝试全屏模式吗?
    {
        DEVMODE dmScreenSettings;								// 设备模式
        memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// 确保内存清空为零
        dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Devmode 结构的大小
        dmScreenSettings.dmPelsWidth	= width;				// 所选屏幕宽度
        dmScreenSettings.dmPelsHeight	= height;				// 所选屏幕高度
        dmScreenSettings.dmBitsPerPel	= bits;					// 每象素所选的色彩深度
        dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

        // 尝试设置显示模式并返回结果。注: CDS_FULLSCREEN 移去了状态条
        if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
        {
            // 若模式失败,提供两个选项:退出或在窗口内运行。
            if (MessageBox(NULL,"全屏模式在当前显卡上设置失败!\n使用窗口模式?","NeHe G",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
            {
                //如果用户选择窗口模式,变量fullscreen 的值变为FALSE,程序继续运行
                fullscreen=FALSE;		// 选择窗口模式(Fullscreen=FALSE)
            }
            else
            {
                //如果用户选择退出,弹出消息窗口告知用户程序将结束。并返回FALSE告诉程序窗口未能成功创建。程序退出。
                MessageBox(NULL,"程序将被关闭","错误",MB_OK|MB_ICONSTOP);
                return FALSE;									// 退出并返回 FALSE
            }
        }
    }

    if (fullscreen)												// 仍处于全屏模式吗?
    {
        dwExStyle=WS_EX_APPWINDOW;								// 扩展窗体风格
        dwStyle=WS_POPUP;										// 窗体风格
        ShowCursor(FALSE);										// 隐藏鼠标指针
    }
    else
    {
        dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// 扩展窗体风格
        dwStyle=WS_OVERLAPPEDWINDOW;							// 窗体风格
    }

    AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// 调整窗口达到真正要求的大小

    // 创建窗口
    if (!(hWnd=CreateWindowEx(	dwExStyle,							// 扩展窗体风格
                                "OpenG",							// 类名字
                                title,								// 窗口标题
                                dwStyle |							// 必须的窗体风格属性
                                WS_CLIPSIBLINGS |					// 必须的窗体风格属性
                                WS_CLIPCHILDREN,					// 必须的窗体风格属性
                                0, 0,								// 窗口位置
                                WindowRect.right-WindowRect.left,	// 计算调整好的窗口宽度
                                WindowRect.bottom-WindowRect.top,	// 计算调整好的窗口高度
                                NULL,								// 无父窗口
                                NULL,								// 无菜单
                                hInstance,							// 实例
                                NULL)))								// 不向WM_CREATE传递任何东东
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"窗口创建错误","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    static	PIXELFORMATDESCRIPTOR pfd=				//pfd 告诉窗口我们所希望的东东,即窗口使用的像素格式
    {
        sizeof(PIXELFORMATDESCRIPTOR),				// 上述格式描述符的大小
        1,											// 版本号
        PFD_DRAW_TO_WINDOW |						// 格式支持窗口
        PFD_SUPPORT_OPENGL |						// 格式必须支持OpenGL
        PFD_DOUBLEBUFFER,							// 必须支持双缓冲
        PFD_TYPE_RGBA,								// 申请 RGBA 格式
        bits,										// 选定色彩深度
        0, 0, 0, 0, 0, 0,							// 忽略的色彩位
        0,											// 无Alpha缓存
        0,											// 忽略Shift Bit
        0,											// 无累加缓存
        0, 0, 0, 0,									// 忽略聚集位
        16,											// 16位 Z-缓存 (深度缓存)
        0,											// 无蒙板缓存
        0,											// 无辅助缓存
        PFD_MAIN_PLANE,								// 主绘图层
        0,											// 不使用重叠层
        0, 0, 0										// 忽略层遮罩
    };

    if (!(hDC=GetDC(hWnd)))							// 取得设备描述表了么?
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"不能创建一个窗口设备描述表","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Windows 找到相应的象素格式了吗?
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"不能创建一种相匹配的像素格式","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// 能够设置象素格式么?
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"不能设置像素格式","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    if (!(hRC=wglCreateContext(hDC)))				// 能否取得OpenGL渲染描述表?
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"不能创建OpenGL渲染描述表","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    if(!wglMakeCurrent(hDC,hRC))					// 尝试激活着色描述表
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"不能激活当前的OpenGL渲然描述表","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    ShowWindow(hWnd,SW_SHOW);						// 显示窗口
    SetForegroundWindow(hWnd);						// 略略提高优先级
    SetFocus(hWnd);									// 设置键盘的焦点至此窗口
    ReSizeGLScene(width, height);					// 设置透视 GL 屏幕

    if (!Init())									// 初始化新建的GL窗口
    {
        KillGLWindow();								// 重置显示区
        MessageBox(NULL,"初始化失败","错误",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;								// 返回 FALSE
    }

    return TRUE;									// 成功
}
Example #22
0
int CGLWindow::OnCreate(LPCREATESTRUCT lpCreateStruct) 
	{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// Get the device context
	m_hDC = ::GetDC(this->m_hWnd);
	
	// Set the Pixel Format
	SetPixelFormat(m_hDC, m_nPixelFormat, NULL);

	// Create the rendering context and make it current
	m_hRC = wglCreateContext(m_hDC);

	if(m_hRC != NULL)
		wglMakeCurrent(m_hDC, m_hRC);

	// Setup the context
	if(m_hRC != NULL)
		{
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glGenTextures(6, m_Sides);
		glEnable(GL_TEXTURE_2D);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_CULL_FACE);
		glFrontFace(GL_CCW);

	    BYTE *pBytes;
	    int nWidth, nHeight;
	
	    glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);

		// Load the texture objects
		pBytes = gltResourceBMPBits(IDB_BITMAP1, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[0]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		pBytes = gltResourceBMPBits(IDB_BITMAP2, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[1]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		pBytes = gltResourceBMPBits(IDB_BITMAP3, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[2]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		pBytes = gltResourceBMPBits(IDB_BITMAP4, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[3]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		pBytes = gltResourceBMPBits(IDB_BITMAP5, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[4]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		pBytes = gltResourceBMPBits(IDB_BITMAP6, &nWidth, &nHeight);
		glBindTexture(GL_TEXTURE_2D, m_Sides[5]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
			GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);

		}
		
	SetTimer(101, 30, NULL);

	return 0;
	}
Example #23
0
int GLinitialize()
{
 //----------------------------------------------------// 
#ifdef _WINDOWS
 HGLRC objectRC;
 // init
 dcGlobal = GetDC(hWWindow);                           // FIRST: dc/rc stuff
 objectRC = wglCreateContext(dcGlobal);
 GLCONTEXT=objectRC;
 wglMakeCurrent(dcGlobal, objectRC);
 // CheckWGLExtensions(dcGlobal);
 if(bWindowMode) ReleaseDC(hWWindow,dcGlobal);         // win mode: release dc again
#endif
 //----------------------------------------------------// 

 glViewport(rRatioRect.left,                           // init viewport by ratio rect
            iResY-(rRatioRect.top+rRatioRect.bottom),
            rRatioRect.right,
            rRatioRect.bottom);

 glScissor(0, 0, iResX, iResY);                        // init clipping (fullscreen)
 glEnable(GL_SCISSOR_TEST);

#ifndef OWNSCALE
 glMatrixMode(GL_TEXTURE);                             // init psx tex sow and tow if not "ownscale"
 glLoadIdentity();
 glScalef(1.0f/255.99f,1.0f/255.99f,1.0f);             // geforce precision hack
#endif

 glMatrixMode(GL_PROJECTION);                          // init projection with psx resolution
 glLoadIdentity();
 glOrtho(0,PSXDisplay.DisplayMode.x,
         PSXDisplay.DisplayMode.y, 0, -1, 1);

 if(iZBufferDepth)                                     // zbuffer?
  {
   uiBufferBits=GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT;
   glEnable(GL_DEPTH_TEST);
   glDepthFunc(GL_ALWAYS);
   iDepthFunc=1;
  }
 else                                                  // no zbuffer?
  {
   uiBufferBits=GL_COLOR_BUFFER_BIT;
   glDisable(GL_DEPTH_TEST);
  }

 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);                 // first buffer clear
 glClear(uiBufferBits);

 if(bUseLines)                                         // funny lines 
  {
   glPolygonMode(GL_FRONT, GL_LINE);
   glPolygonMode(GL_BACK, GL_LINE);
  }
 else                                                  // or the real filled thing
  {
   glPolygonMode(GL_FRONT, GL_FILL);
   glPolygonMode(GL_BACK, GL_FILL);
  }

 MakeDisplayLists();                                   // lists for menu/opaque
 GetExtInfos();                                        // get ext infos
 SetExtGLFuncs();                                      // init all kind of stuff (tex function pointers)

 glEnable(GL_ALPHA_TEST);                              // wanna alpha test

 if(!bUseAntiAlias)                                    // no anti-alias (default)
  {
   glDisable(GL_LINE_SMOOTH);
   glDisable(GL_POLYGON_SMOOTH);
   glDisable(GL_POINT_SMOOTH);
  }
 else                                                  // wanna try it? glitches galore...
  {
   glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
   glEnable(GL_LINE_SMOOTH);
   glEnable(GL_POLYGON_SMOOTH);
   glEnable(GL_POINT_SMOOTH);
   glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
   glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
   glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST);
  }

 ubGloAlpha=127;                                       // init some drawing vars
 ubGloColAlpha=127;
 TWin.UScaleFactor = 1;
 TWin.VScaleFactor = 1;
 bDrawMultiPass=FALSE;
 bTexEnabled=FALSE;
 bUsingTWin=FALSE;

 if(bDrawDither)  glEnable(GL_DITHER);                 // dither mode
 else             glDisable(GL_DITHER);

 glDisable(GL_FOG);                                    // turn all (currently) unused modes off
 glDisable(GL_LIGHTING);
 glDisable(GL_LOGIC_OP);
 glDisable(GL_STENCIL_TEST);
 glDisable(GL_TEXTURE_1D);
 glDisable(GL_TEXTURE_2D);
 glDisable(GL_CULL_FACE);

 glPixelTransferi(GL_RED_SCALE, 1);                    // to be sure:
 glPixelTransferi(GL_RED_BIAS, 0);                     // init more OGL vals
 glPixelTransferi(GL_GREEN_SCALE, 1);
 glPixelTransferi(GL_GREEN_BIAS, 0);
 glPixelTransferi(GL_BLUE_SCALE, 1);
 glPixelTransferi(GL_BLUE_BIAS, 0);
 glPixelTransferi(GL_ALPHA_SCALE, 1);
 glPixelTransferi(GL_ALPHA_BIAS, 0);

#ifdef _WINDOWS
                                                       // detect Windows hw/sw mode (just for info)
 if(!strcmp("Microsoft Corporation",(LPTSTR)glGetString(GL_VENDOR)) &&
    !strcmp("GDI Generic",          (LPTSTR)glGetString(GL_RENDERER)))
      bGLSoft=TRUE;
 else bGLSoft=FALSE;

#else

 printf(glGetString(GL_VENDOR));                       // linux: tell user what is getting used
 printf("\n");
 printf(glGetString(GL_RENDERER));
 printf("\n");

#endif

 glFlush();                                            // we are done...
 glFinish();

 CreateScanLines();                                    // setup scanline stuff (if wanted)

 CheckTextureMemory();                                 // check available tex memory

 if(bKeepRatio) SetAspectRatio();                      // set ratio

 if(iShowFPS)                                          // user wants FPS display on startup?
  {
   ulKeybits|=KEY_SHOWFPS;                             // -> ok, turn display on
   szDispBuf[0]=0;
   BuildDispMenu(0);
  }

 bIsFirstFrame = FALSE;                                // we have survived the first frame :)

 return 0;
}
Example #24
0
	int Create(){
		GLuint PixelFormat;
		WNDCLASS wc;
		RECT WindowRect;
		WindowRect.left = WindowRect.top = 0;
		WindowRect.right = mWidth;
		WindowRect.bottom = mHeight;

		mInstance = GetModuleHandle(NULL);
		wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.lpfnWndProc = (WNDPROC)WndProc;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = mInstance;
		wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
		wc.hCursor = LoadCursor(NULL, IDC_ARROW);
		wc.hbrBackground = NULL;
		wc.lpszMenuName = NULL;
		wc.lpszClassName = mClassName;

		if(!RegisterClass(&wc)) return FALSE;

		AdjustWindowRectEx(&WindowRect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE);

		mHWND = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, mClassName, mTitle, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, mInstance, (LPVOID)this);

		if(!mHWND){
			Destroy();
			return FALSE;
		}

		static	PIXELFORMATDESCRIPTOR pfd = {
			sizeof(PIXELFORMATDESCRIPTOR),
			1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 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
		};

		mHDC = GetDC(mHWND);
		if(!mHDC){
			Destroy();
			return FALSE;
		}

		PixelFormat = ChoosePixelFormat(mHDC, &pfd);
		if(!PixelFormat){
			Destroy();
			return FALSE;
		}

		if(!SetPixelFormat(mHDC, PixelFormat, &pfd)){
			Destroy();
			return FALSE;
		}

		mHRC = wglCreateContext(mHDC);

		if(!mHRC){
			Destroy();
			return FALSE;
		}

		if(!wglMakeCurrent(mHDC, mHRC)){
			Destroy();
			return FALSE;
		}

		ShowWindow(mHWND, SW_SHOW);
		SetForegroundWindow(mHWND);
		SetFocus(mHWND);
		ResizeGL(mWidth, mHeight);

		if(!InitGL()){
			Destroy();
			return FALSE;
		}

		mActive = TRUE;

		return TRUE;
	}
Example #25
0
HRESULT CVCamStream::OpenReceiver()
{
	HDC hdc = NULL;
	HWND hwnd = NULL;
	HGLRC hRc = NULL;
	char windowtitle[512];

	glContext = wglGetCurrentContext();

	// Once created it seems stable and retained
	if(glContext == NULL) {

		// We only need an OpenGL context with no window
		hwnd = GetForegroundWindow(); // Any window will do - we don't render to it
		if(!hwnd) { 
			printf("InitOpenGL error 1\n");
			MessageBoxA(NULL, "Error 1\n", "InitOpenGL", MB_OK);
			return S_FALSE; 
		}

		hdc = GetDC(hwnd);
		if(!hdc) { 
			printf("InitOpenGL error 2\n"); 
			MessageBoxA(NULL, "Error 2\n", "InitOpenGL", MB_OK); 
			return S_FALSE; 
		}
		GetWindowTextA(hwnd, windowtitle, 256); // debug

		PIXELFORMATDESCRIPTOR pfd;
		ZeroMemory( &pfd, sizeof( pfd ) );
		pfd.nSize = sizeof( pfd );
		pfd.nVersion = 1;
		pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.cColorBits = 32;
		pfd.cDepthBits = 16;
		pfd.iLayerType = PFD_MAIN_PLANE;
		int iFormat = ChoosePixelFormat(hdc, &pfd);
		if(!iFormat) { 
			printf("InitOpenGL error 3\n"); 
			MessageBoxA(NULL, "Error 3\n", "InitOpenGL", MB_OK);
			return S_FALSE; 
		}

		if(!SetPixelFormat(hdc, iFormat, &pfd)) { 
			printf("InitOpenGL error 4\n"); 
			MessageBoxA(NULL, "Error 4\n", "InitOpenGL", MB_OK); 
			return S_FALSE; 
		}

		hRc = wglCreateContext(hdc);
		if(!hRc) { 
			printf("InitOpenGL error 5\n"); 
			MessageBoxA(NULL, "Error 5\n", "InitOpenGL", MB_OK); 
			return S_FALSE; 
		}

		wglMakeCurrent(hdc, hRc);
		if(wglGetCurrentContext() == NULL) {
			printf("InitOpenGL error 6\n");
			MessageBoxA(NULL, "Error 6\n", "InitOpenGL", MB_OK);
			return S_FALSE; 
		}

		// Drop through to return true
		// printf("InitOpenGL : hwnd = %x (%s), hdc = %x, context = %x\n", hwnd, windowtitle, hdc, hRc);

		// int nCurAvailMemoryInKB = 0;
		// glGetIntegerv(0x9049, &nCurAvailMemoryInKB);
		// printf("Memory available [%i]\n", nCurAvailMemoryInKB);

		/*
		// Glut method
		// You need to create a rendering context BEFORE calling glutInit()
		// First you need to create a valid OpenGL rendering context and call glewInit() 
		// to initialize the extension entry points. 
		int argc = 1;
		char *argv = (char*)"vCam";
		char **vptr = &argv;
		glutInit(&argc, vptr);
		// In this case there is not be a rendering context. There is if an external window is present
		// but we don't know what it is. So create a window here but it will not show.
		glutCreateWindow("vCamGL");
		GLhdc = wglGetCurrentDC();
		GLhwnd = WindowFromDC(GLhdc);
		*/


	} // end no glcontext 

	
	#ifdef UseD3D9
	receiver.SetDX9(true);
	#else
	receiver.SetDX9(false); // Set to DX9 for compatibility with Version 1 apps
	#endif

	// This is a receiver so try to connect
	if(receiver.CreateReceiver(SharedMemoryName, senderWidth, senderHeight)) {
		return NO_ERROR;
	}

	return S_FALSE;

} // end OpenReceiver
//完成windows的CreateWindowEx函数系列,此函数名任取
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure|10成员窗口类别结构
	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

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= (HICON)LoadImage(NULL,"Data/i0.ico",IMAGE_ICON,0,0,LR_LOADFROMFILE);  // 加载一个外部图标
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	//全屏模式下的相关设置
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)		//如果全屏模式没有设置成功
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?|如果还在全屏模式需要一些辅助设置
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style|强制窗体位于最前
		dwStyle=WS_POPUP;										// Windows Style|没有边框
		ShowCursor(FALSE);										// Hide Mouse Pointer|隐藏鼠标指针
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size|调整绘图区域为设置的分辨率,即稍微扩大边框区域,仅对非全屏模式有效

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}
	//wglMakeCurrent(hDC, hRC)执行之后OpenGL窗口创建工作完成
	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen


	reset_model();

	//调用InitGL()
	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}
Example #27
0
	void GLContextWin32::Unbind( void)
	{
		wglMakeCurrent( NULL, NULL);
		m_currentGLContextBound = NULL;
	}
Example #28
0
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
	};

	if (!(hDC=GetDC(hWnd))) {
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return ERR_CANT_CREATE;								// Return FALSE
	}

	if (!(pixel_format=ChoosePixelFormat(hDC,&pfd)))	// 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
	}

	if(!SetPixelFormat(hDC,pixel_format,&pfd))		// 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
	}

	if (!(hRC=wglCreateContext(hDC)))				// 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 Adress for CreateContextAttribs", "ERROR",MB_OK|MB_ICONEXCLAMATION);
			wglDeleteContext(hRC);
			return ERR_CANT_CREATE;
		}

		HGLRC new_hRC;
		if (!(new_hRC=wglCreateContextAttribsARB(hDC,0, attribs)))
		{
			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;
}
Example #29
0
void VideoSettings::SetMode()
{
#ifdef _WINDOWS
	if (!hWnd)
		return;

	// Clear the rendering context
	wglMakeCurrent(NULL, NULL); 

	if (hRC) {
		wglDeleteContext(hRC);
		hRC = NULL;
	}

	if (hDC) {
		ReleaseDC(hWnd,hDC);
		hDC = NULL;
	}

	hDC = GetDC(hWnd);
	if (!hDC) {						// Did We Get A Device Context?
		wxLogMessage(wxT("Error: Can't Create A GL Device Context."));
		return;
	}
	
	GLboolean status;
	unsigned int numFormats;
	float fAttributes[] = { 0,0};
	std::vector<int> AttributeList;

	AttributeList.push_back(WGL_DRAW_TO_WINDOW_ARB);
	AttributeList.push_back(GL_TRUE);
	AttributeList.push_back(WGL_SUPPORT_OPENGL_ARB);
	AttributeList.push_back(GL_TRUE);
	AttributeList.push_back(WGL_ACCELERATION_ARB);
	AttributeList.push_back(curCap.hwAcc);
	AttributeList.push_back(WGL_COLOR_BITS_ARB);
	AttributeList.push_back(curCap.colour);
	AttributeList.push_back(WGL_ALPHA_BITS_ARB);
	AttributeList.push_back(curCap.alpha);
	AttributeList.push_back(WGL_DEPTH_BITS_ARB);
	AttributeList.push_back(curCap.zBuffer);
	//AttributeList.push_back(WGL_STENCIL_BITS_ARB);
	//AttributeList.push_back(curCap.stencil);
	AttributeList.push_back(WGL_DOUBLE_BUFFER_ARB);
	AttributeList.push_back(curCap.doubleBuffer);

	// 8229 being software mode
	if (curCap.hwAcc!=8229  && curCap.accum!=0) {
		AttributeList.push_back(WGL_ACCUM_BITS_ARB);
		AttributeList.push_back(curCap.accum);
	}

	if (curCap.aaSamples != 0 && supportAntiAlias) {
		AttributeList.push_back(WGL_SAMPLE_BUFFERS_ARB);
		AttributeList.push_back(GL_TRUE);
		AttributeList.push_back(WGL_SAMPLES_ARB);
		AttributeList.push_back(curCap.aaSamples);
	}
	AttributeList.push_back(0);
	AttributeList.push_back(0);
    

	status = wglChoosePixelFormatARB(hDC, &AttributeList[0], fAttributes, 1, &pixelFormat, &numFormats);
	if (status == GL_TRUE && numFormats) {
		if (SetPixelFormat(hDC, pixelFormat, &pfd) == FALSE) {
			//wxLogMessage(wxT("Error: Failed To Set Requested Pixel Format."));
			secondPass = true;
			return;
		}

		hRC = wglCreateContext(hDC);
		if (!hRC) {
			wxLogMessage(wxT("Error: Failed To Create OpenGL Context."));
			return;
		}
		
		render = true;
		SetCurrent();
	} else {
		// Error
		// Something went wrong,  fall back to the basic opengl setup
		GetAvailableMode();
	}
#endif
}
Example #30
0
GLboolean glewCreateContext (struct createParams* params)
{
    WNDCLASS wc;
    PIXELFORMATDESCRIPTOR pfd;
    /* register window class */
    ZeroMemory(&wc, sizeof(WNDCLASS));
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpfnWndProc = DefWindowProc;
    wc.lpszClassName = "GLEW";
    if (0 == RegisterClass(&wc)) return GL_TRUE;
    /* create window */
    wnd = CreateWindow("GLEW", "GLEW", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                       CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL);
    if (NULL == wnd) return GL_TRUE;
    /* get the device context */
    dc = GetDC(wnd);
    if (NULL == dc) return GL_TRUE;
    /* find pixel format */
    ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));
    if (params->pixelformat == -1) /* find default */
    {
        pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
        pfd.nVersion = 1;
        pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
        params->pixelformat = ChoosePixelFormat(dc, &pfd);
        if (params->pixelformat == 0) return GL_TRUE;
    }
    /* set the pixel format for the dc */
    if (FALSE == SetPixelFormat(dc, params->pixelformat, &pfd)) return GL_TRUE;
    /* create rendering context */
    rc = wglCreateContext(dc);
    if (NULL == rc) return GL_TRUE;
    if (FALSE == wglMakeCurrent(dc, rc)) return GL_TRUE;
    if (params->major || params->profile || params->flags)
    {
        HGLRC oldRC = rc;
        int contextAttrs[20];
        int i;

        wglewInit();

        /* Intel HD 3000 has WGL_ARB_create_context, but not WGL_ARB_create_context_profile */
        if (!wglewGetExtension("WGL_ARB_create_context"))
            return GL_TRUE;

        i = 0;
        if (params->major)
        {
            contextAttrs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
            contextAttrs[i++] = params->major;
            contextAttrs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB;
            contextAttrs[i++] = params->minor;
        }
        if (params->profile)
        {
            contextAttrs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB;
            contextAttrs[i++] = params->profile;
        }
        if (params->flags)
        {
            contextAttrs[i++] = WGL_CONTEXT_FLAGS_ARB;
            contextAttrs[i++] = params->flags;
        }
        contextAttrs[i++] = 0;
        rc = wglCreateContextAttribsARB(dc, 0, contextAttrs);

        if (NULL == rc) return GL_TRUE;
        if (!wglMakeCurrent(dc, rc)) return GL_TRUE;

        wglDeleteContext(oldRC);
    }
    return GL_FALSE;
}