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