Trying again to change \"fgStructure.Window\" to \"fgStructure.CurrentWindow\" and...
[freeglut] / src / freeglut_gamemode.c
1 /*
2  * freeglut_gamemode.c
3  *
4  * The game mode handling code.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Thu Dec 16 1999
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #include <GL/freeglut.h>
29 #include "freeglut_internal.h"
30
31 /*
32  * TODO BEFORE THE STABLE RELEASE:
33  *
34  *  glutGameModeString()    -- missing
35  *  glutEnterGameMode()     -- X11 version
36  *  glutLeaveGameMode()     -- is that correct?
37  *  glutGameModeGet()       -- is that correct?
38  */
39
40
41 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
42
43 /*
44  * Remembers the current visual settings, so that
45  * we can change them and restore later...
46  */
47 static void fghRememberState( void )
48 {
49 #if TARGET_HOST_UNIX_X11
50
51     /*
52      * This highly depends on the XFree86 extensions,
53      * not approved as X Consortium standards
54      */
55 #   ifdef X_XF86VidModeGetModeLine
56
57
58     /*
59      * Remember the current ViewPort location of the screen to be able to
60      * restore the ViewPort on LeaveGameMode():
61      */
62     if( !XF86VidModeGetViewPort(
63              fgDisplay.Display,
64              fgDisplay.Screen,
65              &fgDisplay.DisplayViewPortX,
66              &fgDisplay.DisplayViewPortY ) )
67         fgWarning( "XF86VidModeGetViewPort failed" );
68
69     /*
70      * Remember the current pointer location before going fullscreen
71      * for restoring it later:
72      */
73     {
74         Window junk_window;
75         unsigned int mask;
76
77         XQueryPointer(
78             fgDisplay.Display, fgDisplay.RootWindow,
79             &junk_window, &junk_window,
80             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY,
81             &fgDisplay.DisplayPointerX, &fgDisplay.DisplayPointerY, &mask
82         );
83     }
84
85     /* Query the current display settings: */
86     fgDisplay.DisplayModeValid =
87       XF86VidModeGetModeLine(
88         fgDisplay.Display,
89         fgDisplay.Screen,
90         &fgDisplay.DisplayModeClock,
91         &fgDisplay.DisplayMode
92     );
93
94     if( !fgDisplay.DisplayModeValid )
95             fgWarning( "XF86VidModeGetModeLine failed" );
96
97 #   else
98     /*
99      * XXX warning fghRememberState: missing XFree86 video mode extensions,
100      * XXX game mode will not change screen resolution when activated
101      */
102 #   endif
103
104 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
105
106 /*    DEVMODE devMode; */
107
108     /* Grab the current desktop settings... */
109
110 /* hack to get around my stupid cross-gcc headers */
111 #define FREEGLUT_ENUM_CURRENT_SETTINGS -1
112
113     EnumDisplaySettings( NULL, FREEGLUT_ENUM_CURRENT_SETTINGS,
114                          &fgDisplay.DisplayMode );
115
116     /* Make sure we will be restoring all settings needed */
117     fgDisplay.DisplayMode.dmFields |=
118         DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
119
120 #endif
121 }
122
123 /*
124  * Restores the previously remembered visual settings
125  */
126 static void fghRestoreState( void )
127 {
128 #if TARGET_HOST_UNIX_X11
129
130 #   ifdef X_XF86VidModeGetAllModeLines
131     /* Restore the remembered pointer position: */
132     XWarpPointer(
133         fgDisplay.Display, None, fgDisplay.RootWindow, 0, 0, 0, 0,
134         fgDisplay.DisplayPointerX, fgDisplay.DisplayPointerY
135     );
136
137     /*
138      * This highly depends on the XFree86 extensions,
139      * not approved as X Consortium standards
140      */
141
142     if( fgDisplay.DisplayModeValid )
143     {
144         XF86VidModeModeInfo** displayModes;
145         int i, displayModesCount;
146
147         if( !XF86VidModeGetAllModeLines(
148                  fgDisplay.Display,
149                  fgDisplay.Screen,
150                  &displayModesCount,
151                  &displayModes ) )
152         {
153             fgWarning( "XF86VidModeGetAllModeLines failed" );
154             return;
155         }
156
157
158         /*
159          * Check every of the modes looking for one that matches our demands.
160          * If we find one, switch to it and restore the remembered viewport.
161          */
162         for( i = 0; i < displayModesCount; i++ )
163         {
164             if(displayModes[ i ]->hdisplay == fgDisplay.DisplayMode.hdisplay &&
165                displayModes[ i ]->vdisplay == fgDisplay.DisplayMode.vdisplay &&
166                displayModes[ i ]->dotclock == fgDisplay.DisplayModeClock )
167             {
168                 if( !XF86VidModeSwitchToMode(
169                          fgDisplay.Display,
170                          fgDisplay.Screen,
171                          displayModes[ i ] ) )
172                 {
173                     fgWarning( "XF86VidModeSwitchToMode failed" );
174                     break;
175                 }
176
177                 if( !XF86VidModeSetViewPort(
178                          fgDisplay.Display,
179                          fgDisplay.Screen,
180                          fgDisplay.DisplayViewPortX,
181                          fgDisplay.DisplayViewPortY ) )
182                     fgWarning( "XF86VidModeSetViewPort failed" );
183
184
185                 /*
186                  * For the case this would be the last X11 call the application
187                  * calls exit() we've to flush the X11 output queue to have the
188                  * commands sent to the X server before the application exits.
189                  */
190                 XFlush( fgDisplay.Display );
191
192                 break;
193             }
194         }
195         XFree( displayModes );
196     }
197
198 #   else
199     /*
200      * XXX warning fghRestoreState: missing XFree86 video mode extensions,
201      * XXX game mode will not change screen resolution when activated
202      */
203 #   endif
204
205 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
206
207     /* Restore the previously rememebered desktop display settings */
208     ChangeDisplaySettings( &fgDisplay.DisplayMode, 0 );
209
210 #endif
211 }
212
213 /*
214  * Checks the display mode settings against user's preferences
215  */
216 static GLboolean fghCheckDisplayMode( int width, int height, int depth, int refresh )
217 {
218     /* The desired values should be stored in fgState structure... */
219     return ( width == fgState.GameModeSize.X ) &&
220            ( height == fgState.GameModeSize.Y ) &&
221            ( depth == fgState.GameModeDepth ) &&
222            (refresh == fgState.GameModeRefresh );
223 }
224
225 /*
226  * Changes the current display mode to match user's settings
227  */
228 static GLboolean fghChangeDisplayMode( GLboolean haveToTest )
229 {
230     GLboolean success = GL_FALSE;
231 #if TARGET_HOST_UNIX_X11
232
233     /*
234      * This highly depends on the XFree86 extensions,
235      * not approved as X Consortium standards
236      */
237 #   ifdef X_XF86VidModeGetAllModeLines
238
239     /*
240      * This is also used by applcations which check modes by calling
241      * glutGameModeGet(GLUT_GAME_MODE_POSSIBLE), so allow the check:
242      */
243     if( haveToTest || fgDisplay.DisplayModeValid )
244     {
245         XF86VidModeModeInfo** displayModes;
246         int i, ignoreRefreshRate, displayModesCount;
247
248         if( !XF86VidModeGetAllModeLines(
249                  fgDisplay.Display,
250                  fgDisplay.Screen,
251                  &displayModesCount,
252                  &displayModes ) )
253         {
254             fgWarning( "XF86VidModeGetAllModeLines failed" );
255             return success;
256         }
257
258
259         /*
260          * Check every of the modes looking for one that matches our demands,
261          * ignoring the refresh rate if no exact match could be found.
262          */
263         for( ignoreRefreshRate = 0;
264              !success && ( ignoreRefreshRate <= 1 );
265              ignoreRefreshRate++)
266         {
267             for( i = 0;
268                  !success && ( i < displayModesCount );
269                  i++ )
270             {
271                 /* Compute the displays refresh rate, dotclock comes in kHz. */
272                 int refresh = ( displayModes[ i ]->dotclock * 1000 ) /
273                               ( displayModes[ i ]->htotal * displayModes[ i ]->vtotal );
274
275                 success = fghCheckDisplayMode( displayModes[ i ]->hdisplay,
276                                                displayModes[ i ]->vdisplay,
277                                                fgState.GameModeDepth,
278                                                ( ignoreRefreshRate ? fgState.GameModeRefresh : refresh ) );
279             }
280         }
281
282         if( !haveToTest && success ) {
283             if( !XF86VidModeSwitchToMode(
284                      fgDisplay.Display,
285                      fgDisplay.Screen,
286                      displayModes[ i ] ) )
287                 fgWarning( "XF86VidModeSwitchToMode failed" );
288         }
289
290         XFree( displayModes );
291     }
292
293 #   else
294     /*
295      * XXX warning fghChangeDisplayMode: missing XFree86 video mode extensions,
296      * XXX game mode will not change screen resolution when activated
297      */
298 #   endif
299
300 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
301
302     unsigned int    displayModes = 0, mode = 0xffffffff;
303     /* HDC      desktopDC; */
304     DEVMODE  devMode;
305
306     /*
307      * Enumerate the available display modes
308      * Try to get a complete match
309      */
310     while( EnumDisplaySettings( NULL, displayModes, &devMode ) )
311     {
312         /* Does the enumerated display mode match the user's preferences? */
313         if( fghCheckDisplayMode( devMode.dmPelsWidth,  devMode.dmPelsHeight,
314                                  devMode.dmBitsPerPel,
315                                  devMode.dmDisplayFrequency ) )
316         {
317             mode = displayModes;
318             break;
319         }
320         displayModes++;
321     }
322
323     if( mode == 0xffffffff )
324     {
325         /* then try without Display Frequency */
326         displayModes = 0;
327
328         /* Enumerate the available display modes */
329         while( EnumDisplaySettings( NULL, displayModes, &devMode ) )
330         {
331             /* then try without Display Frequency */
332             if( fghCheckDisplayMode( devMode.dmPelsWidth,
333                                      devMode.dmPelsHeight,
334                                      devMode.dmBitsPerPel,
335                                      fgState.GameModeRefresh ) )
336             {
337                 mode = displayModes;
338                 break;
339             }
340             displayModes++;
341         }
342     }
343
344     /* Did we find a matching display mode? */
345     if( mode != 0xffffffff )
346     {
347         int retVal = DISP_CHANGE_SUCCESSFUL;
348
349         /* Mark the values we want to modify in the display change call */
350         devMode.dmFields |=
351             DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;
352
353         retVal = ChangeDisplaySettings( &devMode, haveToTest ? CDS_TEST : 0 );
354
355         /* I don't know if it's really needed, but looks nice: */
356         success = (retVal == DISP_CHANGE_SUCCESSFUL) ||
357             (retVal == DISP_CHANGE_NOTUPDATED);
358
359         if( !haveToTest && success )
360         {
361             fgState.GameModeSize.X  = devMode.dmPelsWidth;
362             fgState.GameModeSize.Y  = devMode.dmPelsHeight;
363             fgState.GameModeDepth   = devMode.dmBitsPerPel;
364             fgState.GameModeRefresh = devMode.dmDisplayFrequency;
365         }
366     }
367
368 #endif
369
370     return success;
371 }
372
373
374 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
375
376 /*
377  * Sets the game mode display string
378  */
379 void FGAPIENTRY glutGameModeString( const char* string )
380 {
381     int width = 640, height = 480, depth = 16, refresh = 72;
382
383     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeString" );
384
385     /*
386      * This one seems a bit easier than glutInitDisplayString. The bad thing
387      * about it that I was unable to find the game mode string definition, so
388      * that I assumed it is: "[width]x[height]:[depth]@[refresh rate]", which
389      * appears in all GLUT game mode programs I have seen to date.
390      */
391     if( sscanf( string, "%ix%i:%i@%i", &width, &height, &depth, &refresh ) !=
392         4 )
393         if( sscanf( string, "%ix%i:%i", &width, &height, &depth ) != 3 )
394             if( sscanf( string, "%ix%i@%i", &width, &height, &refresh ) != 3 )
395                 if( sscanf( string, "%ix%i", &width, &height ) != 2 )
396                     if( sscanf( string, ":%i@%i", &depth, &refresh ) != 2 )
397                         if( sscanf( string, ":%i", &depth ) != 1 )
398                             if( sscanf( string, "@%i", &refresh ) != 1 )
399                                 fgWarning(
400                                     "unable to parse game mode string `%s'",
401                                     string
402                                 );
403
404     /* Hopefully it worked, and if not, we still have the default values */
405     fgState.GameModeSize.X  = width;
406     fgState.GameModeSize.Y  = height;
407     fgState.GameModeDepth   = depth;
408     fgState.GameModeRefresh = refresh;
409 }
410
411 /*
412  * Enters the game mode
413  */
414 int FGAPIENTRY glutEnterGameMode( void )
415 {
416     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutEnterGameMode" );
417
418     if( fgStructure.GameMode )
419         fgAddToWindowDestroyList( fgStructure.GameMode );
420     else
421         fghRememberState( );
422
423     if( ! fghChangeDisplayMode( GL_FALSE ) )
424     {
425         fgWarning( "failed to change screen settings" );
426         return FALSE;
427     }
428
429     fgStructure.GameMode = fgCreateWindow(
430         NULL, "FREEGLUT", 0, 0,
431         fgState.GameModeSize.X, fgState.GameModeSize.Y, GL_TRUE, GL_FALSE
432     );
433
434     fgStructure.GameMode->State.IsGameMode = GL_TRUE;
435
436 #if TARGET_HOST_UNIX_X11
437
438     /* Move the window up to the topleft corner */
439     XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle, 0, 0 );
440
441     /*
442      * Sync needed to avoid a real race, the Xserver must have really created
443      * the window before we can grab the pointer into it:
444      */
445     XSync( fgDisplay.Display, False );
446
447     /* Move the Pointer to the middle of the fullscreen window */
448     XWarpPointer(
449         fgDisplay.Display,
450         None,
451         fgDisplay.RootWindow,
452         0, 0, 0, 0,
453         fgState.GameModeSize.X/2, fgState.GameModeSize.Y/2
454     );
455
456     /*
457      * Grab the pointer to confine it into the window after the calls to
458      * XWrapPointer() which ensure that the pointer really enters the window.
459      *
460      * We also need to wait here until XGrabPointer() returns GrabSuccess,
461      * otherwise the new window is not viewable yet and if the next function
462      * (XSetInputFocus) is called with a not yet viewable window, it will exit
463      * the application which we have to aviod, so wait until it's viewable:
464      */
465     while( GrabSuccess != XGrabPointer(
466                fgDisplay.Display, fgStructure.GameMode->Window.Handle,
467                TRUE,
468                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask
469                | PointerMotionMask,
470                GrabModeAsync, GrabModeAsync,
471                fgStructure.GameMode->Window.Handle, None, CurrentTime) )
472         usleep( 100 );
473
474     /*
475      * Change input focus to the new window. This will exit the application
476      * if the new window is not viewable yet, see the XGrabPointer loop above.
477      */
478     XSetInputFocus(
479         fgDisplay.Display,
480         fgStructure.GameMode->Window.Handle,
481         RevertToNone,
482         CurrentTime
483     );
484
485 #   ifdef X_XF86VidModeSetViewPort
486
487     if( fgDisplay.DisplayModeValid )
488     {
489         int x, y;
490         Window child;
491
492         /* Change to viewport to the window topleft edge: */
493         if( !XF86VidModeSetViewPort( fgDisplay.Display, fgDisplay.Screen, 0, 0 ) )
494             fgWarning( "XF86VidModeSetViewPort failed" );
495
496         /*
497          * Final window repositioning: It could be avoided using an undecorated
498          * window using override_redirect, but this * would possily require
499          * more changes and investigation.
500          */
501
502         /* Get the current postion of the drawable area on screen */
503         XTranslateCoordinates(
504             fgDisplay.Display,
505             fgStructure.CurrentWindow->Window.Handle,
506             fgDisplay.RootWindow,
507             0, 0, &x, &y,
508             &child
509         );
510
511         /* Move the decorataions out of the topleft corner of the display */
512         XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
513                      -x, -y);
514     }
515
516 #endif
517
518     /* Grab the keyboard, too */
519     XGrabKeyboard(
520         fgDisplay.Display,
521         fgStructure.GameMode->Window.Handle,
522         FALSE,
523         GrabModeAsync, GrabModeAsync,
524         CurrentTime
525     );
526
527 #endif
528
529     return TRUE;
530 }
531
532 /*
533  * Leaves the game mode
534  */
535 void FGAPIENTRY glutLeaveGameMode( void )
536 {
537     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveGameMode" );
538
539     freeglut_return_if_fail( fgStructure.GameMode );
540
541     fgStructure.GameMode->State.IsGameMode = GL_FALSE;
542
543     fgAddToWindowDestroyList( fgStructure.GameMode );
544     fgStructure.GameMode = NULL;
545
546 #if TARGET_HOST_UNIX_X11
547
548     XUngrabPointer( fgDisplay.Display, CurrentTime );
549     XUngrabKeyboard( fgDisplay.Display, CurrentTime );
550
551 #endif
552
553     fghRestoreState();
554 }
555
556 /*
557  * Returns information concerning the freeglut game mode
558  */
559 int FGAPIENTRY glutGameModeGet( GLenum eWhat )
560 {
561     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGameModeGet" );
562
563     switch( eWhat )
564     {
565     case GLUT_GAME_MODE_ACTIVE:
566         return !!fgStructure.GameMode;
567
568     case GLUT_GAME_MODE_POSSIBLE:
569         return fghChangeDisplayMode( GL_TRUE );
570
571     case GLUT_GAME_MODE_WIDTH:
572         return fgState.GameModeSize.X;
573
574     case GLUT_GAME_MODE_HEIGHT:
575         return fgState.GameModeSize.Y;
576
577     case GLUT_GAME_MODE_PIXEL_DEPTH:
578         return fgState.GameModeDepth;
579
580     case GLUT_GAME_MODE_REFRESH_RATE:
581         return fgState.GameModeRefresh;
582
583     case GLUT_GAME_MODE_DISPLAY_CHANGED:
584         /*
585          * This is true if the game mode has been activated successfully..
586          */
587         return !!fgStructure.GameMode;
588     }
589
590     fgWarning( "Unknown gamemode get: %d", eWhat );
591     return -1;
592 }
593
594 /*** END OF FILE ***/