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