Exemplo n.º 1
0
void z_ed3View::ShowTheCursor (void)
{
	while (ShowCursor (TRUE) < 0);
}
Exemplo n.º 2
0
void SingleOpenGLWindowImplT::Close()
{
#ifdef _WIN32
    // Release DirectInput.
    DirectInput.Release();

    // Rendering-Context zurückgeben.
    if (hRC)
    {
        // Vorher noch prüfen, ob es OpenGL-Fehler gab.
        while (true)
        {
            GLenum Error=glGetError();

            switch (Error)
            {
                case GL_NO_ERROR         : break;
                case GL_INVALID_ENUM     : MessageBox(NULL, "GL_INVALID_ENUM     ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                case GL_INVALID_VALUE    : MessageBox(NULL, "GL_INVALID_VALUE    ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                case GL_INVALID_OPERATION: MessageBox(NULL, "GL_INVALID_OPERATION", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                case GL_STACK_OVERFLOW   : MessageBox(NULL, "GL_STACK_OVERFLOW   ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                case GL_STACK_UNDERFLOW  : MessageBox(NULL, "GL_STACK_UNDERFLOW  ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                case GL_OUT_OF_MEMORY    : MessageBox(NULL, "GL_OUT_OF_MEMORY    ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
                default                  : MessageBox(NULL, "GL_UNKNOWN!!!       ", NULL, MB_OK | MB_ICONERROR | MB_TOPMOST); break;
            }

            if (Error==GL_NO_ERROR) break;
        }

        if (!wglMakeCurrent  (NULL, NULL)) MessageBox(NULL, "Unable to deactivate DC and RC.",      NULL, MB_OK | MB_ICONERROR);
        if (!wglDeleteContext(hRC)       ) MessageBox(NULL, "Unable to release rendering context.", NULL, MB_OK | MB_ICONERROR);

        hRC=NULL;
    }

    // Device-Context zurückgeben.
    if (hDC)
    {
        if (!ReleaseDC(hWindow, hDC)) MessageBox(NULL, "Unable to release device context.", NULL, MB_OK | MB_ICONERROR);
        hDC=NULL;
    }

    // Fenster schließen.
    if (hWindow)
    {
        if (!DestroyWindow(hWindow)) MessageBox(NULL, "Unable to destroy window.", NULL, MB_OK | MB_ICONERROR);
        hWindow=NULL;
    }

    // Fensterklasse abmelden. Dabei zurückgegebene Fehlercodes ignorieren.
    UnregisterClass("CafuMain", hInstance);

    // Standard-Display wiederherstellen.
    if (FullScreen)
    {
        ChangeDisplaySettings(NULL, 0);
        ShowCursor(true);
    }
#else
    // De-activate the invisible mouse cursor again (restore the previous visible cursor).
    XUndefineCursor(DisplayPtr, Win);

    // Turn on auto-repeat.
    // XAutoRepeatOn(DisplayPtr);

    // WARNING: Omitting the following line worked when this library was a static library.
    // When it became a shared library, the next call to glXMakeCurrent() caused a segmentation fault without this line.
    // That's strange. Probably it's just a driver bug on my machine, but I thought I'd better mention it...
    glXDestroyContext(DisplayPtr, RC);

    XCloseDisplay(DisplayPtr);
#endif

    // OpenGLWindow geschlossen.
    WindowIsOpen=false;
}
int Game_Init(void *parms)
{
// this function is where you do all the initialization
// for your game

    int index; // looping var

// start up DirectDraw (replace the parms as you desire)
    DDraw_Init2(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP,1);

// initialize directinput
    DInput_Init();

// acquire the keyboard
    DInput_Init_Keyboard();

// add calls to acquire other directinput devices here...

// initialize directsound and directmusic
    DSound_Init();
    DMusic_Init();

// hide the mouse
    if (!WINDOWED_APP)
        ShowCursor(FALSE);

// seed random number generator
    srand(Start_Clock());

    Open_Error_File("ERROR.TXT");

// initialize math engine
    Build_Sin_Cos_Tables();

// initialize the camera with 90 FOV, normalized coordinates
    Init_CAM4DV1(&cam,      // the camera object
                 CAM_MODEL_EULER, // the euler model
                 &cam_pos,  // initial camera position
                 &cam_dir,  // initial camera angles
                 &cam_target,      // no target
                 10.0,        // near and far clipping planes
                 12000.0,
                 120.0,      // field of view in degrees
                 WINDOW_WIDTH,   // size of final screen viewport
                 WINDOW_HEIGHT);

// set a scaling vector
    VECTOR4D_INITXYZ(&vscale,20.00,20.00,20.00);

// load all the objects in
    for (int index_obj=0; index_obj < NUM_OBJECTS; index_obj++)
    {
        Load_OBJECT4DV2_COB2(&obj_array[index_obj], object_filenames[index_obj],
                             &vscale, &vpos, &vrot, VERTEX_FLAGS_SWAP_YZ  |
                             VERTEX_FLAGS_TRANSFORM_LOCAL
                             /* VERTEX_FLAGS_TRANSFORM_LOCAL_WORLD*/,0 );

    } // end for index_obj

// set current object
    curr_object = 0;
    obj_work = &obj_array[curr_object];

// load in the scenery object that we will place all over the place
    Load_OBJECT4DV2_COB2(&obj_scene, "fire_cube01.cob",
                         &vscale, &vpos, &vrot, VERTEX_FLAGS_SWAP_YZ  |
                         VERTEX_FLAGS_TRANSFORM_LOCAL
                         /* VERTEX_FLAGS_TRANSFORM_LOCAL_WORLD*/, 0);

// position the scenery objects randomly
    for (index = 0; index < NUM_SCENE_OBJECTS; index++)
    {
        // randomly position object
        scene_objects[index].x = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
        scene_objects[index].y = RAND_RANGE(-200, 200);
        scene_objects[index].z = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
    } // end for

// set up lights
    Reset_Lights_LIGHTV2(lights2, MAX_LIGHTS);

// create some working colors
    white.rgba = _RGBA32BIT(255,255,255,0);
    gray.rgba  = _RGBA32BIT(100,100,100,0);
    black.rgba = _RGBA32BIT(0,0,0,0);
    red.rgba   = _RGBA32BIT(255,0,0,0);
    green.rgba = _RGBA32BIT(0,255,0,0);
    blue.rgba  = _RGBA32BIT(0,0,255,0);
    orange.rgba = _RGBA32BIT(255,128,0,0);
    yellow.rgba  = _RGBA32BIT(255,255,0,0);


// ambient light
    Init_Light_LIGHTV2(lights2,               // array of lights to work with
                       AMBIENT_LIGHT_INDEX,
                       LIGHTV2_STATE_ON,      // turn the light on
                       LIGHTV2_ATTR_AMBIENT,  // ambient light type
                       gray, black, black,    // color for ambient term only
                       NULL, NULL,            // no need for pos or dir
                       0,0,0,                 // no need for attenuation
                       0,0,0);                // spotlight info NA

    VECTOR4D dlight_dir = {-1,0,-1,1};

// directional light
    Init_Light_LIGHTV2(lights2,               // array of lights to work with
                       INFINITE_LIGHT_INDEX,
                       LIGHTV2_STATE_ON,      // turn the light on
                       LIGHTV2_ATTR_INFINITE, // infinite light type
                       black, gray, black,    // color for diffuse term only
                       NULL, &dlight_dir,     // need direction only
                       0,0,0,                 // no need for attenuation
                       0,0,0);                // spotlight info NA


    VECTOR4D plight_pos = {0,200,0,1};

// point light
    Init_Light_LIGHTV2(lights2,               // array of lights to work with
                       POINT_LIGHT_INDEX,
                       LIGHTV2_STATE_ON,      // turn the light on
                       LIGHTV2_ATTR_POINT,    // pointlight type
                       black, yellow, black,    // color for diffuse term only
                       &plight_pos, NULL,     // need pos only
                       0,.002,0,              // linear attenuation only
                       0,0,1);                // spotlight info NA


    VECTOR4D slight2_pos = {0,1000,0,1};
    VECTOR4D slight2_dir = {-1,0,-1,1};

// spot light2
    Init_Light_LIGHTV2(lights2,                  // array of lights to work with
                       SPOT_LIGHT2_INDEX,
                       LIGHTV2_STATE_ON,         // turn the light on
                       LIGHTV2_ATTR_SPOTLIGHT2,  // spot light type 2
                       black, red, black,        // color for diffuse term only
                       &slight2_pos, &slight2_dir, // need pos only
                       0,.001,0,                 // linear attenuation only
                       0,0,1);


// create lookup for lighting engine
    RGB_16_8_IndexedRGB_Table_Builder(DD_PIXEL_FORMAT565,  // format we want to build table for
                                      palette,             // source palette
                                      rgblookup);          // lookup table

// create the z buffer
    Create_Zbuffer(&zbuffer,
                   WINDOW_WIDTH,
                   WINDOW_HEIGHT,
                   ZBUFFER_ATTR_32BIT);

// create the alpha table
    RGB_Alpha_Table_Builder(NUM_ALPHA_LEVELS, rgb_alpha_table);

// load in the background
    Create_BOB(&background, 0,0,800,600,1, BOB_ATTR_VISIBLE | BOB_ATTR_SINGLE_FRAME, DDSCAPS_SYSTEMMEMORY, 0, 16);
    Load_Bitmap_File(&bitmap16bit, "nebred01.bmp");
    Load_Frame_BOB16(&background, &bitmap16bit,0,0,0,BITMAP_EXTRACT_MODE_ABS);
    Unload_Bitmap_File(&bitmap16bit);

// return success
    return(1);

} // end Game_Init
Exemplo n.º 4
0
HRESULT BKMainFrame::initDirectDraw()
{
	if ( display ) { delete display; display = NULL; }
	display = new CDisplay();

	if ( isFullScreenMode() ) {
		CDC* dc = CWnd::GetDesktopWindow()->GetDC();
		int bpp = dc->GetDeviceCaps( BITSPIXEL );
		CWnd::GetDesktopWindow()->ReleaseDC( dc );
		if ( display->CreateFullScreenDisplay( this, 512, 256, bpp ) != S_OK ) {
			AfxMessageBox( "Failed initializing DirectDraw." );
			return -1;
		}
		ModifyStyle( WS_OVERLAPPEDWINDOW, 0 );
		SetMenu( NULL );

		fullWindowWidth  = display->getSurfaceDesc()->dwWidth;
		fullWindowHeight = display->getSurfaceDesc()->dwHeight;
	} else {
		if ( display->CreateWindowedDisplay( this, bk_width, bk_height ) != S_OK ) {
			AfxMessageBox( "Failed initializing DirectDraw." );
			return -1;
		}
		ModifyStyle( 0, WS_OVERLAPPEDWINDOW );
		SetMenu( CMenu::FromHandle( ::LoadMenu( NULL, MAKEINTRESOURCE( IDR_MAINFRAME ) ) ) );
	}
	::SystemParametersInfo( SPI_GETWORKAREA, 0, &screenRect, 0 );
	updateBounds();
	ShowCursor( !fullScreenMode );

	bytePerPixel = display->getSurfaceDesc()->ddpfPixelFormat.dwRGBBitCount >> 3;
	if ( bytePerPixel > 1 ) {
		DWORD rMask = display->getSurfaceDesc()->ddpfPixelFormat.dwRBitMask;
		DWORD gMask = display->getSurfaceDesc()->ddpfPixelFormat.dwGBitMask;
		DWORD bMask = display->getSurfaceDesc()->ddpfPixelFormat.dwBBitMask;
		DWORD mask;
		rBits = 0;
		gBits = 0;
		bBits = 0;
		rZero = 0;
		gZero = 0;
		bZero = 0;
		mask = rMask;
		while ( (mask & 0x1) == 0 ) {
			mask = mask >> 1;
			rZero++;
		}
		while ( mask & 0x1 ) {
			mask = mask >> 1;
			rBits++;
		}
		mask = gMask;
		while ( (mask & 0x1) == 0 ) {
			mask = mask >> 1;
			gZero++;
		}
		while ( mask & 0x1 ) {
			mask = mask >> 1;
			gBits++;
		}
		mask = bMask;
		while ( (mask & 0x1) == 0 ) {
			mask = mask >> 1;
			bZero++;
		}
		while ( mask & 0x1 ) {
			mask = mask >> 1;
			bBits++;
		}
		rBits = 8 - rBits;
		gBits = 8 - gBits;
		bBits = 8 - bBits;
	}
static int window_init( WININFO *info )
{
	unsigned int	PixelFormat;
    DWORD			dwExStyle, dwStyle;
    DEVMODE			dmScreenSettings;
    RECT			rec;

    WNDCLASS		wc;

    ZeroMemory( &wc, sizeof(WNDCLASS) );
    wc.style         = CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.hInstance     = info->hInstance;
    wc.lpszClassName = info->wndclass;
	
    if( !RegisterClass(&wc) )
        return( 0 );

    if( info->full )
    {
        dmScreenSettings.dmSize       = sizeof(DEVMODE);
        dmScreenSettings.dmFields     = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
        dmScreenSettings.dmBitsPerPel = 24;
        dmScreenSettings.dmPelsWidth  = XRES;
        dmScreenSettings.dmPelsHeight = YRES;
        if( ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
            return( 0 );
        dwExStyle = WS_EX_APPWINDOW;
        dwStyle   = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
		ShowCursor( 0 );
    }
    else
    {
        dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
        dwStyle   = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU;
    }

    rec.left   = 0;
    rec.top    = 0;
    rec.right  = XRES;
    rec.bottom = YRES;
    AdjustWindowRect( &rec, dwStyle, 0 );

    info->hWnd = CreateWindowEx( dwExStyle, wc.lpszClassName, "avada kedabra!", dwStyle,
                               (GetSystemMetrics(SM_CXSCREEN)-rec.right+rec.left)>>1,
                               (GetSystemMetrics(SM_CYSCREEN)-rec.bottom+rec.top)>>1,
                               rec.right-rec.left, rec.bottom-rec.top, 0, 0, info->hInstance, 0 );
    if( !info->hWnd )
        return( 0 );
	hWnd = info->hWnd;

    if( !(info->hDC=GetDC(info->hWnd)) )
        return( 0 );

    if( !(PixelFormat=ChoosePixelFormat(info->hDC,&pfd)) )
        return( 0 );

    if( !SetPixelFormat(info->hDC,PixelFormat,&pfd) )
        return( 0 );

    if( !(info->hRC=wglCreateContext(info->hDC)) )
        return( 0 );

    if( !wglMakeCurrent(info->hDC,info->hRC) )
        return( 0 );
    
    return( 1 );
}
Exemplo n.º 6
0
//=============================================================================
// Destructor
//=============================================================================
Game::~Game()
{
    deleteAll();                // free all reserved memory
    ShowCursor(true);           // show cursor
}
Exemplo n.º 7
0
LRESULT CALLBACK
winWindowProc (HWND hwnd, UINT message, 
	       WPARAM wParam, LPARAM lParam)
{
  static winPrivScreenPtr	s_pScreenPriv = NULL;
  static winScreenInfo		*s_pScreenInfo = NULL;
  static ScreenPtr		s_pScreen = NULL;
  static HWND			s_hwndLastPrivates = NULL;
  static HINSTANCE		s_hInstance;
  static Bool			s_fTracking = FALSE;
  static unsigned long		s_ulServerGeneration = 0;
  static UINT			s_uTaskbarRestart = 0;
  int				iScanCode;
  int				i;

#if CYGDEBUG
  winDebugWin32Message("winWindowProc", hwnd, message, wParam, lParam);
#endif
  
  /* Watch for server regeneration */
  if (g_ulServerGeneration != s_ulServerGeneration)
    {
      /* Store new server generation */
      s_ulServerGeneration = g_ulServerGeneration;
    }

  /* Only retrieve new privates pointers if window handle is null or changed */
  if ((s_pScreenPriv == NULL || hwnd != s_hwndLastPrivates)
      && (s_pScreenPriv = GetProp (hwnd, WIN_SCR_PROP)) != NULL)
    {
#if CYGDEBUG
      winDebug ("winWindowProc - Setting privates handle\n");
#endif
      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
      s_pScreen = s_pScreenInfo->pScreen;
      s_hwndLastPrivates = hwnd;
    }
  else if (s_pScreenPriv == NULL)
    {
      /* For safety, handle case that should never happen */
      s_pScreenInfo = NULL;
      s_pScreen = NULL;
      s_hwndLastPrivates = NULL;
    }

  /* Branch on message type */
  switch (message)
    {
    case WM_TRAYICON:
      return winHandleIconMessage (hwnd, message, wParam, lParam,
				   s_pScreenPriv);

    case WM_CREATE:
#if CYGDEBUG
      winDebug ("winWindowProc - WM_CREATE\n");
#endif
      
      /*
       * Add a property to our display window that references
       * this screens' privates.
       *
       * This allows the window procedure to refer to the
       * appropriate window DC and shadow DC for the window that
       * it is processing.  We use this to repaint exposed
       * areas of our display window.
       */
      s_pScreenPriv = ((LPCREATESTRUCT) lParam)->lpCreateParams;
      s_hInstance = ((LPCREATESTRUCT) lParam)->hInstance;
      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
      s_pScreen = s_pScreenInfo->pScreen;
      s_hwndLastPrivates = hwnd;
      s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
      SetProp (hwnd, WIN_SCR_PROP, s_pScreenPriv);

      /* Setup tray icon */
      if (!s_pScreenInfo->fNoTrayIcon)
	{
	  /*
	   * NOTE: The WM_CREATE message is processed before CreateWindowEx
	   * returns, so s_pScreenPriv->hwndScreen is invalid at this point.
	   * We go ahead and copy our hwnd parameter over top of the screen
	   * privates hwndScreen so that we have a valid value for
	   * that member.  Otherwise, the tray icon will disappear
	   * the first time you move the mouse over top of it.
	   */
	  
	  s_pScreenPriv->hwndScreen = hwnd;

	  winInitNotifyIcon (s_pScreenPriv);
	}
      return 0;

    case WM_DISPLAYCHANGE:
      /* We cannot handle a display mode change during initialization */
      if (s_pScreenInfo == NULL)
	FatalError ("winWindowProc - WM_DISPLAYCHANGE - The display "
		    "mode changed while we were intializing.  This is "
		    "very bad and unexpected.  Exiting.\n");

      /*
       * We do not care about display changes with
       * fullscreen DirectDraw engines, because those engines set
       * their own mode when they become active.
       */
      if (s_pScreenInfo->fFullScreen
	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
#ifdef XWIN_PRIMARYFB
	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
#endif
	      ))
	{
	  /* 
	   * Store the new display dimensions and depth.
	   * We do this here for future compatibility in case we
	   * ever allow switching from fullscreen to windowed mode.
	   */
	  s_pScreenPriv->dwLastWindowsWidth = GetSystemMetrics (SM_CXSCREEN);
	  s_pScreenPriv->dwLastWindowsHeight = GetSystemMetrics (SM_CYSCREEN);
	  s_pScreenPriv->dwLastWindowsBitsPixel
	    = GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);	  
	  break;
	}
      
      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - orig bpp: %d, last bpp: %d, "
	      "new bpp: %d\n",
	      (int) s_pScreenInfo->dwBPP,
	      (int) s_pScreenPriv->dwLastWindowsBitsPixel,
	      wParam);

      ErrorF ("winWindowProc - WM_DISPLAYCHANGE - new width: %d "
	      "new height: %d\n",
	      LOWORD (lParam), HIWORD (lParam));

      /*
       * TrueColor --> TrueColor depth changes are disruptive for:
       *	Windowed:
       *		Shadow DirectDraw
       *		Shadow DirectDraw Non-Locking
       *		Primary DirectDraw
       *
       * TrueColor --> TrueColor depth changes are non-optimal for:
       *	Windowed:
       *		Shadow GDI
       *
       *	FullScreen:
       *		Shadow GDI
       *
       * TrueColor --> PseudoColor or vice versa are disruptive for:
       *	Windowed:
       *		Shadow DirectDraw
       *		Shadow DirectDraw Non-Locking
       *		Primary DirectDraw
       *		Shadow GDI
       */

      /*
       * Check for a disruptive change in depth.
       * We can only display a message for a disruptive depth change,
       * we cannot do anything to correct the situation.
       */
      if ((s_pScreenInfo->dwBPP != wParam)
	  && (s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DD
	      || s_pScreenInfo->dwEngine == WIN_SERVER_SHADOW_DDNL
#ifdef XWIN_PRIMARYFB
	      || s_pScreenInfo->dwEngine == WIN_SERVER_PRIMARY_DD
#endif
	      ))
	{
	  /* Cannot display the visual until the depth is restored */
	  ErrorF ("winWindowProc - Disruptive change in depth\n");

	  /* Display Exit dialog */
	  winDisplayDepthChangeDialog (s_pScreenPriv);

	  /* Flag that we have an invalid screen depth */
	  s_pScreenPriv->fBadDepth = TRUE;

	  /* Minimize the display window */
	  ShowWindow (hwnd, SW_MINIMIZE);
	}
      else
	{
	  /* Flag that we have a valid screen depth */
	  s_pScreenPriv->fBadDepth = FALSE;
	}
      
      /*
       * Check for a change in display dimensions.
       * We can simply recreate the same-sized primary surface when
       * the display dimensions change.
       */
      if (s_pScreenPriv->dwLastWindowsWidth != LOWORD (lParam)
	  || s_pScreenPriv->dwLastWindowsHeight != HIWORD (lParam))
	{
	  /*
	   * NOTE: The non-DirectDraw engines set the ReleasePrimarySurface
	   * and CreatePrimarySurface function pointers to point
	   * to the no operation function, NoopDDA.  This allows us
	   * to blindly call these functions, even if they are not
	   * relevant to the current engine (e.g., Shadow GDI).
	   */

#if CYGDEBUG
	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions changed\n");
#endif
	  
	  /* Release the old primary surface */
	  (*s_pScreenPriv->pwinReleasePrimarySurface) (s_pScreen);

#if CYGDEBUG
	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Released "
		  "primary surface\n");
#endif

	  /* Create the new primary surface */
	  (*s_pScreenPriv->pwinCreatePrimarySurface) (s_pScreen);

#if CYGDEBUG
	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Recreated "
		  "primary surface\n");
#endif

#if 0
	  /* Multi-Window mode uses RandR for resizes */
	  if (s_pScreenInfo->fMultiWindow)
	    {
	      RRSetScreenConfig ();
	    }
#endif
	}
      else
	{
#if CYGDEBUG
	  winDebug ("winWindowProc - WM_DISPLAYCHANGE - Dimensions did not "
		  "change\n");
#endif
	}

      /* Store the new display dimensions and depth */
      if (s_pScreenInfo->fMultipleMonitors)
	{
	  s_pScreenPriv->dwLastWindowsWidth
	    = GetSystemMetrics (SM_CXVIRTUALSCREEN);
	  s_pScreenPriv->dwLastWindowsHeight
	    = GetSystemMetrics (SM_CYVIRTUALSCREEN);
	}
      else
	{
	  s_pScreenPriv->dwLastWindowsWidth
	    = GetSystemMetrics (SM_CXSCREEN);
	  s_pScreenPriv->dwLastWindowsHeight
	    = GetSystemMetrics (SM_CYSCREEN);
	}
      s_pScreenPriv->dwLastWindowsBitsPixel
	= GetDeviceCaps (s_pScreenPriv->hdcScreen, BITSPIXEL);
      break;

    case WM_SIZE:
      {
	SCROLLINFO		si;
	RECT			rcWindow;
	int			iWidth, iHeight;

#if CYGDEBUG
	winDebug ("winWindowProc - WM_SIZE\n");
#endif

	/* Break if we do not use scrollbars */
	if (!s_pScreenInfo->fScrollbars
	    || !s_pScreenInfo->fDecoration
#ifdef XWIN_MULTIWINDOWEXTWM
	    || s_pScreenInfo->fMWExtWM
#endif
	    || s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
	    || s_pScreenInfo->fMultiWindow
#endif
	    || s_pScreenInfo->fFullScreen)
	  break;

	/* No need to resize if we get minimized */
	if (wParam == SIZE_MINIMIZED)
	  return 0;

	/*
	 * Get the size of the whole window, including client area,
	 * scrollbars, and non-client area decorations (caption, borders).
	 * We do this because we need to check if the client area
	 * without scrollbars is large enough to display the whole visual.
	 * The new client area size passed by lParam already subtracts
	 * the size of the scrollbars if they are currently displayed.
	 * So checking is LOWORD(lParam) == visual_width and
	 * HIWORD(lParam) == visual_height will never tell us to hide
	 * the scrollbars because the client area would always be too small.
	 * GetClientRect returns the same sizes given by lParam, so we
	 * cannot use GetClientRect either.
	 */
	GetWindowRect (hwnd, &rcWindow);
	iWidth = rcWindow.right - rcWindow.left;
	iHeight = rcWindow.bottom - rcWindow.top;

	ErrorF ("winWindowProc - WM_SIZE - window w: %d h: %d, "
		"new client area w: %d h: %d\n",
		iWidth, iHeight, LOWORD (lParam), HIWORD (lParam));

	/* Subtract the frame size from the window size. */
	iWidth -= 2 * GetSystemMetrics (SM_CXSIZEFRAME);
	iHeight -= (2 * GetSystemMetrics (SM_CYSIZEFRAME)
		    + GetSystemMetrics (SM_CYCAPTION));

	/*
	 * Update scrollbar page sizes.
	 * NOTE: If page size == range, then the scrollbar is
	 * automatically hidden.
	 */

	/* Is the naked client area large enough to show the whole visual? */
	if (iWidth < s_pScreenInfo->dwWidth
	    || iHeight < s_pScreenInfo->dwHeight)
	  {
	    /* Client area too small to display visual, use scrollbars */
	    iWidth -= GetSystemMetrics (SM_CXVSCROLL);
	    iHeight -= GetSystemMetrics (SM_CYHSCROLL);
	  }
	
	/* Set the horizontal scrollbar page size */
	si.cbSize = sizeof (si);
	si.fMask = SIF_PAGE | SIF_RANGE;
	si.nMin = 0;
	si.nMax = s_pScreenInfo->dwWidth - 1;
	si.nPage = iWidth;
	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
	
	/* Set the vertical scrollbar page size */
	si.cbSize = sizeof (si);
	si.fMask = SIF_PAGE | SIF_RANGE;
	si.nMin = 0;
	si.nMax = s_pScreenInfo->dwHeight - 1;
	si.nPage = iHeight;
	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);

	/*
	 * NOTE: Scrollbars may have moved if they were at the 
	 * far right/bottom, so we query their current position.
	 */
	
	/* Get the horizontal scrollbar position and set the offset */
	si.cbSize = sizeof (si);
	si.fMask = SIF_POS;
	GetScrollInfo (hwnd, SB_HORZ, &si);
	s_pScreenInfo->dwXOffset = -si.nPos;
	
	/* Get the vertical scrollbar position and set the offset */
	si.cbSize = sizeof (si);
	si.fMask = SIF_POS;
	GetScrollInfo (hwnd, SB_VERT, &si);
	s_pScreenInfo->dwYOffset = -si.nPos;
      }
      return 0;

    case WM_VSCROLL:
      {
	SCROLLINFO		si;
	int			iVertPos;

#if CYGDEBUG
	winDebug ("winWindowProc - WM_VSCROLL\n");
#endif
      
	/* Get vertical scroll bar info */
	si.cbSize = sizeof (si);
	si.fMask = SIF_ALL;
	GetScrollInfo (hwnd, SB_VERT, &si);

	/* Save the vertical position for comparison later */
	iVertPos = si.nPos;

	/*
	 * Don't forget:
	 * moving the scrollbar to the DOWN, scroll the content UP
	 */
	switch (LOWORD(wParam))
	  {
	  case SB_TOP:
	    si.nPos = si.nMin;
	    break;
	  
	  case SB_BOTTOM:
	    si.nPos = si.nMax - si.nPage + 1;
	    break;

	  case SB_LINEUP:
	    si.nPos -= 1;
	    break;
	  
	  case SB_LINEDOWN:
	    si.nPos += 1;
	    break;
	  
	  case SB_PAGEUP:
	    si.nPos -= si.nPage;
	    break;
	  
	  case SB_PAGEDOWN:
	    si.nPos += si.nPage;
	    break;

	  case SB_THUMBTRACK:
	    si.nPos = si.nTrackPos;
	    break;

	  default:
	    break;
	  }

	/*
	 * We retrieve the position after setting it,
	 * because Windows may adjust it.
	 */
	si.fMask = SIF_POS;
	SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
	GetScrollInfo (hwnd, SB_VERT, &si);
      
	/* Scroll the window if the position has changed */
	if (si.nPos != iVertPos)
	  {
	    /* Save the new offset for bit block transfers, etc. */
	    s_pScreenInfo->dwYOffset = -si.nPos;

	    /* Change displayed region in the window */
	    ScrollWindowEx (hwnd,
			    0,
			    iVertPos - si.nPos,
			    NULL,
			    NULL,
			    NULL,
			    NULL,
			    SW_INVALIDATE);
	  
	    /* Redraw the window contents */
	    UpdateWindow (hwnd);
	  }
      }
      return 0;

    case WM_HSCROLL:
      {
	SCROLLINFO		si;
	int			iHorzPos;

#if CYGDEBUG
	winDebug ("winWindowProc - WM_HSCROLL\n");
#endif
      
	/* Get horizontal scroll bar info */
	si.cbSize = sizeof (si);
	si.fMask = SIF_ALL;
	GetScrollInfo (hwnd, SB_HORZ, &si);

	/* Save the horizontal position for comparison later */
	iHorzPos = si.nPos;

	/*
	 * Don't forget:
	 * moving the scrollbar to the RIGHT, scroll the content LEFT
	 */
	switch (LOWORD(wParam))
	  {
	  case SB_LEFT:
	    si.nPos = si.nMin;
	    break;
	  
	  case SB_RIGHT:
	    si.nPos = si.nMax - si.nPage + 1;
	    break;

	  case SB_LINELEFT:
	    si.nPos -= 1;
	    break;
	  
	  case SB_LINERIGHT:
	    si.nPos += 1;
	    break;
	  
	  case SB_PAGELEFT:
	    si.nPos -= si.nPage;
	    break;
	  
	  case SB_PAGERIGHT:
	    si.nPos += si.nPage;
	    break;

	  case SB_THUMBTRACK:
	    si.nPos = si.nTrackPos;
	    break;

	  default:
	    break;
	  }

	/*
	 * We retrieve the position after setting it,
	 * because Windows may adjust it.
	 */
	si.fMask = SIF_POS;
	SetScrollInfo (hwnd, SB_HORZ, &si, TRUE);
	GetScrollInfo (hwnd, SB_HORZ, &si);
      
	/* Scroll the window if the position has changed */
	if (si.nPos != iHorzPos)
	  {
	    /* Save the new offset for bit block transfers, etc. */
	    s_pScreenInfo->dwXOffset = -si.nPos;

	    /* Change displayed region in the window */
	    ScrollWindowEx (hwnd,
			    iHorzPos - si.nPos,
			    0,
			    NULL,
			    NULL,
			    NULL,
			    NULL,
			    SW_INVALIDATE);
	  
	    /* Redraw the window contents */
	    UpdateWindow (hwnd);
	  }
      }
      return 0;

    case WM_GETMINMAXINFO:
      {
	MINMAXINFO		*pMinMaxInfo = (MINMAXINFO *) lParam;
	int			iCaptionHeight;
	int			iBorderHeight, iBorderWidth;

#if CYGDEBUG	
	winDebug ("winWindowProc - WM_GETMINMAXINFO - pScreenInfo: %08x\n",
		s_pScreenInfo);
#endif

	/* Can't do anything without screen info */
	if (s_pScreenInfo == NULL
	    || !s_pScreenInfo->fScrollbars
	    || s_pScreenInfo->fFullScreen
	    || !s_pScreenInfo->fDecoration
#ifdef XWIN_MULTIWINDOWEXTWM
	    || s_pScreenInfo->fMWExtWM
#endif
	    || s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
	    || s_pScreenInfo->fMultiWindow
#endif
	    )
	  break;

	/*
	 * Here we can override the maximum tracking size, which
	 * is the largest size that can be assigned to our window
	 * via the sizing border.
	 */

	/*
	 * FIXME: Do we only need to do this once, since our visual size
	 * does not change?  Does Windows store this value statically
	 * once we have set it once?
	 */

	/* Get the border and caption sizes */
	iCaptionHeight = GetSystemMetrics (SM_CYCAPTION);
	iBorderWidth = 2 * GetSystemMetrics (SM_CXSIZEFRAME);
	iBorderHeight = 2 * GetSystemMetrics (SM_CYSIZEFRAME);
	
	/* Allow the full visual to be displayed */
	pMinMaxInfo->ptMaxTrackSize.x
	  = s_pScreenInfo->dwWidth + iBorderWidth;
	pMinMaxInfo->ptMaxTrackSize.y
	  = s_pScreenInfo->dwHeight + iBorderHeight + iCaptionHeight;
      }
      return 0;

    case WM_ERASEBKGND:
#if CYGDEBUG
      winDebug ("winWindowProc - WM_ERASEBKGND\n");
#endif
      /*
       * Pretend that we did erase the background but we don't care,
       * the application uses the full window estate. This avoids some
       * flickering when resizing.
       */
      return TRUE;

    case WM_PAINT:
#if CYGDEBUG
      winDebug ("winWindowProc - WM_PAINT\n");
#endif
      /* Only paint if we have privates and the server is enabled */
      if (s_pScreenPriv == NULL
	  || !s_pScreenPriv->fEnabled
	  || (s_pScreenInfo->fFullScreen && !s_pScreenPriv->fActive)
	  || s_pScreenPriv->fBadDepth)
	{
	  /* We don't want to paint */
	  break;
	}

      /* Break out here if we don't have a valid paint routine */
      if (s_pScreenPriv->pwinBltExposedRegions == NULL)
	break;
      
      /* Call the engine dependent repainter */
      (*s_pScreenPriv->pwinBltExposedRegions) (s_pScreen);
      return 0;

    case WM_PALETTECHANGED:
      {
#if CYGDEBUG
	winDebug ("winWindowProc - WM_PALETTECHANGED\n");
#endif
	/*
	 * Don't process if we don't have privates or a colormap,
	 * or if we have an invalid depth.
	 */
	if (s_pScreenPriv == NULL
	    || s_pScreenPriv->pcmapInstalled == NULL
	    || s_pScreenPriv->fBadDepth)
	  break;

	/* Return if we caused the palette to change */
	if ((HWND) wParam == hwnd)
	  {
	    /* Redraw the screen */
	    (*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
	    return 0;
	  }
	
	/* Reinstall the windows palette */
	(*s_pScreenPriv->pwinRealizeInstalledPalette) (s_pScreen);
	
	/* Redraw the screen */
	(*s_pScreenPriv->pwinRedrawScreen) (s_pScreen);
	return 0;
      }

    case WM_MOUSEMOVE:
      /* We can't do anything without privates */
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /* Has the mouse pointer crossed screens? */
      if (s_pScreen != miPointerCurrentScreen ())
	miPointerSetNewScreen (s_pScreenInfo->dwScreen,
			       GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset);

      /* Are we tracking yet? */
      if (!s_fTracking)
	{
	  TRACKMOUSEEVENT		tme;
	  
	  /* Setup data structure */
	  ZeroMemory (&tme, sizeof (tme));
	  tme.cbSize = sizeof (tme);
	  tme.dwFlags = TME_LEAVE;
	  tme.hwndTrack = hwnd;

	  /* Call the tracking function */
	  if (!(*g_fpTrackMouseEvent) (&tme))
	    ErrorF ("winWindowProc - _TrackMouseEvent failed\n");

	  /* Flag that we are tracking now */
	  s_fTracking = TRUE;
	}

      /* Hide or show the Windows mouse cursor */
      if (g_fSoftwareCursor && g_fCursor && (s_pScreenPriv->fActive || s_pScreenInfo->fLessPointer))
	{
	  /* Hide Windows cursor */
	  g_fCursor = FALSE;
	  ShowCursor (FALSE);
	}
      else if (g_fSoftwareCursor && !g_fCursor && !s_pScreenPriv->fActive
	       && !s_pScreenInfo->fLessPointer)
	{
	  /* Show Windows cursor */
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}
      
      /* Deliver absolute cursor position to X Server */
      miPointerAbsoluteCursor (GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset,
			       GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset,
			       g_c32LastInputEventTime = GetTickCount ());
      return 0;

    case WM_NCMOUSEMOVE:
      /*
       * We break instead of returning 0 since we need to call
       * DefWindowProc to get the mouse cursor changes
       * and min/max/close button highlighting in Windows XP.
       * The Platform SDK says that you should return 0 if you
       * process this message, but it fails to mention that you
       * will give up any default functionality if you do return 0.
       */
      
      /* We can't do anything without privates */
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      
      /* Non-client mouse movement, show Windows cursor */
      if (g_fSoftwareCursor && !g_fCursor)
	{
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}
      break;

    case WM_MOUSELEAVE:
      /* Mouse has left our client area */

      /* Flag that we are no longer tracking */
      s_fTracking = FALSE;

      /* Show the mouse cursor, if necessary */
      if (g_fSoftwareCursor && !g_fCursor)
	{
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}
      return 0;

    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONDOWN:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	SetCapture (hwnd);
      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button1, wParam);
      
    case WM_LBUTTONUP:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	ReleaseCapture ();
      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button1, wParam);

    case WM_MBUTTONDBLCLK:
    case WM_MBUTTONDOWN:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	SetCapture (hwnd);
      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button2, wParam);
      
    case WM_MBUTTONUP:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	ReleaseCapture ();
      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button2, wParam);
      
    case WM_RBUTTONDBLCLK:
    case WM_RBUTTONDOWN:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	SetCapture (hwnd);
      return winMouseButtonsHandle (s_pScreen, ButtonPress, Button3, wParam);
      
    case WM_RBUTTONUP:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	ReleaseCapture ();
      return winMouseButtonsHandle (s_pScreen, ButtonRelease, Button3, wParam);

    case WM_XBUTTONDBLCLK:
    case WM_XBUTTONDOWN:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	SetCapture (hwnd);
      return winMouseButtonsHandle (s_pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
    case WM_XBUTTONUP:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
      if (s_pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOWEXTWM
	  || s_pScreenInfo->fMWExtWM
#endif
	  )
	ReleaseCapture ();
      return winMouseButtonsHandle (s_pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);

    case WM_TIMER:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /* Branch on the timer id */
      switch (wParam)
	{
	case WIN_E3B_TIMER_ID:
	  /* Send delayed button press */
	  winMouseButtonsSendEvent (ButtonPress,
				    s_pScreenPriv->iE3BCachedPress);

	  /* Kill this timer */
	  KillTimer (s_pScreenPriv->hwndScreen, WIN_E3B_TIMER_ID);

	  /* Clear screen privates flags */
	  s_pScreenPriv->iE3BCachedPress = 0;
	  break;

	case WIN_POLLING_MOUSE_TIMER_ID:
	  {
	    POINT		point;
	    
	    /* Get the current position of the mouse cursor */
	    GetCursorPos (&point);
	    
	    /* Map from screen (-X, -Y) to root (0, 0) */
	    point.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
	    point.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);
	    
	    /* Deliver absolute cursor position to X Server */
	    miPointerAbsoluteCursor (point.x, point.y,
				     g_c32LastInputEventTime = GetTickCount());
	  }
	}
      return 0;

    case WM_CTLCOLORSCROLLBAR:
      FatalError ("winWindowProc - WM_CTLCOLORSCROLLBAR - We are not "
		  "supposed to get this message.  Exiting.\n");
      return 0;

    case WM_MOUSEWHEEL:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;
#if CYGDEBUG
      winDebug ("winWindowProc - WM_MOUSEWHEEL\n");
#endif
      winMouseWheel (s_pScreen, GET_WHEEL_DELTA_WPARAM(wParam));
      break;

    case WM_SETFOCUS:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /* Save handle of our main window that last received focus */
      g_hwndKeyboardFocus = hwnd;

      /* Restore the state of all mode keys */
      winRestoreModeKeyStates ();

      /* Add the keyboard hook if possible */
      if (g_fKeyboardHookLL)
	g_fKeyboardHookLL = winInstallKeyboardHookLL ();
      return 0;

    case WM_KILLFOCUS:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /* Clear handle of our main window that last received focus */
      g_hwndKeyboardFocus = NULL;

      /* Release any pressed keys */
      winKeybdReleaseKeys ();

      /* Remove our keyboard hook if it is installed */
      winRemoveKeyboardHookLL ();
      return 0;

    case WM_SYSKEYDOWN:
    case WM_KEYDOWN:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /*
       * FIXME: Catching Alt-F4 like this is really terrible.  This should
       * be generalized to handle other Windows keyboard signals.  Actually,
       * the list keys to catch and the actions to perform when caught should
       * be configurable; that way user's can customize the keys that they
       * need to have passed through to their window manager or apps, or they
       * can remap certain actions to new key codes that do not conflict
       * with the X apps that they are using.  Yeah, that'll take awhile.
       */
      if ((s_pScreenInfo->fUseWinKillKey && wParam == VK_F4
	   && (GetKeyState (VK_MENU) & 0x8000))
	  || (s_pScreenInfo->fUseUnixKillKey && wParam == VK_BACK
	      && (GetKeyState (VK_MENU) & 0x8000)
	      && (GetKeyState (VK_CONTROL) & 0x8000)))
	{
	  /*
	   * Better leave this message here, just in case some unsuspecting
	   * user enters Alt + F4 and is surprised when the application
	   * quits.
	   */
	  ErrorF ("winWindowProc - WM_*KEYDOWN - Closekey hit, quitting\n");
	  
	  /* Display Exit dialog */
	  winDisplayExitDialog (s_pScreenPriv);
	  return 0;
	}
      
      /*
       * Don't do anything for the Windows keys, as focus will soon
       * be returned to Windows.  We may be able to trap the Windows keys,
       * but we should determine if that is desirable before doing so.
       */
      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
	break;

#ifdef XKB
      /* 
       * Discard presses generated from Windows auto-repeat
       * ago: Only discard them if XKB is not disabled 
       */
      if (!g_winInfo.xkb.disable && (lParam & (1<<30)))
      {
        switch (wParam)
        {
          /* ago: Pressing LControl while RControl is pressed is 
           * Indicated as repeat. Fix this!
           */
          case VK_CONTROL:
          case VK_SHIFT:
            if (winCheckKeyPressed(wParam, lParam))
              return 0;
            break;
          default:
            return 0;
        }
      } 
#endif 
      
      /* Discard fake Ctrl_L presses that precede AltGR on non-US keyboards */
      if (winIsFakeCtrl_L (message, wParam, lParam))
	return 0;
      
      /* Translate Windows key code to X scan code */
      winTranslateKey (wParam, lParam, &iScanCode);

      /* Ignore repeats for CapsLock */
      if (wParam == VK_CAPITAL)
	lParam = 1;

      /* Send the key event(s) */
      for (i = 0; i < LOWORD(lParam); ++i)
	winSendKeyEvent (iScanCode, TRUE);
      return 0;

    case WM_SYSKEYUP:
    case WM_KEYUP:
      if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
	break;

      /*
       * Don't do anything for the Windows keys, as focus will soon
       * be returned to Windows.  We may be able to trap the Windows keys,
       * but we should determine if that is desirable before doing so.
       */
      if ((wParam == VK_LWIN || wParam == VK_RWIN) && !g_fKeyboardHookLL)
	break;

      /* Ignore the fake Ctrl_L that follows an AltGr release */
      if (winIsFakeCtrl_L (message, wParam, lParam))
	return 0;

      /* Enqueue a keyup event */
      winTranslateKey (wParam, lParam, &iScanCode);
      winSendKeyEvent (iScanCode, FALSE);

      /* Release all pressed shift keys */
      if (wParam == VK_SHIFT) 
        winFixShiftKeys (iScanCode);
      return 0;

    case WM_HOTKEY:
      if (s_pScreenPriv == NULL)
	break;

      /* Call the engine-specific hot key handler */
      (*s_pScreenPriv->pwinHotKeyAltTab) (s_pScreen);
      return 0;

    case WM_ACTIVATE:
      if (s_pScreenPriv == NULL
	  || s_pScreenInfo->fIgnoreInput)
	break;

      /* TODO: Override display of window when we have a bad depth */
      if (LOWORD(wParam) != WA_INACTIVE && s_pScreenPriv->fBadDepth)
	{
	  ErrorF ("winWindowProc - WM_ACTIVATE - Bad depth, trying "
		  "to override window activation\n");

	  /* Minimize the window */
	  ShowWindow (hwnd, SW_MINIMIZE);

	  /* Display dialog box */
	  if (g_hDlgDepthChange != NULL)
	    {
	      /* Make the existing dialog box active */
	      SetActiveWindow (g_hDlgDepthChange);
	    }
	  else
	    {
	      /* TODO: Recreate the dialog box and bring to the top */
	      ShowWindow (g_hDlgDepthChange, SW_SHOWDEFAULT);
	    }

	  /* Don't do any other processing of this message */
	  return 0;
	}

#if CYGDEBUG
      winDebug ("winWindowProc - WM_ACTIVATE\n");
#endif

      /*
       * Focus is being changed to another window.
       * The other window may or may not belong to
       * our process.
       */

      /* Clear any lingering wheel delta */
      s_pScreenPriv->iDeltaZ = 0;

      /* Reshow the Windows mouse cursor if we are being deactivated */
      if (g_fSoftwareCursor && LOWORD(wParam) == WA_INACTIVE
	  && !g_fCursor)
	{
	  /* Show Windows cursor */
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}
      return 0;

    case WM_ACTIVATEAPP:
      if (s_pScreenPriv == NULL
	  || s_pScreenInfo->fIgnoreInput)
	break;

#if CYGDEBUG || TRUE
      winDebug ("winWindowProc - WM_ACTIVATEAPP\n");
#endif

      /* Activate or deactivate */
      s_pScreenPriv->fActive = wParam;

      /* Reshow the Windows mouse cursor if we are being deactivated */
      if (g_fSoftwareCursor && !s_pScreenPriv->fActive
	  && !g_fCursor)
	{
	  /* Show Windows cursor */
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}

#ifdef XWIN_CLIPBOARD
      /* Make sure the clipboard chain is ok. */
      winFixClipboardChain ();
#endif

      /* Call engine specific screen activation/deactivation function */
      (*s_pScreenPriv->pwinActivateApp) (s_pScreen);

#ifdef XWIN_MULTIWINDOWEXTWM
      if (s_pScreenPriv->fActive)
	{
	  /* Restack all window unless using built-in wm. */
	  if (s_pScreenInfo->fInternalWM && s_pScreenInfo->fAnotherWMRunning)
	    winMWExtWMRestackWindows (s_pScreen);
	}
#endif

      return 0;

    case WM_COMMAND:
      switch (LOWORD (wParam))
	{
	case ID_APP_EXIT:
	  /* Display Exit dialog */
	  winDisplayExitDialog (s_pScreenPriv);
	  return 0;
	case ID_APP_SHOWCURSOR:
	  winDebug("ShowCursor: %d\n", ShowCursor(TRUE));
	  return 0;

#ifdef XWIN_MULTIWINDOW
	case ID_APP_HIDE_ROOT:
	  if (s_pScreenPriv->fRootWindowShown)
	    ShowWindow (s_pScreenPriv->hwndScreen, SW_HIDE);
	  else
	    ShowWindow (s_pScreenPriv->hwndScreen, SW_SHOW);
	  s_pScreenPriv->fRootWindowShown = !s_pScreenPriv->fRootWindowShown;
	  return 0;
#endif

	case ID_APP_ABOUT:
	  /* Display the About box */
	  winDisplayAboutDialog (s_pScreenPriv);
	  return 0;

	default:
	  /* It's probably one of the custom menus... */
	  if (HandleCustomWM_COMMAND (0, LOWORD (wParam)))
	    return 0;
	}
      break;

    case WM_ENDSESSION:
    case WM_GIVEUP:
      /* Tell X that we are giving up */
#ifdef XWIN_MULTIWINDOW
      if (s_pScreenInfo->fMultiWindow)
	winDeinitMultiWindowWM ();
#endif
      GiveUp (0);
      return 0;

    case WM_CLOSE:
      /* Display Exit dialog */
      winDisplayExitDialog (s_pScreenPriv);
      return 0;

    case WM_SETCURSOR:
      if (LOWORD(lParam) == HTCLIENT)
	{
	  if (!g_fSoftwareCursor) SetCursor (s_pScreenPriv->cursor.handle);
	  return TRUE;
	}
      break;

#ifdef XWIN_MULTIWINDOWEXTWM
    case WM_MANAGE:
      ErrorF ("winWindowProc - WM_MANAGE\n");
      s_pScreenInfo->fAnotherWMRunning = FALSE;

      if (s_pScreenInfo->fInternalWM)
	{
	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
	  //RootlessRepositionWindows (s_pScreen);
	}
      break;

    case WM_UNMANAGE:
      ErrorF ("winWindowProc - WM_UNMANAGE\n");
      s_pScreenInfo->fAnotherWMRunning = TRUE;

      if (s_pScreenInfo->fInternalWM)
	{
	  EnumThreadWindows (g_dwCurrentThreadID, winMWExtWMDecorateWindow, 0);
	  winMWExtWMRestackWindows (s_pScreen);
	}
      break;
#endif

    default:
      if(message == s_uTaskbarRestart)
	{
	  winInitNotifyIcon (s_pScreenPriv);
	}
      break;
    }

  return DefWindowProc (hwnd, message, wParam, lParam);
}
Exemplo n.º 8
0
/** 创建windows窗口 */
bool GLWindow::Create(const char * window_title,const char * class_name, HINSTANCE h_instance, LPVOID lpParam)
{
	int nX=0;
	int nY=0;
	PIXELFORMATDESCRIPTOR pfd =											/**< 设置像素描述结构 */
	{
		sizeof(PIXELFORMATDESCRIPTOR),									/**< 像素描述结构的大小 */ 
		1,																/**< 版本号 */
		PFD_DRAW_TO_WINDOW	|											/**< 缓存区的输出显示在一个窗口中 */
		PFD_SUPPORT_OPENGL	|											/**< 缓存区支持OpenGL绘图 */
		PFD_STEREO			|											/**< 颜色缓存区是立体缓存 */
		PFD_DOUBLEBUFFER,												/**< 颜色缓存区是双缓存 */
		PFD_TYPE_RGBA,													/**< 使用RGBA颜色格式 */
		m_BitsPerPixel,													/**< 颜色缓存区中颜色值所占的位深 */
		0, 0, 0, 0, 0, 0,												/**< 使用默认的颜色设置 */
		0,																/**< 无Alpha缓存 */
		0,																/**< 颜色缓存区中alpha成分的移位计数 */
		0,																/**< 无累计缓存区 */
		0, 0, 0, 0,														/**< 累计缓存区无移位 */
		32,																/**< 32位深度缓存 */
		0,																/**< 无蒙版缓存 */
		0,																/**< 无辅助缓存区 */
		PFD_MAIN_PLANE,													/**< 必须为PFD_MAIN_PLANE,设置为主绘图层 */
		0,																/**< 表示OpenGL实现所支持的上层或下层平面的数量 */
		0, 0, 0															/**< 过时,已不再使用 */
	};

	DWORD windowStyle = WS_TILEDWINDOW  ;							/**< 定义我们窗口类型,使用常规设定 */
	DWORD windowExtendedStyle = WS_EX_APPWINDOW;						

	if (m_IsFullScreen == true)											/**< 如果为全屏模式,尝试转化为全屏模式 */
	{
		if (ChangeScreenSetting() == false)
		{																/**< 全屏模式转换失败,弹出对话框提示,并尝试窗口模式 */
			MessageBox(HWND_DESKTOP, "模式转换失败.\n在窗口模式下运行.", "Error", MB_OK | MB_ICONEXCLAMATION);
			m_IsFullScreen = false;										/**< 设置为窗口模式 */
		}
		else															/**< 如果为窗口模式 */
		{
			ShowCursor(false);											/**< 隐藏鼠标 */
			windowStyle = WS_POPUP;										/**< 设置窗口模式为顶层窗口 */
			windowExtendedStyle |= WS_EX_TOPMOST;						
		}																
	}

	/// 调整我们窗口的大小,使其客户区的大小为我们设置的大小
	RECT windowRect = {GetPosX(), GetPosY(), GetPosX() + GetWidth(), GetPosY() + GetHeight()};
	if (m_IsFullScreen == false)										/**< 在窗口模式下使用 */
	{	
		windowExtendedStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;	/**< 使窗口具有3D外观 */
		int wid = GetSystemMetrics(SM_CXSCREEN);		/**< 获取当前屏幕宽 */
		int hei = GetSystemMetrics(SM_CYSCREEN);		/**< 获取当前屏幕高 */
		nX = (wid - GetWidth()) / 2;                    /**< 计算窗口居中用 */
		nY = (hei - GetHeight()) / 2;			
		/// 调整我们窗口的大小,使其客户区的大小为我们设置的大小
		AdjustWindowRectEx(&windowRect, windowStyle, 0, windowExtendedStyle);
		/// 判断窗口的左上角是否隐藏在桌面外
		if (windowRect.left < 0)										/**< 如果窗口X坐标为负,移动坐标到0处,并调整窗口的位置 */
		{
			windowRect.right -= windowRect.left;						
			windowRect.left = 0;										
		}
		if (windowRect.top < 0)											/**< 如果窗口Y坐标为负,移动坐标到0处,并调整窗口的位置 */
		{
			windowRect.bottom -= windowRect.top;						
			windowRect.top = 0;											
		}
	}

	/// 创建窗口
	m_hWnd = CreateWindowEx(windowExtendedStyle,						/**< 窗口的扩展风格 */
							class_name,									/**< 窗口的类名 */
							window_title,								/**< 窗口标题 */
							windowStyle,								/**< 窗口的风格 */
							nX,nY,                                      /**< 窗口的左上角位置 */
							windowRect.right - windowRect.left,			/**< 窗口的宽度 */
							windowRect.bottom - windowRect.top,			/**< 窗口的高度 */
                            HWND_DESKTOP,								/**< 窗口的父窗口为桌面 */
							0,											/**< 无菜单 */
							h_instance,									/**< 传入窗口的实例句柄 */
							lpParam);									/**< 传入程序类参数 */

	while (m_hWnd != 0)													/**< 窗口是否创建成功 */
	{
		m_hDC = GetDC(m_hWnd);											/**< 返回窗口的设备描述表 */
		if (m_hDC == 0)													/**< 如果为空 */
		{																/**< 失败 */
			break;														
		}

		GLuint PixelFormat = ChoosePixelFormat(m_hDC, &pfd);			/**< 查找一个兼容的像素格式 */
		if (PixelFormat == 0)											/**< 如果没找到 */
		{																/**< 失败 */
			break;														
		}
		if (SetPixelFormat(m_hDC, PixelFormat, &pfd) == false)			/**< 设置像素格式 */
		{																/**< 失败 */
			break;														
		}
		m_hRC = wglCreateContext(m_hDC);								/**< 创建OpenGL的渲染描述表 */
		if (m_hRC == 0)													/**< 如果为空 */
		{																/**< 失败 */
			break;														
		}
		if (wglMakeCurrent(m_hDC, m_hRC) == false)						/**< 设置当前的OpenGL的渲染对象为当前的窗口 */
		{																/**< 失败 */
			break;														
		}
        
		ShowWindow(m_hWnd, SW_NORMAL);									/**< 显示窗口 */
		ReshapeGL();													/**< 告诉OpenGL调整窗口大小 */
		return true;													/**< 成功返回 */
	}																	

	Destroy();															/**< 释放资源 */
	return false;														/**< 返回失败 */
}
Exemplo n.º 9
0
void InitWindow(HINSTANCE hInstance)
{
	// TODO: make it search all available configs and ask what to load from or something
	if(!cfg.LoadFromFile("default.cfg")) LogToFile("debug.log", "Failed to load config");

	window_rect.left = 0;
	window_rect.right = cfg.scr_width;
	window_rect.top = 0;
	window_rect.bottom = cfg.scr_height;

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

	fullscreenflag = cfg.fullscreen;

	if(!RegisterClass(&window_class))
	{
		MessageBox(NULL, "Failed to register window class", "RegisterClass() Error", MB_OK | MB_ICONEXCLAMATION);
		LogToFile("debug.log", "Failed to register window class");
		PostQuitMessage(-1);
	}

	if(cfg.fullscreen)
	{
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));    // Очистка для хранения установок
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);      // Размер структуры Devmode
		dmScreenSettings.dmPelsWidth = cfg.scr_width;        // Ширина экрана
		dmScreenSettings.dmPelsHeight = cfg.scr_height;        // Высота экрана
		dmScreenSettings.dmBitsPerPel = cfg.scr_bpp;        // Глубина цвета
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Режим Пикселя

		DWORD disp;

		disp = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);

		switch(disp)
		{
		case DISP_CHANGE_SUCCESSFUL:
			{
				fullscreenflag = true;
				ShowCursor(true);
				break;
			}
		case DISP_CHANGE_BADDUALVIEW:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADDUALVIEW)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADDUALVIEW", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADFLAGS:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADFLAGS)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADFLAGS", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADMODE:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADMODE)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADMODE", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADPARAM:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADPARAM)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADPARAM", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_FAILED:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_FAILED)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_FAILED", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_NOTUPDATED:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_NOTUPDATED)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_NOTUPDATED", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_RESTART:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_RESTART)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_RESTART", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		}

	}

	if(fullscreenflag)
	{
		dwExStyle = WS_EX_APPWINDOW;
		//dwStyle = WS_OVERLAPPED;
		dwStyle = WS_POPUP;
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPED;
	}

	AdjustWindowRectEx(&window_rect, dwStyle, false, dwExStyle);


	game_window = CreateWindowEx(dwExStyle,
			window_class.lpszClassName, GAMENAME,
			WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
			dwStyle,
			GetSystemMetrics(0) - GetSystemMetrics(0)/2 - window_rect.right / 2,
			GetSystemMetrics(1) - GetSystemMetrics(1)/2 - window_rect.bottom / 2,
			window_rect.right - window_rect.left,
			window_rect.bottom - window_rect.top,
			NULL, NULL, hInstance, NULL);

	if(!game_window)
	{
		
			LogToFile("debug.log","Failed to create game window");
			MessageBox(NULL, "Failed to create game window", "CreateWindowEx() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
					
			
	}

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

	hDC = GetDC(game_window);

	if(!hDC)
	{
			LogToFile("debug.log","Failed to create device context");
			MessageBox(NULL, "Failed to create device context", "GetDC() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	pf = ChoosePixelFormat(hDC, &pfd);

	if(!pf)
	{
			LogToFile("debug.log","Failed to choose pixel format");
			MessageBox(NULL, "Failed to set pixel format", "ChoosePixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	if(!SetPixelFormat(hDC, pf, &pfd))
	{
			LogToFile("debug.log","Failed to set pixel format");
			MessageBox(NULL, "Failed to set pixel format", "SetPixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	hRC = wglCreateContext(hDC);

	if(!hRC)
	{
			LogToFile("debug.log","Failed to create rendering context");
			MessageBox(NULL, "Failed to create rendering context", "wglCreateContext() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	if(!wglMakeCurrent(hDC, hRC))
	{
			LogToFile("debug.log","Failed to make current context");
			MessageBox(NULL, "Failed to make current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	ShowWindow(game_window, SW_SHOW);
	SetForegroundWindow(game_window);
	SetFocus(game_window);
}
int Game_Init(void *parms)
{
// this function is where you do all the initialization 
// for your game

int index; // looping var

// start up DirectDraw (replace the parms as you desire)
DDraw_Init(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP);

// initialize directinput
DInput_Init();

// acquire the keyboard 
DInput_Init_Keyboard();

// add calls to acquire other directinput devices here...

// initialize directsound and directmusic
DSound_Init();
DMusic_Init();

// hide the mouse
if (!WINDOWED_APP)
    ShowCursor(FALSE);

// seed random number generator
srand(Start_Clock()); 

Open_Error_File("ERROR.TXT");

// initialize math engine
Build_Sin_Cos_Tables();

// initialize the camera with 90 FOV, normalized coordinates
Init_CAM4DV1(&cam,            // the camera object
             CAM_MODEL_EULER, // the euler model
             &cam_pos,        // initial camera position
             &cam_dir,        // initial camera angles
             &cam_target,     // no target
             40.0,            // near and far clipping planes
             12000.0,
             90.0,            // field of view in degrees
             WINDOW_WIDTH,    // size of final screen viewport
             WINDOW_HEIGHT);

VECTOR4D terrain_pos = {0,0,0,0};

Generate_Terrain_OBJECT4DV2(&obj_terrain,            // pointer to object
                            TERRAIN_WIDTH,           // width in world coords on x-axis
                            TERRAIN_HEIGHT,          // height (length) in world coords on z-axis
                            TERRAIN_SCALE,           // vertical scale of terrain
                            "checkerheight01.bmp",  // filename of height bitmap encoded in 256 colors
                            "checker256256.bmp",   // filename of texture map
                             RGB16Bit(255,255,255),  // color of terrain if no texture        
                             &terrain_pos,           // initial position
                             NULL,                   // initial rotations
                             POLY4DV2_ATTR_RGB16  
                             | POLY4DV2_ATTR_SHADE_MODE_FLAT 
                             // | POLY4DV2_ATTR_SHADE_MODE_GOURAUD
                             | POLY4DV2_ATTR_SHADE_MODE_TEXTURE);

// the shading attributes we would like


// set up lights
Reset_Lights_LIGHTV2(lights2, MAX_LIGHTS);

// create some working colors
white.rgba = _RGBA32BIT(255,255,255,0);
gray.rgba  = _RGBA32BIT(100,100,100,0);
black.rgba = _RGBA32BIT(0,0,0,0);
red.rgba   = _RGBA32BIT(255,0,0,0);
green.rgba = _RGBA32BIT(0,255,0,0);
blue.rgba  = _RGBA32BIT(0,0,255,0);

// ambient light
Init_Light_LIGHTV2(lights2,
                   AMBIENT_LIGHT_INDEX,   
                   LIGHTV2_STATE_ON,      // turn the light on
                   LIGHTV2_ATTR_AMBIENT,  // ambient light type
                   gray, black, black,    // color for ambient term only
                   NULL, NULL,            // no need for pos or dir
                   0,0,0,                 // no need for attenuation
                   0,0,0);                // spotlight info NA

VECTOR4D dlight_dir = {-1,1,-1,1};

// directional light
Init_Light_LIGHTV2(lights2,
                   INFINITE_LIGHT_INDEX,  
                   LIGHTV2_STATE_ON,      // turn the light on
                   LIGHTV2_ATTR_INFINITE, // infinite light type
                   black, gray, black,    // color for diffuse term only
                   NULL, &dlight_dir,     // need direction only
                   0,0,0,                 // no need for attenuation
                   0,0,0);                // spotlight info NA


VECTOR4D plight_pos = {0,200,0,1};

// point light
Init_Light_LIGHTV2(lights2,
                   POINT_LIGHT_INDEX,
                   LIGHTV2_STATE_ON,      // turn the light on
                   LIGHTV2_ATTR_POINT,    // pointlight type
                   black, green, black,   // color for diffuse term only
                   &plight_pos, NULL,     // need pos only
                   0,.001,0,              // linear attenuation only
                   0,0,1);                // spotlight info NA


// point light
Init_Light_LIGHTV2(lights2,
                   POINT_LIGHT2_INDEX,
                   LIGHTV2_STATE_ON,     // turn the light on
                   LIGHTV2_ATTR_POINT,   // pointlight type
                   black, blue, black,   // color for diffuse term only
                   &plight_pos, NULL,    // need pos only
                   0,.002,0,            // linear attenuation only
                   0,0,1);               // spotlight info NA

VECTOR4D slight2_pos = {0,200,0,1};
VECTOR4D slight2_dir = {-1,1,-1,1};


// create lookup for lighting engine
RGB_16_8_IndexedRGB_Table_Builder(DD_PIXEL_FORMAT565,  // format we want to build table for
                                  palette,             // source palette
                                  rgblookup);          // lookup table

// create the z buffer
Create_Zbuffer(&zbuffer,
               WINDOW_WIDTH,
               WINDOW_HEIGHT,
               ZBUFFER_ATTR_32BIT);


// load background sounds
wind_sound_id = DSound_Load_WAV("WIND.WAV");

// start the sounds
DSound_Play(wind_sound_id, DSBPLAY_LOOPING);
DSound_Set_Volume(wind_sound_id, 100);

#if 0
// load in the cockpit image
Load_Bitmap_File(&bitmap16bit, "lego01.BMP");
Create_BOB(&cockpit, 0,0,800,600,1, BOB_ATTR_VISIBLE | BOB_ATTR_SINGLE_FRAME, DDSCAPS_SYSTEMMEMORY, 0, 16); 
Load_Frame_BOB16(&cockpit, &bitmap16bit,0,0,0,BITMAP_EXTRACT_MODE_ABS);
Unload_Bitmap_File(&bitmap16bit);
#endif

// set single precission
//_control87( _PC_24, MCW_PC );

// return success
return(1);

} // end Game_Init
// The primary exception filter
LONG WINAPI BWAPIExceptionFilter(EXCEPTION_POINTERS *ep)
{
  DDrawDestroy();
  ShowCursor(TRUE);

  SYSTEMTIME st;
  char szFilename[MAX_PATH];

  // Create the file
  GetSystemTime(&st);
  sprintf_s(szFilename, MAX_PATH, "%sbwapi-data\\logs\\Exceptions\\%u_%02u_%02u.txt", szInstallPath, st.wYear, st.wMonth, st.wDay);

  FILE *hFile = fopen( szFilename, "a+");
  if ( hFile )
  {
    fprintf(hFile, "\n//////////////////////////////////////////////////\n");

    // Print the time
    time_t _t = time(NULL);
    fprintf(hFile, "TIME: %s\n", ctime(&_t));

    // Print version data
    WORD w1,w2,w3,w4;
    GetCurrentProductVersion(w1, w2, w3, w4);
    fprintf(hFile, "VERSION: %hu.%hu.%hu.%hu\n", w1, w2, w3, w4);

    // BWAPI/Broodwar specific
    fprintf(hFile, "BWAPI:\n");
    fprintf(hFile, "  REVISION: %u\n", BWAPI::BroodwarImpl.getRevision());
    fprintf(hFile, "  BUILD: %s\n", BWAPI::BroodwarImpl.isDebug() ? "DEBUG" : "RELEASE");
    fprintf(hFile, "  ERROR: %s\n", BWAPI::BroodwarImpl.getLastError().c_str());
    fprintf(hFile, "  LOCATION: %s %s\n", BWAPI::BroodwarImpl.isMultiplayer() ? (BWAPI::BroodwarImpl.isBattleNet() ? "Battle.net" : "Multiplayer") : "Single Player", BWAPI::BroodwarImpl.isReplay() ? "Replay" : "");
    
    if ( BWAPI::BroodwarImpl.isInGame() )
    {
      fprintf(hFile, "MAP: %s\n     %s\n", BWAPI::BroodwarImpl.mapName().c_str(), BWAPI::BroodwarImpl.mapFileName().c_str());
      NULLCHECK(BWAPI::BroodwarImpl.self());
      NULLCHECK(BWAPI::BroodwarImpl.enemy());
      NULLCHECK(BWAPI::BroodwarImpl.neutral());
      if ( BWAPI::BroodwarImpl.hAIModule && !BWAPI::BroodwarImpl.client )
        fprintf(hFile, "\"Broodwar\" pointer was not initialized for AI module.\n");
      if ( BWAPI::BroodwarImpl.hTournamentModule && !BWAPI::BroodwarImpl.tournamentAI )
        fprintf(hFile, "\"Broodwar\" pointer was not initialized for Tournament module.\n");
    }

    // Print the exception info
    DWORD dwExceptionCode = ep->ExceptionRecord->ExceptionCode;
    fprintf(hFile, "\nEXCEPTION: 0x%p    %s\n", dwExceptionCode, GetExceptionName(dwExceptionCode));

    // Store exception address
    PVOID pExceptionAddr = ep->ExceptionRecord->ExceptionAddress;

    // Print offending module info
    fprintf(hFile, "FAULT:     0x%p    %s\n", pExceptionAddr, getModuleNameFrom(pExceptionAddr).c_str());

    // Print register information
    fprintf(hFile, "REGISTERS:\n");
    DWORD dwCntxtFlags = ep->ContextRecord->ContextFlags;
    if ( dwCntxtFlags & CONTEXT_INTEGER )
      fprintf(hFile, "  EDI: %08X\n"
                     "  ESI: %08X\n"
                     "  EBX: %08X\n"
                     "  EDX: %08X\n"
                     "  ECX: %08X\n"
                     "  EAX: %08X\n",
                     ep->ContextRecord->Edi,
                     ep->ContextRecord->Esi,
                     ep->ContextRecord->Ebx,
                     ep->ContextRecord->Edx,
                     ep->ContextRecord->Ecx,
                     ep->ContextRecord->Eax);
    if ( dwCntxtFlags & CONTEXT_CONTROL )
      fprintf(hFile, "  EBP: %08X\n"
                     "  EIP: %08X\n"
                     "  ESP: %08X\n",
                     ep->ContextRecord->Ebp,
                     ep->ContextRecord->Eip,
                     ep->ContextRecord->Esp);

    // Get the stack frame
    STACKFRAME sf = { 0 };
    sf.AddrPC.Mode      = AddrModeFlat;
    sf.AddrPC.Offset    = ep->ContextRecord->Eip;
    sf.AddrFrame.Mode   = AddrModeFlat;
    sf.AddrFrame.Offset = ep->ContextRecord->Ebp;
    sf.AddrStack.Mode   = AddrModeFlat;
    sf.AddrStack.Offset = ep->ContextRecord->Esp;

    // Create a context record copy
    CONTEXT c = *ep->ContextRecord;

    // Do the stack trace
    fprintf(hFile, "STACK:\n");

    // Get frequently used handles
    HANDLE hProcess = GetCurrentProcess();
    HANDLE hThread  = GetCurrentThread();

    // Initialize symbols and stuff
    if ( _SymInitialize )
    {
      _SymInitialize(hProcess, NULL, FALSE);
      if ( _SymSetOptions )
        _SymSetOptions(SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_AUTO_PUBLICS |
                        SYMOPT_DEFERRED_LOADS | SYMOPT_FAVOR_COMPRESSED |
                        SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_LOAD_ANYTHING |
                        SYMOPT_LOAD_LINES);

      // Load all module symbols
      if ( _SymLoadModule )
      {
        MODULEENTRY32 me32;
        me32.dwSize = sizeof(MODULEENTRY32);

        HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
        if ( Module32First(hSnapshot, &me32) )
        {
          do
          {
            _SymLoadModule(hProcess, NULL, me32.szExePath, me32.szModule, (DWORD)me32.modBaseAddr, me32.modBaseSize);
          } while( Module32Next(hSnapshot, &me32) );
        }
        CloseHandle(hSnapshot);
      } // if _SymLoadModule is valid
    }

    // Load custom symbols for Broodwar, etc
    std::vector<_customSymbolStore> customSymbols;
    char szSymbolMap[MAX_PATH];
    sprintf_s(szSymbolMap, MAX_PATH, "%sbwapi-data\\data\\Broodwar.map", szInstallPath);
    FILE *hBWSymbols = fopen(szSymbolMap, "r");
    if ( hBWSymbols )
    {
      char szSymbolName[512];
      DWORD dwAddress = 0;
      DWORD dwSize = 0;
      for (;;)
      {
        int iResult = fscanf(hBWSymbols, "%512s %x %x", szSymbolName, &dwAddress, &dwSize);
        if ( iResult == EOF || iResult == 0 )
          break;
        _customSymbolStore sym = { szSymbolName, dwAddress, dwAddress + dwSize };
        customSymbols.push_back(sym);
      }
      fclose(hBWSymbols);
    }

    // Walk, don't run
    if ( _StackWalk && _SymFunctionTableAccess && _SymGetModuleBase )
    {
      while ( _StackWalk(IMAGE_FILE_MACHINE_I386, 
                          hProcess, 
                          hThread, 
                          &sf, 
                          &c, 
                          NULL, 
                          _SymFunctionTableAccess,
                          _SymGetModuleBase,
                          NULL) )
      {
        DWORD dwOffset = sf.AddrPC.Offset;
        fprintf(hFile, "  %-16s  0x%p    ", getModuleNameFrom((LPCVOID)dwOffset).c_str(), dwOffset);
        bool foundSomething = false;
        if ( dwOffset )
        {
          // Get the symbol name
          IMAGEHLP_SYMBOL_PACKAGE sip = { 0 };
          sip.sym.SizeOfStruct  = sizeof(IMAGEHLP_SYMBOL);
          sip.sym.MaxNameLength = MAX_SYM_NAME;

          DWORD dwJunk = 0;
          if ( _SymInitialize && _SymGetSymFromAddr && _SymGetSymFromAddr(hProcess, dwOffset, &dwJunk, &sip.sym) )
          {
            fprintf(hFile, "%s", sip.sym.Name);
            foundSomething = true;
          }

          // Get the file name + line
          IMAGEHLP_LINE il = { 0 };
          il.SizeOfStruct = sizeof(IMAGEHLP_LINE);
          dwJunk = 0;
          if ( _SymInitialize && _SymGetLineFromAddr && _SymGetLineFromAddr(hProcess, dwOffset, &dwJunk, &il) )
          {
            fprintf(hFile, "\n                                     %s:%u", il.FileName, il.LineNumber);
            foundSomething = true;
          }

          if ( !foundSomething )
          {
            for ( std::vector<_customSymbolStore>::const_iterator i = customSymbols.begin(),
                  iend = customSymbols.end();
                  i != iend;
                  ++i )
            {
              if ( dwOffset >= i->dwStartAddress && dwOffset < i->dwEndAddress )
              {
                fprintf(hFile, "%s", i->name.c_str());
                foundSomething = true;
                break;
              }
            }
          }
        }

        if ( !foundSomething )
          fprintf(hFile, "  ----");

        fprintf(hFile, "\n");
      }
    }
    // Clean up
    if ( _SymInitialize && _SymCleanup )
      _SymCleanup(hProcess);
    fclose(hFile);
  } // ^if hFile

  ShowCursor(FALSE);

  // Call the previous exception filter
  return TopExceptionFilter.DefFilterProc(ep);
}
Exemplo n.º 12
0
	void PointerManager::setPointerVisible(bool _value)
	{
		ShowCursor(_value);
	}
Exemplo n.º 13
0
void SystemClass::InitializeWindows(int &_ScreenWidth, int &_ScreenHeight)
{
	WNDCLASSEX WindowClass;
	DEVMODE ScreenSettings;
	int PosX, PosY;

	ApplicationHandle = this;
	m_Instance = GetModuleHandle(NULL);
	m_ApplicationName = L"Project Potato";

	WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	WindowClass.lpfnWndProc = WndProc;
	WindowClass.cbClsExtra = 0;
	WindowClass.cbWndExtra = 0;
	WindowClass.hInstance = m_Instance;
	WindowClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	WindowClass.hIconSm = WindowClass.hIcon;
	WindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	WindowClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	WindowClass.lpszMenuName = NULL;
	WindowClass.lpszClassName = m_ApplicationName;
	WindowClass.cbSize = sizeof(WNDCLASSEX);

	RegisterClassEx(&WindowClass);

	_ScreenWidth = GetSystemMetrics(SM_CXSCREEN);
	_ScreenHeight = GetSystemMetrics(SM_CYSCREEN);

	if(FULL_SCREEN)
	{
		memset(&ScreenSettings, 0, sizeof(ScreenSettings));
		ScreenSettings.dmSize = sizeof(ScreenSettings);
		ScreenSettings.dmPelsWidth = (unsigned long)_ScreenWidth;
		ScreenSettings.dmPelsHeight = (unsigned long)_ScreenHeight;
		ScreenSettings.dmBitsPerPel = 32;
		ScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		ChangeDisplaySettings(&ScreenSettings, CDS_FULLSCREEN);

		PosX = PosY = 0;
	}

	else
	{
		_ScreenWidth = 800;
		_ScreenHeight = 600;

		PosX = (GetSystemMetrics(SM_CXSCREEN) - _ScreenWidth) / 2;
		PosY = (GetSystemMetrics(SM_CYSCREEN) - _ScreenHeight) / 2;
	}


	m_WindowHandle = CreateWindowEx(WS_EX_APPWINDOW, m_ApplicationName, m_ApplicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, PosX, PosY, _ScreenWidth, _ScreenHeight,
		NULL,NULL, m_Instance, NULL);

	ShowWindow(m_WindowHandle, SW_SHOW);
	SetForegroundWindow(m_WindowHandle);
	SetFocus(m_WindowHandle);

	ShowCursor(false);
}
Exemplo n.º 14
0
void ImageLoader::error(String txt)
{
	ShowCursor (1);  // show cursor
    MessageBox(0, txt.c_String(), "Error", MB_OK|MB_ICONERROR);
    PostQuitMessage(0);
}
Exemplo n.º 15
0
int Game_Init(void *parms,  int num_parms)
{
// this function is where you do all the initialization 
// for your game

int index;         // looping var
char filename[80]; // used to build up files names

// start up DirectDraw (replace the parms as you desire)
DDraw_Init(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP);

// joystick creation section ////////////////////////////////

/// start up DirectInput
DInput_Init();

// initialize the joystick
DInput_Init_Joystick(-24,24,-24,24);

///////////////////////////////////////////////////////////

// load the background
Load_Bitmap_File(&bitmap16bit, "MUSH_24.BMP");

// load in the four frames of the mushroom
for (index=0; index<4; index++)
    {
    // create mushroom bitmaps
    Create_Bitmap(&mushrooms[index],0,0,32,32,16);
    Load_Image_Bitmap16(&mushrooms[index],&bitmap16bit,index,0,BITMAP_EXTRACT_MODE_CELL);  
    } // end for index

// now create the bug blaster bob
Create_BOB(&blaster,0,0,32,32,3,
           BOB_ATTR_VISIBLE | BOB_ATTR_MULTI_ANIM | BOB_ATTR_ANIM_ONE_SHOT,
           DDSCAPS_SYSTEMMEMORY,0,16);

// load in the four frames of the mushroom
for (index=0; index < 3; index++)
     Load_Frame_BOB16(&blaster,&bitmap16bit,index,index,1,BITMAP_EXTRACT_MODE_CELL);  

// unload the bitmap file
Unload_Bitmap_File(&bitmap16bit);

// set the animation sequences for bug blaster
Load_Animation_BOB(&blaster,0,5,blaster_anim);

// set up stating state of bug blaster
Set_Pos_BOB(&blaster,320, 400);
Set_Anim_Speed_BOB(&blaster,3);

// create mushroom playfield bitmap
Create_Bitmap(&playfield,0,0,SCREEN_WIDTH,SCREEN_HEIGHT, 16);
playfield.attr |= BITMAP_ATTR_LOADED;

// fill in the background
Load_Bitmap_File(&bitmap16bit, "GRASS_24.BMP");

// load the grass bitmap image
Load_Image_Bitmap16(&playfield,&bitmap16bit,0,0,BITMAP_EXTRACT_MODE_ABS);
Unload_Bitmap_File(&bitmap16bit);

// seed random number generator
srand(Start_Clock());

// create the random mushroom patch
for (index=0; index<50; index++)
    {
    // select a mushroom
    int mush = rand()%4;

    // set mushroom to random position
    mushrooms[mush].x = rand()%(SCREEN_WIDTH-32);
    mushrooms[mush].y = rand()%(SCREEN_HEIGHT-128);

    // now draw the mushroom into playfield
    Draw_Bitmap16(&mushrooms[mush], playfield.buffer, playfield.width*2,1);

    } // end for

// hide the mouse
if (!WINDOWED_APP)
    ShowCursor(FALSE);

// return success
return(1);

} // end Game_Init
Exemplo n.º 16
0
BOOL CreateWindowGL (GL_Window* window)									// This Code Creates Our OpenGL Window
{
	DWORD windowStyle = WS_OVERLAPPEDWINDOW;							// Define Our Window Style
	DWORD windowExtendedStyle = WS_EX_APPWINDOW;						// Define The Window's Extended Style

	PIXELFORMATDESCRIPTOR pfd =											// pfd Tells Windows How We Want Things To Be
	{
		sizeof (PIXELFORMATDESCRIPTOR),									// Size Of This Pixel Format Descriptor
		1,																// Version Number
		PFD_DRAW_TO_WINDOW |											// Format Must Support Window
		PFD_SUPPORT_OPENGL |											// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,												// Must Support Double Buffering
		PFD_TYPE_RGBA,													// Request An RGBA Format
		window->init.bitsPerPixel,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,												// Color Bits Ignored
		0,																// No Alpha Buffer
		0,																// Shift Bit Ignored
		0,																// No Accumulation Buffer
		0, 0, 0, 0,														// Accumulation Bits Ignored
		16,																// 16Bit Z-Buffer (Depth Buffer)  
		0,																// No Stencil Buffer
		0,																// No Auxiliary Buffer
		PFD_MAIN_PLANE,													// Main Drawing Layer
		0,																// Reserved
		0, 0, 0															// Layer Masks Ignored
	};

	RECT windowRect = {0, 0, window->init.width, window->init.height};	// Define Our Window Coordinates

	GLuint PixelFormat;													// Will Hold The Selected Pixel Format

	if (window->init.isFullScreen == TRUE)								// Fullscreen Requested, Try Changing Video Modes
	{
		if (ChangeScreenResolution (window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE)
		{
			// Fullscreen Mode Failed.  Run In Windowed Mode Instead
			MessageBox (HWND_DESKTOP, "Mode Switch Failed.\nRunning In Windowed Mode.", "Error", MB_OK | MB_ICONEXCLAMATION);
			window->init.isFullScreen = FALSE;							// Set isFullscreen To False (Windowed Mode)
		}
		else															// Otherwise (If Fullscreen Mode Was Successful)
		{
			ShowCursor (FALSE);											// Turn Off The Cursor
			windowStyle = WS_POPUP;										// Set The WindowStyle To WS_POPUP (Popup Window)
			windowExtendedStyle |= WS_EX_TOPMOST;						// Set The Extended Window Style To WS_EX_TOPMOST
		}																// (Top Window Covering Everything Else)
	}
	else																// If Fullscreen Was Not Selected
	{
		// Adjust Window, Account For Window Borders
		AdjustWindowRectEx (&windowRect, windowStyle, 0, windowExtendedStyle);
	}

	// Create The OpenGL Window
	window->hWnd = CreateWindowEx (windowExtendedStyle,					// Extended Style
								   window->init.application->className,	// Class Name
								   window->init.title,					// Window Title
								   windowStyle,							// Window Style
								   0, 0,								// Window X,Y Position
								   windowRect.right - windowRect.left,	// Window Width
								   windowRect.bottom - windowRect.top,	// Window Height
								   HWND_DESKTOP,						// Desktop Is Window's Parent
								   0,									// No Menu
								   window->init.application->hInstance, // Pass The Window Instance
								   window);

	if (window->hWnd == 0)												// Was Window Creation A Success?
	{
		return FALSE;													// If Not Return False
	}

	window->hDC = GetDC (window->hWnd);									// Grab A Device Context For This Window
	if (window->hDC == 0)												// Did We Get A Device Context?
	{
		// Failed
		DestroyWindow (window->hWnd);									// Destroy The Window
		window->hWnd = 0;												// Zero The Window Handle
		return FALSE;													// Return False
	}

	PixelFormat = ChoosePixelFormat (window->hDC, &pfd);				// Find A Compatible Pixel Format
	if (PixelFormat == 0)												// Did We Find A Compatible Format?
	{
		// Failed
		ReleaseDC (window->hWnd, window->hDC);							// Release Our Device Context
		window->hDC = 0;												// Zero The Device Context
		DestroyWindow (window->hWnd);									// Destroy The Window
		window->hWnd = 0;												// Zero The Window Handle
		return FALSE;													// Return False
	}

	if (SetPixelFormat (window->hDC, PixelFormat, &pfd) == FALSE)		// Try To Set The Pixel Format
	{
		// Failed
		ReleaseDC (window->hWnd, window->hDC);							// Release Our Device Context
		window->hDC = 0;												// Zero The Device Context
		DestroyWindow (window->hWnd);									// Destroy The Window
		window->hWnd = 0;												// Zero The Window Handle
		return FALSE;													// Return False
	}

	window->hRC = wglCreateContext (window->hDC);						// Try To Get A Rendering Context
	if (window->hRC == 0)												// Did We Get A Rendering Context?
	{
		// Failed
		ReleaseDC (window->hWnd, window->hDC);							// Release Our Device Context
		window->hDC = 0;												// Zero The Device Context
		DestroyWindow (window->hWnd);									// Destroy The Window
		window->hWnd = 0;												// Zero The Window Handle
		return FALSE;													// Return False
	}

	// Make The Rendering Context Our Current Rendering Context
	if (wglMakeCurrent (window->hDC, window->hRC) == FALSE)
	{
		// Failed
		wglDeleteContext (window->hRC);									// Delete The Rendering Context
		window->hRC = 0;												// Zero The Rendering Context
		ReleaseDC (window->hWnd, window->hDC);							// Release Our Device Context
		window->hDC = 0;												// Zero The Device Context
		DestroyWindow (window->hWnd);									// Destroy The Window
		window->hWnd = 0;												// Zero The Window Handle
		return FALSE;													// Return False
	}

	ShowWindow (window->hWnd, SW_NORMAL);								// Make The Window Visible
	window->isVisible = TRUE;											// Set isVisible To True

	ReshapeGL (window->init.width, window->init.height);				// Reshape Our GL Window

	ZeroMemory (window->keys, sizeof (Keys));							// Clear All Keys

	window->lastTickCount = GetTickCount ();							// Get Tick Count

	return TRUE;														// Window Creating Was A Success
																		// Initialization Will Be Done In WM_CREATE
}
Exemplo n.º 17
0
void Window::initialize(BOOL isWindowed) 
{ 
	mIsWindowed = isWindowed;

	WNDCLASSEX windowAttributes;
	windowAttributes.cbSize         = sizeof(windowAttributes);
	windowAttributes.style          = CS_HREDRAW | CS_VREDRAW;
	windowAttributes.lpfnWndProc    = messageDispatcher;
	windowAttributes.cbClsExtra     = 0;
	windowAttributes.cbWndExtra     = 0;
	windowAttributes.hInstance      = mInstance;
	windowAttributes.hIcon          = LoadIcon(NULL, IDI_APPLICATION); // LoadIcon(NULL, :TODO: RESSOURCE);
	windowAttributes.hCursor        = LoadCursor(NULL, IDC_ARROW); // LoadIcon(NULL, :TODO: RESSOURCE);
	windowAttributes.hbrBackground  = (HBRUSH) GetStockObject(WHITE_BRUSH);
	windowAttributes.lpszMenuName   = NULL;
    windowAttributes.lpszClassName  = mClassName.c_str();
	windowAttributes.hIconSm        = LoadIcon(NULL, IDI_WINLOGO); // LoadIcon(NULL, :TODO: RESSOURCE);

	if( RegisterClassEx(&windowAttributes) == NULL )
	{
        dispose();
        MessageBox(mHandle, Utils::format("Couldn't register class %s", mClassName).c_str(), "Error", 0);
        return;
	}

	mWidth        = isWindowed ? mWidth  : GetSystemMetrics(SM_CXSCREEN);
	mHeight       = isWindowed ? mHeight : GetSystemMetrics(SM_CYSCREEN);
	INT x         = isWindowed ? (INT) ((GetSystemMetrics(SM_CXSCREEN) / 2) - (mWidth / 2.0f)) : 0;
	INT y         = isWindowed ? (INT) ((GetSystemMetrics(SM_CYSCREEN) / 2) - (mHeight / 2.0f)) : 0;
	DWORD style   = isWindowed ? WS_OVERLAPPEDWINDOW : WS_POPUP;
    DWORD exStyle = isWindowed ? WS_EX_APPWINDOW | WS_EX_WINDOWEDGE : WS_EX_APPWINDOW;

    if ( !isWindowed )
	{
		DEVMODE deviceSettings;								
		memset(&deviceSettings, 0, sizeof(deviceSettings));

		deviceSettings.dmSize = sizeof(deviceSettings);
		deviceSettings.dmPelsWidth	= mWidth;
		deviceSettings.dmPelsHeight	= mHeight;
		deviceSettings.dmBitsPerPel	= 32;
		deviceSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

        ShowCursor(FALSE);
		if ( ChangeDisplaySettings(&deviceSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL )
		{
			dispose();
			MessageBox(mHandle, "Couldn't set device mode settings", "Error", 0);
            return;
		}
	}

    RECT windowRect = {0, mWidth, 0, mHeight};
    AdjustWindowRectEx(&windowRect, style, FALSE, exStyle);

	if ( !(mHandle = CreateWindowEx(exStyle, mClassName.c_str(), mName.c_str(), style,  
                                    x, y, mWidth, mHeight, NULL, NULL, mInstance, this)) )
	{
        dispose();
        MessageBox(mHandle, Utils::format("Couldn't create window %s", mName).c_str(), "Error", 0);
        return;
	}

    if ( mRenderingContext != NULL )
    {
        mRenderingContext->setWindowHandle(mHandle);
        mRenderingContext->registerContext();
    }

	SetWindowPos(mHandle, HWND_TOP, x, y, mWidth, mHeight, SWP_NOZORDER | SWP_SHOWWINDOW);
    SetForegroundWindow(mHandle);					
	SetFocus(mHandle);

	// Don't show everything off yet
	hide();
}
Exemplo n.º 18
0
/////////////////////////////////////////////////////////
// switch cursor on/off
//
/////////////////////////////////////////////////////////
void gemw32window::cursorMess(bool state)
{
    ShowCursor(state);
}
Exemplo n.º 19
0
bool GLWindow::DisplayWindow(int _width, int _height)
{
	GLuint	  PixelFormat;			// Holds The Results After Searching For A Match
	DWORD	   dwExStyle;			  // Window Extended Style
	DWORD	   dwStyle;				// Window Style

	RECT rcdesktop;
	GetWindowRect(GetDesktopWindow(), &rcdesktop);

	if (conf.fullscreen())
	{
		nBackbufferWidth = rcdesktop.right - rcdesktop.left;
		nBackbufferHeight = rcdesktop.bottom - rcdesktop.top;

		dwExStyle = WS_EX_APPWINDOW;
		dwStyle = WS_POPUP;
		ShowCursor(false);
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
	}

	RECT rc;

	rc.left = 0;
	rc.top = 0;
	rc.right = nBackbufferWidth;
	rc.bottom = nBackbufferHeight;
	AdjustWindowRectEx(&rc, dwStyle, false, dwExStyle);
	int X = (rcdesktop.right - rcdesktop.left) / 2 - (rc.right - rc.left) / 2;
	int Y = (rcdesktop.bottom - rcdesktop.top) / 2 - (rc.bottom - rc.top) / 2;

	SetWindowLong(GShwnd, GWL_STYLE, dwStyle);
	SetWindowLong(GShwnd, GWL_EXSTYLE, dwExStyle);

	SetWindowPos(GShwnd, HWND_TOP, X, Y, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW);

	if (conf.fullscreen())
	{
		DEVMODE dmScreenSettings;
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth	= nBackbufferWidth;
		dmScreenSettings.dmPelsHeight   = nBackbufferHeight;
		dmScreenSettings.dmBitsPerPel   = 32;
		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 (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
				conf.setFullscreen(false);
			else
				return false;
		}
	}
	else
	{
		// change to default resolution
		ChangeDisplaySettings(NULL, 0);
	}

	PIXELFORMATDESCRIPTOR pfd =			 // pfd Tells Windows How We Want Things To Be

	{
		sizeof(PIXELFORMATDESCRIPTOR),			  // Size Of This Pixel Format Descriptor
		1,										  // Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,						   // Must Support Double Buffering
		PFD_TYPE_RGBA,							  // Request An RGBA Format
		32,										 // Select Our Color Depth
		0, 0, 0, 0, 0, 0,						   // Color Bits Ignored
		0,										  // 8bit Alpha Buffer
		0,										  // Shift Bit Ignored
		0,										  // No Accumulation Buffer
		0, 0, 0, 0,								 // Accumulation Bits Ignored
		24,										 // 24Bit Z-Buffer (Depth Buffer)
		8,										  // 8bit Stencil Buffer
		0,										  // No Auxiliary Buffer
		PFD_MAIN_PLANE,							 // Main Drawing Layer
		0,										  // Reserved
		0, 0, 0									 // Layer Masks Ignored
	};

	if (!(hDC = GetDC(GShwnd)))
	{
		MessageBox(NULL, "(1) Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
	{
		MessageBox(NULL, "(2) Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	if (!SetPixelFormat(hDC, PixelFormat, &pfd))
	{
		MessageBox(NULL, "(3) Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	if (!(hRC = wglCreateContext(hDC)))
	{
		MessageBox(NULL, "(4) Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	if (!wglMakeCurrent(hDC, hRC))
	{
		MessageBox(NULL, "(5) Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	UpdateWindow(GShwnd);

	return true;
}
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
{
	WNDCLASSEX wc;
	DEVMODE dmScreenSettings;
	int posX, posY;


	// Get an external pointer to this object.
	ApplicationHandle = this;

	// Get the instance of this application.
	m_hinstance = GetModuleHandle(NULL);

	// Give the application a name.
	m_applicationName = L"Engine";

	// Setup the windows class with default settings.
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = m_hinstance;
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hIconSm = wc.hIcon;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = m_applicationName;
	wc.cbSize = sizeof(WNDCLASSEX);
	
	// Register the window class.
	RegisterClassEx(&wc);

	// Determine the resolution of the clients desktop screen.
	screenWidth  = GetSystemMetrics(SM_CXSCREEN);
	screenHeight = GetSystemMetrics(SM_CYSCREEN);

	// Setup the screen settings depending on whether it is running in full screen or in windowed mode.
	if(FULL_SCREEN)
	{
		// If full screen set the screen to maximum size of the users desktop and 32bit.
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
		dmScreenSettings.dmSize       = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth  = (unsigned long)screenWidth;
		dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight;
		dmScreenSettings.dmBitsPerPel = 32;			
		dmScreenSettings.dmFields     = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

		// Change the display settings to full screen.
		ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);

		// Set the position of the window to the top left corner.
		posX = posY = 0;
	}
	else
	{
		// If windowed then set it to 800x600 resolution.
		screenWidth  = 800;
		screenHeight = 600;

		// Place the window in the middle of the screen.
		posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth)  / 2;
		posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
	}

	// Create the window with the screen settings and get the handle to it.
	m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, 
				WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,
				posX, posY, screenWidth, screenHeight, NULL, NULL, m_hinstance, NULL);

	// Bring the window up on the screen and set it as main focus.
	ShowWindow(m_hwnd, SW_SHOW);
	SetForegroundWindow(m_hwnd);
	SetFocus(m_hwnd);

	// Hide the mouse cursor.
	ShowCursor(false);

	return;
}
Exemplo n.º 21
0
int Game_Init(void *parms,  int num_parms)
{
// this function is where you do all the initialization 
// for your game

int index;         // looping var
char filename[80]; // used to build up files names

// start up DirectDraw (replace the parms as you desire)
DDraw_Init(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP);

// joystick creation section ////////////////////////////////

// first create the direct input object
if (DirectInput8Create(main_instance,DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&lpdi,NULL)!=DI_OK)
   return(0);

// first find the f*****g GUID of your particular joystick
lpdi->EnumDevices(DI8DEVCLASS_GAMECTRL, 
                  DI_Enum_Joysticks, 
                  &joystickGUID, 
                  DIEDFL_ATTACHEDONLY | DIEDFL_FORCEFEEDBACK); 

if (lpdi->CreateDevice(joystickGUID, &lpdijoy, NULL)!=DI_OK)
   return(0);

// set cooperation level
if (lpdijoy->SetCooperativeLevel(main_window_handle, 
	                 DISCL_EXCLUSIVE | DISCL_BACKGROUND)!=DI_OK)
   return(0);

// set data format
if (lpdijoy->SetDataFormat(&c_dfDIJoystick2)!=DI_OK)
   return(0);

// set the range of the joystick
DIPROPRANGE joy_axis_range;

// first x axis
joy_axis_range.lMin = -32;
joy_axis_range.lMax = 32;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_X;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);

// now y-axis
joy_axis_range.lMin = -32;
joy_axis_range.lMax = 32;

joy_axis_range.diph.dwSize       = sizeof(DIPROPRANGE); 
joy_axis_range.diph.dwHeaderSize = sizeof(DIPROPHEADER); 
joy_axis_range.diph.dwObj        = DIJOFS_Y;
joy_axis_range.diph.dwHow        = DIPH_BYOFFSET;

lpdijoy->SetProperty(DIPROP_RANGE,&joy_axis_range.diph);

// and now the dead band

DIPROPDWORD dead_band; // here's our property word

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_X;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// 4 will be used on both sides of the range +/-
dead_band.dwData            = 1000;

// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);

dead_band.diph.dwSize       = sizeof(dead_band);
dead_band.diph.dwHeaderSize = sizeof(dead_band.diph);
dead_band.diph.dwObj        = DIJOFS_Y;
dead_band.diph.dwHow        = DIPH_BYOFFSET;

// 4 will be used on both sides of the range +/-
dead_band.dwData            = 1000;

// finally set the property
lpdijoy->SetProperty(DIPROP_DEADZONE,&dead_band.diph);


// acquire the joystick
if (lpdijoy->Acquire()!=DI_OK)
   return(0);


// force feedback setup
DWORD      dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG       lDirection[2] = { 0, 0 };


DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

// setup the periodic structure
diPeriodic.dwMagnitude = DI_FFNOMINALMAX; 
diPeriodic.lOffset = 0; 
diPeriodic.dwPhase = 0; 
diPeriodic.dwPeriod = (DWORD) (0.05 * DI_SECONDS); 

// set the modulation envelope 
diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0; 
diEnvelope.dwAttackTime = (DWORD) (0.01 * DI_SECONDS); 
diEnvelope.dwFadeLevel = 0; 
diEnvelope.dwFadeTime = (DWORD) (3.0 * DI_SECONDS); 
 
// set up the effect structure itself
diEffect.dwSize = sizeof(DIEFFECT); 
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS; 
diEffect.dwDuration = (DWORD) INFINITE; // (1 * DI_SECONDS);
 
// set up details of effect
diEffect.dwSamplePeriod = 0;               // = default 
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0; // connect effect to trigger button
diEffect.dwTriggerRepeatInterval = 0;      
diEffect.cAxes = 2; 
diEffect.rgdwAxes = dwAxes; 
diEffect.rglDirection = &lDirection[0]; 
diEffect.lpEnvelope = &diEnvelope; 
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;  
 
// create the effect and get the interface to it 
lpdijoy->CreateEffect(GUID_Square,  // standard GUID 
                     &diEffect,      // where the data is
                     &lpdieffect,    // where to put interface pointer
                     NULL);          // no aggregation


///////////////////////////////////////////////////////////

// load the background
Load_Bitmap_File(&bitmap16bit, "MUSH_24.BMP");

// load in the four frames of the mushroom
for (index=0; index<4; index++)
    {
    // create mushroom bitmaps
    Create_Bitmap(&mushrooms[index],0,0,32,32,16);
    Load_Image_Bitmap16(&mushrooms[index],&bitmap16bit,index,0,BITMAP_EXTRACT_MODE_CELL);  
    } // end for index

// now create the bug blaster bob
Create_BOB(&blaster,0,0,32,32,3,
           BOB_ATTR_VISIBLE | BOB_ATTR_MULTI_ANIM | BOB_ATTR_ANIM_ONE_SHOT,
           DDSCAPS_SYSTEMMEMORY,0,16);

// load in the four frames of the mushroom
for (index=0; index<3; index++)
     Load_Frame_BOB16(&blaster,&bitmap16bit,index,index,1,BITMAP_EXTRACT_MODE_CELL);  

// unload the bitmap file
Unload_Bitmap_File(&bitmap16bit);

// set the animation sequences for bug blaster
Load_Animation_BOB(&blaster,0,5,blaster_anim);

// set up stating state of bug blaster
Set_Pos_BOB(&blaster,320, 400);
Set_Anim_Speed_BOB(&blaster,3);

// create mushroom playfield bitmap
Create_Bitmap(&playfield,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,16);
playfield.attr |= BITMAP_ATTR_LOADED;

// fill in the background
Load_Bitmap_File(&bitmap16bit, "GRASS_24.BMP");

// load the grass bitmap image
Load_Image_Bitmap16(&playfield,&bitmap16bit,0,0,BITMAP_EXTRACT_MODE_ABS);
Unload_Bitmap_File(&bitmap16bit);

// seed random number generator
srand(Start_Clock());

// create the random mushroom patch
for (index=0; index<50; index++)
    {
    // select a mushroom
    int mush = rand()%4;

    // set mushroom to random position
    mushrooms[mush].x = rand()%(SCREEN_WIDTH-32);
    mushrooms[mush].y = rand()%(SCREEN_HEIGHT-128);

    // now draw the mushroom into playfield
    Draw_Bitmap16(&mushrooms[mush], playfield.buffer, playfield.width*2,1);

    } // end for

// hide the mouse
if (!WINDOWED_APP)
   ShowCursor(FALSE);

// return success
return(1);

} // end Game_Init
Exemplo n.º 22
0
Font::Font(const char *file)
{
	Image image;

	hAlign = FONT_HORIZ_ALIGN_LEFT;
	vAlign = FONT_VERT_ALIGN_TOP;

	if( !image.Load(file) )
	{
		char error[100];
		sprintf(error, "Unable to Load font:\n\'%s\'", file);
		ShowCursor(true);
		MessageBox(NULL, error, "Error", MB_OK | MB_ICONERROR);
		ShowCursor(false);
		return;
	}

	image.FlipVertical();

	glGenTextures(1, &tex_id);
	glBindTexture(GL_TEXTURE_2D, tex_id);
	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_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.GetWidth(), image.GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.GetPixels());

	int size = image.GetWidth();
	step = size / 16;
	    
	list_id = glGenLists(256);

	int d1 = 0;
	int d2 = 0;
    
	for(int y = 0, i = 0; y < 16; y++)
	{

		for(int x = 0; x < 16; x++, i++)
		{
			unsigned char *ptr;

			d1 = 0;
			d2 = 9999;

			// Obter largura
			for(int j = 0; j < step; j++)
			{

				ptr = (unsigned char *)image.GetPixels() + (size * y * step + x * step + j) * 4;
				int k;
				for(k = 0; k < step; k++)
				{
					if(*(ptr + 3) != 0)
					{
						if(j < d2) d2 = j;
						if(j > d1) d1 = j;
					}
					ptr += size * 4;
				}
			}
			if(d2 != 9999) width[i] = (d1 - d2 + 1);
			else width[i] = 0;

			if(width[i] > maxWidth)
				maxWidth = width[i];

			d1 = 0;
			d2 = 9999;

			// Obter altura
			for(int j = 0; j < step; j++)
			{
				ptr = (unsigned char *)image.GetPixels() + (size * y * step + x * step + j * size) * 4;
				int k;
				for(k = 0; k < step; k++)
				{
					if(*(ptr + 3) != 0)
					{
						if(j < d2) d2 = j;
						if(j > d1) d1 = j;
					}
					ptr += 4;
				}
			}
			if(d2 != 9999) height[i] = d1 - d2 + 1;
			else height[i] = 0;

			if(height[i] > maxHeight)
				maxHeight = height[i];


			hOffset[i] = 0;

			// Obter distância vazia antes do início do caracter na horizontal
			for(int j = 0; j < step; j++)
			{
				ptr = (unsigned char *)image.GetPixels() + (size * y * step + x * step + j) * 4;
				int k;
				for(k = 0; k < step; k++)
				{
					if(*(ptr + 3) != 0) break;
					ptr += size * 4;
				}
				if(k != step) break;
				hOffset[i]++;
			}

			minVertOffset = 999;

			// Obter distância vazia mínima antes do início do caracter na vertical
			for(int j = 0; j < step; j++)
			{
				ptr = (unsigned char *)image.GetPixels() + (size * y * step + x * step + j * size) * 4;
				int k;
				for(k = 0; k < step; k++)
				{
					if(*(ptr + 3) != 0) break;
					ptr += 4;
				}
				if(k != step)
				{
					if(j - 1 < minVertOffset) minVertOffset = j - 1;
					break;
				}
			}
		}
	}

	hInterval = int(maxWidth / 6);
	vInterval = maxHeight + int(maxHeight / 6);

	for(int y = 0, i = 0; y < 16; y++)
	{
		for(int x = 0; x < 16; x++, i++)
		{
			float u1 = float(x * step + hOffset[i]) / (float)size;
			float v1 = float(y * step + minVertOffset) / (float)size;

			float u2 = u1 + (float)width[i] / (float)size;
			float v2 = v1 + (float)maxHeight / (float)size;

			glNewList(list_id + i, GL_COMPILE);
				glBegin(GL_TRIANGLE_STRIP);
					glTexCoord2f(u1, v2);
					glVertex2i(0, maxHeight);		
					glTexCoord2f(u2, v2);
					glVertex2i(width[i], maxHeight);		
					glTexCoord2f(u1, v1);
					glVertex2i(0, 0);
					glTexCoord2f(u2, v1);
					glVertex2i(width[i], 0);
				glEnd();
			glEndList();
		}
	}
}
Exemplo n.º 23
0
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) {
    GLuint      PixelFormat;            // Содержит результаты подбора глубины цвета
    WNDCLASS    wc;                     // Структура классов Windows
    DWORD       dwExStyle;              // Расширенный стиль окна
    DWORD       dwStyle;                // Стиль окна
    RECT        WindowRect;             // Получает значения верхнего левого и нижнего правого углов прямоугольника
    WindowRect.left = (long)0;          // Устанавливает значение лево (Left) в 0
    WindowRect.right = (long)width;     // Устанавливает значение право (Right) в требуемую ширину (Width)
    WindowRect.top = (long)0;           // Устанавливает значение верх (Top) в 0
    WindowRect.bottom = (long)height;   // Устанавливает значение низ (Bottom) в требуемую высоту (Height)

    fullscreen = fullscreenflag;        // Устанавливаем глобальный флвг Fullscreen

    hInstance           = GetModuleHandle(NULL);                // Захватываем Instance для нашего окна
    wc.style            = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;   // Перерисовываем по размеру, и получаем DC для окна.
    wc.lpfnWndProc      = (WNDPROC) WndProc;                    // WndProc Handles Messages
    wc.cbClsExtra       = 0;                                    // Нет дополнительных данных окна
    wc.cbWndExtra       = 0;                                    // Нет дополнительных данных окна
    wc.hInstance        = hInstance;                            // Установим Instance
    wc.hIcon            = LoadIcon(NULL, IDI_WINLOGO);          // Згрузим иконку по умолчанию
    wc.hCursor          = LoadCursor(NULL, IDC_ARROW);          // Згрузим стрелку курсора
    wc.hbrBackground    = NULL;                                 // Фон для GL не требуется
    wc.lpszMenuName     = NULL;                                 // Нам не нужны меню
    wc.lpszClassName    = "OpenGL";                             // Установим имя класса

    if (!RegisterClass(&wc)) {                                  // Попытаемся зарегистрировать класс окна
        MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", 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 избавляется от кнопки стариGets Rid Of Start Bar.
        if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
            // Если режиим не включился, предложим две возможности. Выйти или использовать оконный режим.
            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;     // Выбран оконный режим.  Fullscreen = FALSE
            } else {
                // Показать сообщение, что приложение закончило работу.
                MessageBox(NULL, "Program Will Now Close.", "ERROR", 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,                        // Расширенный стиль для окна
                                  "OpenGL",                           // Наименование класса
                                  title,                              // Заголовок окна
                                  dwStyle |                           // Определенный стиль окна
                                  WS_CLIPSIBLINGS |                   // Требуемый стиль окна
                                  WS_CLIPCHILDREN,                    // Требуемый стиль окна
                                  0, 0,                               // Местоположение окна
                                  WindowRect.right - WindowRect.left, // Вычисление ширины окна
                                  WindowRect.bottom - WindowRect.top, // Вычисление высоты окна
                                  NULL,                               // Нет родительского окна
                                  NULL,                               // Нет меню
                                  hInstance,                          // Instance
                                  NULL))) {                           // Не посылать сообщение по WM_CREATE
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    static  PIXELFORMATDESCRIPTOR pfd = {           // pfd сообщает Windows какие параметры мы хотим
        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,                                          // Нет альфа буферизации
        0,                                          // Бит сдвига игнорируется
        0,                                          // Нет буфера накопления
        0, 0, 0, 0,                                 // Биты накопления игнорируются
        16,                                         // 16битный Z-бувер (Буфер глубины)
        0,                                          // Нет буфера трафарета (stencil buffer)
        0,                                          // Нет вспомогательного буфера
        PFD_MAIN_PLANE,                             // Главная плоскость рисования
        0,                                          // Зарезервировано
        0, 0, 0                                     // Слой масок игнорируется
    };

    if (!(hDC = GetDC(hWnd))) {                     // Мы получили контекст устройства?
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { // Windows нашла соответствующий формат пикселя?
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    if(!SetPixelFormat(hDC, PixelFormat, &pfd)) {   // Мы можем установить формат пикселя?
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    if (!(hRC = wglCreateContext(hDC))) {           // Мы можем получить контекст изображения?
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    if(!wglMakeCurrent(hDC, hRC)) {                 // Пытаемся активировать контекст изображения
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Вернуть FALSE
    }

    ShowWindow(hWnd, SW_SHOW);                      // Показать окно
    SetForegroundWindow(hWnd);                      // Слегка увеличим приоритет
    SetFocus(hWnd);                                 // Устанавливаем фокус клавииатуры на окно
    ReSizeGLScene(width, height);                   // Устанавливаем наше GL окно с перспективой

    if (!InitGL()) {                                // Инициализируем наше GL окно
        KillGLWindow();                             // Инициализация дисплея
        MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE;                               // Возращает FALSE
    }

    return TRUE;                                    // Успешное завершение инициализациии
}
Exemplo n.º 24
0
	/**
	 * Destroys the window and its associated properties.  Be careful calling this if
	 * the window is already destroyed by the user!
	 */
	void Window::destroy()
	{
		// Check whether the window is fullscreen or not.
		if (this->isFullscreen)
		{
			// Change the display settings for the window to not be full screen.
			if (ChangeDisplaySettings(NULL, 0) != DISP_CHANGE_SUCCESSFUL)
			{
#ifdef _DEBUG
				// If debugging, display an error indicating where the program failed.
				MessageBox(NULL, (LPCWSTR)L"Changing display from fullscreen failed!", (LPCWSTR)L"Window Destroy ERROR", MB_OK | MB_ICONERROR);
#else
				// If not debugging, display a nice error code to reference for the user.
				MessageBox(NULL, (LPCWSTR)L"Error closing application!\nError code: WD" + FULLSCREEN_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR);
#endif
				// Make sure that the cursor is shown finally too.
				ShowCursor(true);
			}

			// Set the fullscreen boolean to false.
			this->isFullscreen = false;

			//		// Check if there is a device context and attempt to release it.
			//		if(deviceContext && !deviceContext->unused && !ReleaseDC(windowHandle, deviceContext))
			//		{
			//#ifdef _DEBUG
			//			// If debugging, display an error indicating that the device context couldn't be released.
			//			MessageBox(NULL, (LPCWSTR)L"Error releasing device context!", (LPCWSTR)L"Window Destroy ERROR", MB_OK | MB_ICONERROR);
			//#else
			//			// Display a nice error for the user if not debugging.
			//			MessageBox(NULL, (LPCWSTR)L"Error closing application!\nError code: WD" + DC_RELEASE_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR);
			//#endif
			//			// Set the device context to NULL.
			//			deviceContext = NULL;
			//		}
			//		// Check if there is a window handle and attempt to destroy the window associated with it.
			//		if(windowHandle && !windowHandle->unused && !DestroyWindow(windowHandle))
			//		{
			//#ifdef _DEBUG
			//			// If debugging, display an error indicating that the window handle couldn't be destroyed.
			//			MessageBox(NULL, (LPCWSTR)L"Error destroying window handle!", (LPCWSTR)L"Window Destroy ERROR", MB_OK | MB_ICONERROR);
			//#else
			//			// Display a nice error to the user if not debugging.
			//			MessageBox(NULL, (LPCWSTR)L"Error closing application!\nError code: WD" + WH_DESTROY_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR);
			//#endif
			//			// Set the window handle to NULL.
			//			windowHandle = NULL;
			//		}
			//		// Attempt to unregister the title associated with the window.
			//		if(!UnregisterClass(this->title, appInstance))
			//		{
			//#ifdef _DEBUG
			//			// If debugging, display  an error indicating that the window class could not be unregistered.
			//			MessageBox(NULL, (LPCWSTR)L"Error unregistering class!", (LPCWSTR)L"Window Destroy ERROR", MB_OK | MB_ICONERROR);
			//#else
			//			// Display a nice error to the user if not debugging.
			//			MessageBox(NULL, (LPCWSTR)L"Error closing application!\nError code: WD" + WC_UNREGISTER_ERROR, (LPCWSTR)L"Error", MB_OK | MB_ICONERROR);
			//#endif
			//			// Set the applications instance handle to NULL.
			//			appInstance = NULL;
			//		}
		}
	}
Exemplo n.º 25
0
const char* SingleOpenGLWindowImplT::Open(const std::string& Title_, unsigned int Width_, unsigned int Height_, char BPP_, bool FullScreen_)
{
#ifdef _WIN32
    if (WindowIsOpen) return "OpenGLWindow is already open.";

    hInstance=GetModuleHandle(NULL);   // 'GetModuleHandle(NULL)' entspricht 'hInstance' von 'WinMain()'.
    hWindow  =NULL;
    hDC      =NULL;
    hRC      =NULL;

    Title      =Title_;
    Width      =Width_;
    Height     =Height_;
    BPP        =BPP_;
    FullScreen =FullScreen_;
    IsMinimized=false;

    for (unsigned int c=0; c<256; c++) KeyboardState[c]=false;


    // 1. Window-Klasse ausfüllen und registrieren
    // *******************************************

    WNDCLASSEX MainWindowClass;

    MainWindowClass.cbSize       =sizeof(WNDCLASSEX);                       // Größe dieser Struktur
    MainWindowClass.style        =CS_VREDRAW | CS_HREDRAW | CS_OWNDC;       // Fensterklassenstil
    MainWindowClass.lpfnWndProc  =WinProc;                                  // Zeiger auf Handler-Funktion
    MainWindowClass.cbClsExtra   =0;                                        // Zusätzlicher Platz für KlassenInfos
    MainWindowClass.cbWndExtra   =0;                                        // Zusätzlicher Platz für FensterInfos
    MainWindowClass.hInstance    =hInstance;                                // Unsere Programm-ID
    MainWindowClass.hIcon        =LoadIcon(NULL, IDI_APPLICATION);          // Icon
    MainWindowClass.hIconSm      =LoadIcon(NULL, IDI_APPLICATION);          // Kleines Icon für Task-Bar
    MainWindowClass.hCursor      =LoadCursor(NULL, IDC_ARROW);              // Cursor
    MainWindowClass.hbrBackground=NULL;                                     // Hintergrund-Brush
    MainWindowClass.lpszMenuName =NULL;                                     // Menü
    MainWindowClass.lpszClassName="CafuMain";                               // Name dieser Fensterklasse

    if (!RegisterClassEx(&MainWindowClass)) return "Unable to register the window class.";


    // 2. Display Settings ggf. anpassen
    // *********************************

    if (FullScreen)
    {
        DEVMODE dmScreenSettings;

        memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
        dmScreenSettings.dmSize      =sizeof(dmScreenSettings);
        dmScreenSettings.dmPelsWidth =Width;
        dmScreenSettings.dmPelsHeight=Height;
        dmScreenSettings.dmBitsPerPel=BPP;
        dmScreenSettings.dmFields    =DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;

        // CDS_FULLSCREEN gets rid of start bar.
        if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
        {
            UnregisterClass("CafuMain", hInstance);
            return "Unable to change display settings.";
        }

        ShowCursor(false);
    }


    // 3. Window-Rectangle anpassen
    // ****************************

    unsigned int Style=FullScreen ? WS_POPUP : WS_OVERLAPPEDWINDOW;
    unsigned int ExStyle=WS_EX_APPWINDOW;

    RECT GLWindowRect;

    GLWindowRect.top   =0;
    GLWindowRect.left  =0;
    GLWindowRect.right =Width;
    GLWindowRect.bottom=Height;

    if (!AdjustWindowRectEx(&GLWindowRect, Style, false, ExStyle))
    {
        Close();
        return "Unable to adjust window rectangle.";
    }


    // 4. Window erzeugen
    // ******************

    hWindow=CreateWindowEx(ExStyle,                                    // Fensterstil (erweitert)
                           "CafuMain",                                 // Name der Fensterklasse
                           Title.c_str(),                              // Fenstertitel
                           Style | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,  // Fensterstil
                           0, // FullScreen ? 0 : CW_USEDEFAULT,       // X-Position
                           0, // FullScreen ? 0 : CW_USEDEFAULT,       // Y-Position
                           GLWindowRect.right-GLWindowRect.left,       // Breite
                           GLWindowRect.bottom-GLWindowRect.top,       // Höhe
                           NULL,                                       // Übergeordnetes Fenster
                           NULL,                                       // Menü
                           hInstance,                                  // Unsere Programm-ID
                           NULL);                                      // Zusätzliche Parameter

    if (!hWindow)
    {
        Close();
        return "Unable to create window.";
    }


    // 5. Device Context erfragen
    // **************************

    hDC=GetDC(hWindow);

    if (!hDC)
    {
        Close();
        return "Unable to obtain a GL device context.";
    }


    // 6. PixelFormat abfragen und setzen
    // **********************************

    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  =BPP;
    PFD.cDepthBits  =32;
    PFD.cStencilBits=8;
    PFD.iLayerType=PFD_MAIN_PLANE;

    int PixelFormat=ChoosePixelFormat(hDC, &PFD);

    if (!PixelFormat)
    {
        Close();
        return "Unable to choose a pixel format.";
    }

    if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PFD), &PFD))
    {
        Close();
        return "Unable to verify pixel format.";
    }

    static char ErrorMsg[1024];
    const char* s1="Selected pixel format mismatches:\n";
    const char* s2="\n\nThis is probably a problem with your video card (or its driver).\n"
                   "Please make sure you have the latest drivers installed.\n"
                   "If it still doesn't work, please let me know.\n"
                   "(Email to [email protected], and please include the above message!)";

    if ((PFD.dwFlags & PFD_DRAW_TO_WINDOW)!=PFD_DRAW_TO_WINDOW) { Close(); sprintf(ErrorMsg, "%sPFD_DRAW_TO_WINDOW is not supported.                 %s", s1,                   s2); return ErrorMsg; }
    if ((PFD.dwFlags & PFD_SUPPORT_OPENGL)!=PFD_SUPPORT_OPENGL) { Close(); sprintf(ErrorMsg, "%sOpenGL is not supported.                             %s", s1,                   s2); return ErrorMsg; }
    if ((PFD.dwFlags & PFD_DOUBLEBUFFER  )!=PFD_DOUBLEBUFFER  ) { Close(); sprintf(ErrorMsg, "%sDouble-buffering is not supported.                   %s", s1,                   s2); return ErrorMsg; }
    if (PFD.iPixelType!=PFD_TYPE_RGBA                         ) { Close(); sprintf(ErrorMsg, "%sPixel type RGBA is not supported.                    %s", s1,                   s2); return ErrorMsg; }
 // if (PFD.cColorBits<BPP                                    ) { Close(); sprintf(ErrorMsg, "%sOnly %u color bits found (at least 15 are required). %s", s1, PFD.cColorBits  , s2); return ErrorMsg; }
    if (PFD.cDepthBits<16                                     ) { Close(); sprintf(ErrorMsg, "%sOnly %u depth bits found (at least 16 are required). %s", s1, PFD.cDepthBits  , s2); return ErrorMsg; }
    if (PFD.cStencilBits<8                                    ) { Close(); sprintf(ErrorMsg, "%sOnly %u stencil bits found (at least 8 are required).%s", s1, PFD.cStencilBits, s2); return ErrorMsg; }
    if (PFD.iLayerType!=PFD_MAIN_PLANE                        ) { Close(); sprintf(ErrorMsg, "%sLayer type PFD_MAIN_PLANE is not supported.          %s", s1,                   s2); return ErrorMsg; }

    if(!SetPixelFormat(hDC, PixelFormat, &PFD))
    {
        Close();
        return "Unable to set the pixel format.";
    }


    // 7. Rendering Context erzeugen und aktivieren
    // ********************************************

    hRC=wglCreateContext(hDC);

    if (!hRC)
    {
        Close();
        return "Unable to create a GL rendering context.";
    }

    if(!wglMakeCurrent(hDC, hRC))
    {
        Close();
        return "Unable to activate the GL rendering context.";
    }


    // 8. Fenster anzeigen und einrichten
    // **********************************

    ShowWindow(hWindow, SW_SHOW);                      // Show the window.
    SetForegroundWindow(hWindow);                      // Slightly higher priority.
    SetFocus(hWindow);                                 // Sets keyboard focus to the window.


    // 8.1. DirectInput initialisieren
    // *******************************

    HRESULT hResult=DirectInput.Initialize(hInstance, hWindow);

    if (hResult!=DI_OK)
    {
        static char ErrorMsg[80];

        Close();
        sprintf(ErrorMsg, "Unable to initialize DirectInput!\nhResult=%u", hResult);
        return ErrorMsg;
    }
#else
    PostQuitMsgFlag=false;
    DisplayPtr     =XOpenDisplay(NULL);

    if (!DisplayPtr)                                return "Cannot open display.";
    if (!glXQueryExtension(DisplayPtr, NULL, NULL)) return "No GLX extension.";

#ifdef DEBUG
    int ExtVersionMajor=0;
    int ExtVersionMinor=0;
    if (glXQueryVersion(DisplayPtr, &ExtVersionMajor, &ExtVersionMinor)) printf("GLX version: %i.%i\n", ExtVersionMajor, ExtVersionMinor);
                                                                    else printf("GLX version could not be determined.\n");
#endif

    Title      =Title_;
    Width      =FullScreen_ ? DisplayWidth (DisplayPtr, DefaultScreen(DisplayPtr)) : Width_;
    Height     =FullScreen_ ? DisplayHeight(DisplayPtr, DefaultScreen(DisplayPtr)) : Height_;
    BPP        =BPP_;
    FullScreen =FullScreen_;
    IsMinimized=false;

    for (unsigned int c=0; c<256; c++) KeyboardState[c]=false;


    int VisualInfo_Features[] =
    {
        GLX_RGBA,
        GLX_RED_SIZE, 8,
        GLX_GREEN_SIZE, 8,
        GLX_BLUE_SIZE, 8,
        GLX_ALPHA_SIZE, 8,
        GLX_DEPTH_SIZE, 16,
        GLX_STENCIL_SIZE, 8,
        GLX_DOUBLEBUFFER,
        None
    };


    XVisualInfo* VisualInfo=glXChooseVisual(DisplayPtr, DefaultScreen(DisplayPtr), VisualInfo_Features);
    if (!VisualInfo) return "Cannot find visual. (You can possibly fix this by setting your desktop bit depth to 32 BPP. Just a guess.)";

    RC=glXCreateContext(DisplayPtr, VisualInfo, None, True);
    if (!RC) return "Cannot create GLX context.";


    XSetWindowAttributes WinAttribs;

    WinAttribs.colormap         =XCreateColormap(DisplayPtr, RootWindow(DisplayPtr, VisualInfo->screen), VisualInfo->visual, AllocNone);
    WinAttribs.border_pixel     =0;
    WinAttribs.override_redirect=True;
    WinAttribs.event_mask       =EventMask;

    Win=XCreateWindow(DisplayPtr,
                      RootWindow(DisplayPtr, VisualInfo->screen),
                      0, 0, Width, Height,
                      FullScreen ? 0 : 4,
                      VisualInfo->depth,
                      InputOutput,
                      VisualInfo->visual,
                      FullScreen ? CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect : CWColormap | CWEventMask,
                      &WinAttribs);

    if (!Win) return "Cannot open window.";


    XSizeHints SizeHints;

    SizeHints.flags =PSize | PMaxSize | PMinSize;
    SizeHints.width =SizeHints.max_width =SizeHints.min_width =Width;
    SizeHints.height=SizeHints.max_height=SizeHints.min_height=Height;

    XSetStandardProperties(DisplayPtr, Win, Title.c_str(), NULL, None, NULL, 0, &SizeHints);


    glXMakeCurrent(DisplayPtr, Win, RC);
    XMapRaised(DisplayPtr, Win);

    XEvent Event;

    do
    {
        XMaskEvent(DisplayPtr, StructureNotifyMask, &Event);
    } while ((Event.type!=MapNotify) || (Event.xmap.event!=Win));


    if (FullScreen) XSetInputFocus(DisplayPtr, Win, RevertToPointerRoot, CurrentTime);

    // Turn off auto-repeat.
    // XAutoRepeatOff(DisplayPtr);

    // Make the mouse cursor invisible.
    // This is necessary in order to have it not flickering it in mid-screen all the time.
    Pixmap CursorMask=XCreatePixmap(DisplayPtr, Win, 1, 1, 1);

    XGCValues xgc;
    xgc.function=GXclear;

    GC gc=XCreateGC(DisplayPtr, CursorMask, GCFunction, &xgc);

    XFillRectangle(DisplayPtr, CursorMask, gc, 0, 0, 1, 1);

    XColor DummyColor;
    DummyColor.pixel=0;
    DummyColor.red  =0;
    DummyColor.flags=4;

    Cursor cursor=XCreatePixmapCursor(DisplayPtr, CursorMask, CursorMask, &DummyColor, &DummyColor, 0, 0);

    XFreePixmap(DisplayPtr, CursorMask);
    XFreeGC(DisplayPtr, gc);
 // XDefineCursor(DisplayPtr, Win, XCreateFontCursor(DisplayPtr, XC_tcross));
    XDefineCursor(DisplayPtr, Win, cursor);
#endif

    Resize(Width, Height);                // Perspektivischen OpenGL Screen einrichten.


    // 9. OpenGL initialisieren
    // ************************

    /* if (atof((char const*)glGetString(GL_VERSION))<1.2)
    {
        Close();
        return "Need at least OpenGL version 1.2 to run. Please update your video board drivers.";
    } */

    // glDepthFunc(GL_LEQUAL);
    // glPolygonOffset(1.0, 1.0);

    // glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glShadeModel(GL_SMOOTH);                                        // Enables smooth shading.
    glClearColor(0.0, 0.0, 0.0, 0.0);                               // Black background.

    glClearDepth(1.0);                                              // Depth Buffer setup.
    glEnable(GL_DEPTH_TEST);                                        // Enables depth testing.

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);              // Really nice perspective calculations.

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SwapBuffers();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SwapBuffers();


    // 10. Geschafft: Keine Initialisierungsfehler
    // *******************************************

    WindowIsOpen=true;
    RenderingContextCounter++;
    return NULL;
}
Exemplo n.º 26
0
bool initialize()
{
    // Create components
    renderer = new Renderer();
    ai = new AI();
    input = new Input();
    sound = new Sound();

    quit = false;

    prevTime = 0;

    // TO DO: Load config.ini file to set up resolution and input settings



    // Set up the window (refernced a tutorial at http://www.rastertek.com/dx10tut02.html)
    WNDCLASSEX wc;
    DEVMODE screenSettings;


    // Get initial screen settings
    initialScreenSettings.dmSize = sizeof(DEVMODE);
    EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialScreenSettings);

    // Initialize screenSettings
    screenSettings.dmSize = sizeof(DEVMODE);
    EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &screenSettings);

    hInstance = GetModuleHandle(NULL);
    appName = "CPSC 585 Game";

    memset(&wc, 0, sizeof(WNDCLASSEX));

    wc.style = CS_HREDRAW | CS_VREDRAW;// | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.hInstance     = hInstance;
    wc.hIcon		 = LoadIcon(NULL, IDI_WINLOGO);
    wc.hIconSm       = wc.hIcon;
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    //wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszClassName = appName;
    wc.cbSize        = sizeof(WNDCLASSEX);

    // Register the window class.
    RegisterClassEx(&wc);

    unsigned long resx, resy;
    // Get screen resolution
    resx = initialScreenSettings.dmPelsWidth;
    resy = initialScreenSettings.dmPelsHeight;

    screenSettings.dmPelsWidth = resx; // Screen width
    screenSettings.dmPelsHeight = resy; // Screen height
    screenSettings.dmBitsPerPel = initialScreenSettings.dmBitsPerPel; // bit depth
    screenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

    if (ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
    {
        errorPopup("Changing display settings failed!");
        return false;
    }

    // Create the window at position 0, 0, and with the resolution defined just above
    hwnd = CreateWindowEx(WS_EX_APPWINDOW, appName, appName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,
                          0, 0, resx, resy, NULL, NULL, hInstance, NULL);

    // Bring up the window and set focus
    ShowWindow(hwnd, SW_SHOWNORMAL);


    SetForegroundWindow(hwnd);
    SetFocus(hwnd);

    // Capture the mouse
    SetCapture(hwnd);

    // Keep the mouse in the application area (maybe not necessary since we're doing fullscreen)
    RECT rect;
    GetWindowRect(hwnd, &rect);
    ClipCursor(&rect);

    // Hide the mouse
    ShowCursor(false);


    // Initialize components
    if (!renderer || !ai || !sound || !input)
    {
        errorPopup("Creating Renderer, AI, Sound, or Input component failed! [!renderer || !ai || !sound || !input]");
        return false;
    }

    // TO DO: Run the 'initialize' method for each component
    char* errorMsg = new char[128];
    if (!(renderer->initialize(resx, resy, hwnd, 1.0f, 1000.0f, 200, errorMsg)))
    {
        errorPopup(errorMsg);
        errorPopup("Renderer initialization failed!");
        return false;
    }

    ai->initialize(renderer, input);


    return true;
}
Exemplo n.º 27
0
void display_mac_alert(char *message, int error)
{
	window	*wind;
	d_event	event;
	int		fullscreen;
	bool	osX = FALSE;
	uint 	response;
	int16_t itemHit;

	// Handle Descent's windows properly
	if ((wind = window_get_front()))
		WINDOW_SEND_EVENT(wind, EVENT_WINDOW_DEACTIVATED);

	if ((fullscreen = gr_check_fullscreen()))
		gr_toggle_fullscreen();
	
	osX = ( Gestalt(gestaltSystemVersion, (long *) &response) == noErr)
		&& (response >= 0x01000 );

    ShowCursor();
	
	if (osX)
	{
#ifdef TARGET_API_MAC_CARBON
		DialogRef	alert;
		CFStringRef	error_text = CFSTR("Sorry, a critical error has occurred.");
		CFStringRef	text = NULL;

		text = CFStringCreateWithCString(CFAllocatorGetDefault(), message, kCFStringEncodingMacRoman);
		if (!text)
		{
			if (wind) WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
			return;
		}

		if (CreateStandardAlert(error ? kAlertStopAlert : kAlertNoteAlert, error ? error_text : text, error ? text : NULL, 0, &alert) != noErr)
		{
			CFRelease(text);
			if (wind) WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
			return;
		}
		
		RunStandardAlert(alert, 0, &itemHit);
		CFRelease(text);
#endif
	}
	else
	{
		Str255 	error_text = "\pSorry, a critical error has occurred.";
		Str255 	text;

#if !defined(MAC_OS_X_VERSION_MAX_ALLOWED) || (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_4)	// kill warning
		CopyCStringToPascal(message, text);
#endif
		StandardAlert(error ? kAlertStopAlert : kAlertNoteAlert, error ? error_text : text, error ? text : NULL, 0, &itemHit);
	}

	if ((wind = window_get_front()))
		WINDOW_SEND_EVENT(wind, EVENT_WINDOW_ACTIVATED);
	
	if (!error && fullscreen)
		gr_toggle_fullscreen();
}
Exemplo n.º 28
0
/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
*	title			- Title To Appear At The Top Of The Window				*
*	width			- Width Of The GL Window Or Full screen Mode			*
*	height			- Height Of The GL Window Or Full screen Mode			*
*	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
*	fullscreenflag	- Use Full screen Mode (TRUE) Or Windowed Mode (FALSE)	*/
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
	DWORD		dwExStyle;					// Window extended style
	DWORD		dwStyle;					// Window style
	RECT		WindowRect;					// Grabs rectangle upper left/lower right values
	WindowRect.left = (long)0;				// Set left value to 0
	WindowRect.right = (long)width;			// Set right value to requested width
	WindowRect.top = (long)0;				// Set top value to 0
	WindowRect.bottom = (long)height;		// Set bottom value to requested height

	g_bFullscreen = fullScreenFlag;			// Set the global full screen flag

	hInstance = GetModuleHandle(NULL);								// Grab an instance for out 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 = CLASSNAME;									// Set the class name

	if (!RegisterClass(&wc))										// Attempt to register the window class
	{
		MessageBox(NULL, MSG_REGISTERCLASSFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}
	if (g_bFullscreen)
	{
		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 failed, offer two options. Quit or use windowed mode.
			if (MessageBox(NULL, MSG_FULLSCREENNOTSUPPORT,
				ARTIST_NAME, MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
			{
				g_bFullscreen = FALSE;								// Windowed mode selected. Fullscreen = FALSE
			}
			else
			{
				// Pop up a message box letting user know the program is closing.
				MessageBox(NULL, MSG_PROGRAMNOTCLOSE,
					ERR_ERROR, MB_OK | MB_ICONSTOP);
				return FALSE;					// Return FALSE
			}
		}
	}
	if (g_bFullscreen)												// 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;				// Windows 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
		CLASSNAME,													// Class name
		title,														// Window title
		dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,				// Defined 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)))														// Don't pass anything to WM_CREATE
	{
		KillGLWindow();												// Reset the display
		MessageBox(NULL, MSG_CREATEWINDOWFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}
	static PIXELFORMATDESCRIPTOR pfd =								// pfd tells widows how we want things to be
	{
		sizeof(PIXELFORMATDESCRIPTOR),								// Size of this pixel format descriptor
		1,															// Version number
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,	// Format must support window/opengl/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
		DEPTHBUFFER,												// 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, MSG_CREATEGLDCFAILED,
			ERR_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, MSG_FINDPIXELFORMATFAILED,
			ERR_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, MSG_SETPIXELFORMATFAILED,
			ERR_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, MSG_CREATEGLRCFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;												// Return FALSE
	}

	if (!wglMakeCurrent(hDC, hRC))									// Try To Activate The Rendering Context
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_ACTIVEGLRCFAILED,
			ERR_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

	if (!InitGL())													// Initialize Our Newly Created GL Window
	{
		KillGLWindow();												// Reset The Display
		MessageBox(NULL, MSG_INITFAILED,
			ERR_ERROR, MB_OK | MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}
Exemplo n.º 29
0
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
	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	= "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
	}

	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

	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
}
Exemplo n.º 30
0
void z_ed3View::HideTheCursor (void)
{
	while (ShowCursor (FALSE) >= 0);
}