7893f058ac6cce409d0caf036e84f1afdaca9679
[freeglut] / src / freeglut_init.c
1 /*
2  * freeglut_init.c
3  *
4  * Various freeglut initialization functions.
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 2 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 #define FREEGLUT_BUILDING_LIB
29 #include <GL/freeglut.h>
30 #include "freeglut_internal.h"
31
32 #if TARGET_HOST_POSIX_X11
33 #include <limits.h>  /* LONG_MAX */
34 #endif
35
36 /*
37  * TODO BEFORE THE STABLE RELEASE:
38  *
39  *  fgDeinitialize()        -- Win32's OK, X11 needs the OS-specific
40  *                             deinitialization done
41  *  glutInitDisplayString() -- display mode string parsing
42  *
43  * Wouldn't it be cool to use gettext() for error messages? I just love
44  * bash saying  "nie znaleziono pliku" instead of "file not found" :)
45  * Is gettext easily portable?
46  */
47
48 /* -- GLOBAL VARIABLES ----------------------------------------------------- */
49
50 /*
51  * A structure pointed by g_pDisplay holds all information
52  * regarding the display, screen, root window etc.
53  */
54 SFG_Display fgDisplay;
55
56 /*
57  * The settings for the current freeglut session
58  */
59 SFG_State fgState = { { -1, -1, GL_FALSE },  /* Position */
60                       { 300, 300, GL_TRUE }, /* Size */
61                       GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH,  /* DisplayMode */
62                       GL_FALSE,              /* Initialised */
63                       GLUT_TRY_DIRECT_CONTEXT,  /* DirectContext */
64                       GL_FALSE,              /* ForceIconic */
65                       GL_FALSE,              /* UseCurrentContext */
66                       GL_FALSE,              /* GLDebugSwitch */
67                       GL_FALSE,              /* XSyncSwitch */
68                       GLUT_KEY_REPEAT_ON,    /* KeyRepeat */
69                       INVALID_MODIFIERS,     /* Modifiers */
70                       0,                     /* FPSInterval */
71                       0,                     /* SwapCount */
72                       0,                     /* SwapTime */
73                       0,                     /* Time */
74                       { NULL, NULL },         /* Timers */
75                       { NULL, NULL },         /* FreeTimers */
76                       NULL,                   /* IdleCallback */
77                       0,                      /* ActiveMenus */
78                       NULL,                   /* MenuStateCallback */
79                       NULL,                   /* MenuStatusCallback */
80                       { 640, 480, GL_TRUE },  /* GameModeSize */
81                       16,                     /* GameModeDepth */
82                       72,                     /* GameModeRefresh */
83                       GLUT_ACTION_EXIT,       /* ActionOnWindowClose */
84                       GLUT_EXEC_STATE_INIT,   /* ExecState */
85                       NULL,                   /* ProgramName */
86                       GL_FALSE,               /* JoysticksInitialised */
87                       GL_FALSE,               /* InputDevsInitialised */
88                       1,                      /* AuxiliaryBufferNumber */
89                       4,                      /* SampleNumber */
90                       1,                      /* MajorVersion */
91                       0,                      /* MajorVersion */
92                       0,                      /* ContextFlags */
93                       0                       /* ContextProfile */
94 };
95
96
97 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
98
99 #if TARGET_HOST_POSIX_X11
100
101 /* Return the atom associated with "name". */
102 static Atom fghGetAtom(const char * name)
103 {
104   return XInternAtom(fgDisplay.Display, name, False);
105 }
106
107 /*
108  * Check if "property" is set on "window".  The property's values are returned
109  * through "data".  If the property is set and is of type "type", return the
110  * number of elements in "data".  Return zero otherwise.  In both cases, use
111  * "Xfree()" to free "data".
112  */
113 static int fghGetWindowProperty(Window window,
114                                 Atom property,
115                                 Atom type,
116                                 unsigned char ** data)
117 {
118   /*
119    * Caller always has to use "Xfree()" to free "data", since
120    * "XGetWindowProperty() always allocates one extra byte in prop_return
121    * [i.e. "data"] (even if the property is zero length) [..]".
122    */
123
124   int status;  /*  Returned by "XGetWindowProperty". */
125
126   Atom          type_returned;
127   int           temp_format;             /*  Not used. */
128   unsigned long number_of_elements;
129   unsigned long temp_bytes_after;        /*  Not used. */
130
131
132   status = XGetWindowProperty(fgDisplay.Display,
133                               window,
134                               property,
135                               0,
136                               LONG_MAX,
137                               False,
138                               type,
139                               &type_returned,
140                               &temp_format,
141                               &number_of_elements,
142                               &temp_bytes_after,
143                               data);
144
145   FREEGLUT_INTERNAL_ERROR_EXIT(status == Success,
146                                "XGetWindowProperty failled",
147                                "fghGetWindowProperty");
148
149   if (type_returned != type)
150     {
151       number_of_elements = 0;
152     }
153
154   return number_of_elements;
155 }
156
157 /*  Check if the window manager is NET WM compliant. */
158 static int fghNetWMSupported(void)
159 {
160   Atom wm_check;
161   Window ** window_ptr_1;
162
163   int number_of_windows;
164   int net_wm_supported;
165
166
167   net_wm_supported = 0;
168
169   wm_check = fghGetAtom("_NET_SUPPORTING_WM_CHECK");
170   window_ptr_1 = malloc(sizeof(Window *));
171
172   /*
173    * Check that the window manager has set this property on the root window.
174    * The property must be the ID of a child window.
175    */
176   number_of_windows = fghGetWindowProperty(fgDisplay.RootWindow,
177                                            wm_check,
178                                            XA_WINDOW,
179                                            (unsigned char **) window_ptr_1);
180   if (number_of_windows == 1)
181     {
182       Window ** window_ptr_2;
183
184       window_ptr_2 = malloc(sizeof(Window *));
185
186       /* Check that the window has the same property set to the same value. */
187       number_of_windows = fghGetWindowProperty(**window_ptr_1,
188                                                wm_check,
189                                                XA_WINDOW,
190                                                (unsigned char **) window_ptr_2);
191       if ((number_of_windows == 1) && (**window_ptr_1 == **window_ptr_2))
192       {
193         /* NET WM compliant */
194         net_wm_supported = 1;
195       }
196
197       XFree(*window_ptr_2);
198       free(window_ptr_2);
199     }
200
201         XFree(*window_ptr_1);
202         free(window_ptr_1);
203
204         return net_wm_supported;
205 }
206
207 /*  Check if "hint" is present in "property" for "window". */
208 int fgHintPresent(Window window, Atom property, Atom hint)
209 {
210   Atom ** atoms_ptr;
211   int number_of_atoms;
212   int supported;
213   int i;
214
215   supported = 0;
216
217   atoms_ptr = malloc(sizeof(Atom *));
218   number_of_atoms = fghGetWindowProperty(window,
219                                          property,
220                                          XA_ATOM,
221                                          (unsigned char **) atoms_ptr);
222   for (i = 0; i < number_of_atoms; i++)
223     {
224       if ((*atoms_ptr)[i] == hint)
225       {
226           supported = 1;
227           break;
228       }
229     }
230
231   return supported;
232 }
233
234 #endif /*  TARGET_HOST_POSIX_X11  */
235
236
237 /*
238  * A call to this function should initialize all the display stuff...
239  */
240 static void fghInitialize( const char* displayName )
241 {
242 #if TARGET_HOST_POSIX_X11
243     fgDisplay.Display = XOpenDisplay( displayName );
244
245     if( fgDisplay.Display == NULL )
246         fgError( "failed to open display '%s'", XDisplayName( displayName ) );
247
248     if( !glXQueryExtension( fgDisplay.Display, NULL, NULL ) )
249         fgError( "OpenGL GLX extension not supported by display '%s'",
250             XDisplayName( displayName ) );
251
252     fgDisplay.Screen = DefaultScreen( fgDisplay.Display );
253     fgDisplay.RootWindow = RootWindow(
254         fgDisplay.Display,
255         fgDisplay.Screen
256     );
257
258     fgDisplay.ScreenWidth  = DisplayWidth(
259         fgDisplay.Display,
260         fgDisplay.Screen
261     );
262     fgDisplay.ScreenHeight = DisplayHeight(
263         fgDisplay.Display,
264         fgDisplay.Screen
265     );
266
267     fgDisplay.ScreenWidthMM = DisplayWidthMM(
268         fgDisplay.Display,
269         fgDisplay.Screen
270     );
271     fgDisplay.ScreenHeightMM = DisplayHeightMM(
272         fgDisplay.Display,
273         fgDisplay.Screen
274     );
275
276     fgDisplay.Connection = ConnectionNumber( fgDisplay.Display );
277
278     /* Create the window deletion atom */
279     fgDisplay.DeleteWindow = fghGetAtom("WM_DELETE_WINDOW");
280
281     /* Create the state and full screen atoms */
282     fgDisplay.State           = None;
283     fgDisplay.StateFullScreen = None;
284
285     if (fghNetWMSupported())
286     {
287       const Atom supported = fghGetAtom("_NET_SUPPORTED");
288       const Atom state     = fghGetAtom("_NET_WM_STATE");
289       
290       /* Check if the state hint is supported. */
291       if (fgHintPresent(fgDisplay.RootWindow, supported, state))
292       {
293         const Atom full_screen = fghGetAtom("_NET_WM_STATE_FULLSCREEN");
294         
295         fgDisplay.State = state;
296         
297         /* Check if the window manager supports full screen. */
298         /**  Check "_NET_WM_ALLOWED_ACTIONS" on our window instead? **/
299         if (fgHintPresent(fgDisplay.RootWindow, supported, full_screen))
300         {
301           fgDisplay.StateFullScreen = full_screen;
302         }
303       }
304     }
305
306 #elif TARGET_HOST_MS_WINDOWS
307
308     WNDCLASS wc;
309     ATOM atom;
310
311     /* What we need to do is to initialize the fgDisplay global structure here. */
312     fgDisplay.Instance = GetModuleHandle( NULL );
313
314     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
315
316     if( atom == 0 )
317     {
318         ZeroMemory( &wc, sizeof(WNDCLASS) );
319
320         /*
321          * Each of the windows should have its own device context, and we
322          * want redraw events during Vertical and Horizontal Resizes by
323          * the user.
324          *
325          * XXX Old code had "| CS_DBCLCKS" commented out.  Plans for the
326          * XXX future?  Dead-end idea?
327          */
328         wc.lpfnWndProc    = fgWindowProc;
329         wc.cbClsExtra     = 0;
330         wc.cbWndExtra     = 0;
331         wc.hInstance      = fgDisplay.Instance;
332         wc.hIcon          = LoadIcon( fgDisplay.Instance, _T("GLUT_ICON") );
333
334 #if defined(_WIN32_WCE)
335         wc.style          = CS_HREDRAW | CS_VREDRAW;
336 #else
337         wc.style          = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
338         if (!wc.hIcon)
339           wc.hIcon        = LoadIcon( NULL, IDI_WINLOGO );
340 #endif
341
342         wc.hCursor        = LoadCursor( NULL, IDC_ARROW );
343         wc.hbrBackground  = NULL;
344         wc.lpszMenuName   = NULL;
345         wc.lpszClassName  = _T("FREEGLUT");
346
347         /* Register the window class */
348         atom = RegisterClass( &wc );
349         FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Not Registered", "fghInitialize" );
350     }
351
352     /* The screen dimensions can be obtained via GetSystemMetrics() calls */
353     fgDisplay.ScreenWidth  = GetSystemMetrics( SM_CXSCREEN );
354     fgDisplay.ScreenHeight = GetSystemMetrics( SM_CYSCREEN );
355
356     {
357         HWND desktop = GetDesktopWindow( );
358         HDC  context = GetDC( desktop );
359
360         fgDisplay.ScreenWidthMM  = GetDeviceCaps( context, HORZSIZE );
361         fgDisplay.ScreenHeightMM = GetDeviceCaps( context, VERTSIZE );
362
363         ReleaseDC( desktop, context );
364     }
365
366     /* Set the timer granularity to 1 ms */
367     timeBeginPeriod ( 1 );
368
369 #endif
370
371     fgState.Initialised = GL_TRUE;
372
373     /* InputDevice uses GlutTimerFunc(), so fgState.Initialised must be TRUE */
374     fgInitialiseInputDevices();
375 }
376
377 /*
378  * Perform the freeglut deinitialization...
379  */
380 void fgDeinitialize( void )
381 {
382     SFG_Timer *timer;
383
384     if( !fgState.Initialised )
385     {
386         fgWarning( "fgDeinitialize(): "
387                    "no valid initialization has been performed" );
388         return;
389     }
390
391     /* If there was a menu created, destroy the rendering context */
392     if( fgStructure.MenuContext )
393     {
394 #if TARGET_HOST_POSIX_X11
395         /* Note that the MVisualInfo is not owned by the MenuContext! */
396         glXDestroyContext( fgDisplay.Display, fgStructure.MenuContext->MContext );
397 #endif
398         free( fgStructure.MenuContext );
399         fgStructure.MenuContext = NULL;
400     }
401
402     fgDestroyStructure( );
403
404     while( ( timer = fgState.Timers.First) )
405     {
406         fgListRemove( &fgState.Timers, &timer->Node );
407         free( timer );
408     }
409
410     while( ( timer = fgState.FreeTimers.First) )
411     {
412         fgListRemove( &fgState.FreeTimers, &timer->Node );
413         free( timer );
414     }
415
416 #if !defined(_WIN32_WCE)
417     if ( fgState.JoysticksInitialised )
418         fgJoystickClose( );
419
420     if ( fgState.InputDevsInitialised )
421         fgInputDeviceClose( );
422 #endif /* !defined(_WIN32_WCE) */
423     fgState.JoysticksInitialised = GL_FALSE;
424     fgState.InputDevsInitialised = GL_FALSE;
425
426     fgState.MajorVersion = 1;
427     fgState.MinorVersion = 0;
428     fgState.ContextFlags = 0;
429     fgState.ContextProfile = 0;
430
431     fgState.Initialised = GL_FALSE;
432
433     fgState.Position.X = -1;
434     fgState.Position.Y = -1;
435     fgState.Position.Use = GL_FALSE;
436
437     fgState.Size.X = 300;
438     fgState.Size.Y = 300;
439     fgState.Size.Use = GL_TRUE;
440
441     fgState.DisplayMode = GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH;
442
443     fgState.DirectContext  = GLUT_TRY_DIRECT_CONTEXT;
444     fgState.ForceIconic         = GL_FALSE;
445     fgState.UseCurrentContext   = GL_FALSE;
446     fgState.GLDebugSwitch       = GL_FALSE;
447     fgState.XSyncSwitch         = GL_FALSE;
448     fgState.ActionOnWindowClose = GLUT_ACTION_EXIT;
449     fgState.ExecState           = GLUT_EXEC_STATE_INIT;
450
451     fgState.KeyRepeat       = GLUT_KEY_REPEAT_ON;
452     fgState.Modifiers       = INVALID_MODIFIERS;
453
454     fgState.GameModeSize.X  = 640;
455     fgState.GameModeSize.Y  = 480;
456     fgState.GameModeDepth   =  16;
457     fgState.GameModeRefresh =  72;
458
459     fgListInit( &fgState.Timers );
460     fgListInit( &fgState.FreeTimers );
461
462     fgState.IdleCallback = NULL;
463     fgState.MenuStateCallback = ( FGCBMenuState )NULL;
464     fgState.MenuStatusCallback = ( FGCBMenuStatus )NULL;
465
466     fgState.SwapCount   = 0;
467     fgState.SwapTime    = 0;
468     fgState.FPSInterval = 0;
469
470     if( fgState.ProgramName )
471     {
472         free( fgState.ProgramName );
473         fgState.ProgramName = NULL;
474     }
475
476 #if TARGET_HOST_POSIX_X11
477
478     /*
479      * Make sure all X-client data we have created will be destroyed on
480      * display closing
481      */
482     XSetCloseDownMode( fgDisplay.Display, DestroyAll );
483
484     /*
485      * Close the display connection, destroying all windows we have
486      * created so far
487      */
488     XCloseDisplay( fgDisplay.Display );
489
490 #elif TARGET_HOST_MS_WINDOWS
491
492     /* Reset the timer granularity */
493     timeEndPeriod ( 1 );
494
495 #endif
496
497     fgState.Initialised = GL_FALSE;
498 }
499
500 /*
501  * Everything inside the following #ifndef is copied from the X sources.
502  */
503
504 #if TARGET_HOST_MS_WINDOWS
505
506 /*
507
508 Copyright 1985, 1986, 1987,1998  The Open Group
509
510 Permission to use, copy, modify, distribute, and sell this software and its
511 documentation for any purpose is hereby granted without fee, provided that
512 the above copyright notice appear in all copies and that both that
513 copyright notice and this permission notice appear in supporting
514 documentation.
515
516 The above copyright notice and this permission notice shall be included
517 in all copies or substantial portions of the Software.
518
519 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
520 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
521 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
522 IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
523 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
524 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
525 OTHER DEALINGS IN THE SOFTWARE.
526
527 Except as contained in this notice, the name of The Open Group shall
528 not be used in advertising or otherwise to promote the sale, use or
529 other dealings in this Software without prior written authorization
530 from The Open Group.
531
532 */
533
534 #define NoValue         0x0000
535 #define XValue          0x0001
536 #define YValue          0x0002
537 #define WidthValue      0x0004
538 #define HeightValue     0x0008
539 #define AllValues       0x000F
540 #define XNegative       0x0010
541 #define YNegative       0x0020
542
543 /*
544  *    XParseGeometry parses strings of the form
545  *   "=<width>x<height>{+-}<xoffset>{+-}<yoffset>", where
546  *   width, height, xoffset, and yoffset are unsigned integers.
547  *   Example:  "=80x24+300-49"
548  *   The equal sign is optional.
549  *   It returns a bitmask that indicates which of the four values
550  *   were actually found in the string.  For each value found,
551  *   the corresponding argument is updated;  for each value
552  *   not found, the corresponding argument is left unchanged.
553  */
554
555 static int
556 ReadInteger(char *string, char **NextString)
557 {
558     register int Result = 0;
559     int Sign = 1;
560
561     if (*string == '+')
562         string++;
563     else if (*string == '-')
564     {
565         string++;
566         Sign = -1;
567     }
568     for (; (*string >= '0') && (*string <= '9'); string++)
569     {
570         Result = (Result * 10) + (*string - '0');
571     }
572     *NextString = string;
573     if (Sign >= 0)
574         return Result;
575     else
576         return -Result;
577 }
578
579 static int XParseGeometry (
580     const char *string,
581     int *x,
582     int *y,
583     unsigned int *width,    /* RETURN */
584     unsigned int *height)    /* RETURN */
585 {
586     int mask = NoValue;
587     register char *strind;
588     unsigned int tempWidth = 0, tempHeight = 0;
589     int tempX = 0, tempY = 0;
590     char *nextCharacter;
591
592     if ( (string == NULL) || (*string == '\0'))
593       return mask;
594     if (*string == '=')
595         string++;  /* ignore possible '=' at beg of geometry spec */
596
597     strind = (char *)string;
598     if (*strind != '+' && *strind != '-' && *strind != 'x') {
599         tempWidth = ReadInteger(strind, &nextCharacter);
600         if (strind == nextCharacter)
601             return 0;
602         strind = nextCharacter;
603         mask |= WidthValue;
604     }
605
606     if (*strind == 'x' || *strind == 'X') {
607         strind++;
608         tempHeight = ReadInteger(strind, &nextCharacter);
609         if (strind == nextCharacter)
610             return 0;
611         strind = nextCharacter;
612         mask |= HeightValue;
613     }
614
615     if ((*strind == '+') || (*strind == '-')) {
616         if (*strind == '-') {
617             strind++;
618             tempX = -ReadInteger(strind, &nextCharacter);
619             if (strind == nextCharacter)
620                 return 0;
621             strind = nextCharacter;
622             mask |= XNegative;
623         }
624         else
625         {
626             strind++;
627             tempX = ReadInteger(strind, &nextCharacter);
628             if (strind == nextCharacter)
629                 return 0;
630             strind = nextCharacter;
631         }
632         mask |= XValue;
633         if ((*strind == '+') || (*strind == '-')) {
634             if (*strind == '-') {
635                 strind++;
636                 tempY = -ReadInteger(strind, &nextCharacter);
637                 if (strind == nextCharacter)
638                     return 0;
639                 strind = nextCharacter;
640                 mask |= YNegative;
641             }
642             else
643             {
644                 strind++;
645                 tempY = ReadInteger(strind, &nextCharacter);
646                 if (strind == nextCharacter)
647                     return 0;
648                 strind = nextCharacter;
649             }
650             mask |= YValue;
651         }
652     }
653
654     /* If strind isn't at the end of the string the it's an invalid
655        geometry specification. */
656
657     if (*strind != '\0') return 0;
658
659     if (mask & XValue)
660         *x = tempX;
661     if (mask & YValue)
662         *y = tempY;
663     if (mask & WidthValue)
664         *width = tempWidth;
665     if (mask & HeightValue)
666         *height = tempHeight;
667     return mask;
668 }
669 #endif
670
671 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
672
673 /*
674  * Perform initialization. This usually happens on the program startup
675  * and restarting after glutMainLoop termination...
676  */
677 void FGAPIENTRY glutInit( int* pargc, char** argv )
678 {
679     char* displayName = NULL;
680     char* geometry = NULL;
681     int i, j, argc = *pargc;
682
683     /* will return true for VC8 (VC2005) and higher */
684 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 )
685     size_t sLen;
686 #if HAVE_ERRNO
687     errno_t err;
688 #endif
689 #endif
690
691     if( fgState.Initialised )
692         fgError( "illegal glutInit() reinitialization attempt" );
693
694     if (pargc && *pargc && argv && *argv && **argv)
695     {
696         fgState.ProgramName = strdup (*argv);
697
698         if( !fgState.ProgramName )
699             fgError ("Could not allocate space for the program's name.");
700     }
701
702     fgCreateStructure( );
703
704     /* Get start time */
705     fgState.Time = fgSystemTime();
706
707     /* check if GLUT_FPS env var is set */
708 #ifndef _WIN32_WCE
709     {
710     /* will return true for VC8 (VC2005) and higher */
711 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 ) && HAVE_ERRNO
712         char* fps = NULL;
713         err = _dupenv_s( &fps, &sLen, "GLUT_FPS" );
714         if (err)
715             fgError("Error getting GLUT_FPS environment variable"); 
716 #else
717         const char *fps = getenv( "GLUT_FPS" );
718 #endif
719         if( fps )
720         {
721             int interval;
722             sscanf( fps, "%d", &interval );
723
724             if( interval <= 0 )
725                 fgState.FPSInterval = 5000;  /* 5000 millisecond default */
726             else
727                 fgState.FPSInterval = interval;
728         }
729     /* will return true for VC8 (VC2005) and higher */
730 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 ) && HAVE_ERRNO
731         free ( fps );  fps = NULL;  /* dupenv_s allocates a string that we must free */
732 #endif
733     }
734
735     /* will return true for VC8 (VC2005) and higher */
736 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 ) && HAVE_ERRNO
737     err = _dupenv_s( &displayName, &sLen, "DISPLAY" );
738     if (err)
739         fgError("Error getting DISPLAY environment variable");
740 #else
741     displayName = getenv( "DISPLAY" );
742 #endif
743
744     for( i = 1; i < argc; i++ )
745     {
746         if( strcmp( argv[ i ], "-display" ) == 0 )
747         {
748             if( ++i >= argc )
749                 fgError( "-display parameter must be followed by display name" );
750
751             displayName = argv[ i ];
752
753             argv[ i - 1 ] = NULL;
754             argv[ i     ] = NULL;
755             ( *pargc ) -= 2;
756         }
757         else if( strcmp( argv[ i ], "-geometry" ) == 0 )
758         {
759             if( ++i >= argc )
760                 fgError( "-geometry parameter must be followed by window "
761                          "geometry settings" );
762
763             geometry = argv[ i ];
764
765             argv[ i - 1 ] = NULL;
766             argv[ i     ] = NULL;
767             ( *pargc ) -= 2;
768         }
769         else if( strcmp( argv[ i ], "-direct" ) == 0)
770         {
771             if( fgState.DirectContext == GLUT_FORCE_INDIRECT_CONTEXT )
772                 fgError( "parameters ambiguity, -direct and -indirect "
773                     "cannot be both specified" );
774
775             fgState.DirectContext = GLUT_FORCE_DIRECT_CONTEXT;
776             argv[ i ] = NULL;
777             ( *pargc )--;
778         }
779         else if( strcmp( argv[ i ], "-indirect" ) == 0 )
780         {
781             if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
782                 fgError( "parameters ambiguity, -direct and -indirect "
783                     "cannot be both specified" );
784
785             fgState.DirectContext = GLUT_FORCE_INDIRECT_CONTEXT;
786             argv[ i ] = NULL;
787             (*pargc)--;
788         }
789         else if( strcmp( argv[ i ], "-iconic" ) == 0 )
790         {
791             fgState.ForceIconic = GL_TRUE;
792             argv[ i ] = NULL;
793             ( *pargc )--;
794         }
795         else if( strcmp( argv[ i ], "-gldebug" ) == 0 )
796         {
797             fgState.GLDebugSwitch = GL_TRUE;
798             argv[ i ] = NULL;
799             ( *pargc )--;
800         }
801         else if( strcmp( argv[ i ], "-sync" ) == 0 )
802         {
803             fgState.XSyncSwitch = GL_TRUE;
804             argv[ i ] = NULL;
805             ( *pargc )--;
806         }
807     }
808
809     /* Compact {argv}. */
810     for( i = j = 1; i < *pargc; i++, j++ )
811     {
812         /* Guaranteed to end because there are "*pargc" arguments left */
813         while ( argv[ j ] == NULL )
814             j++;
815         if ( i != j )
816             argv[ i ] = argv[ j ];
817     }
818
819 #endif /* _WIN32_WCE */
820
821     /*
822      * Have the display created now. If there wasn't a "-display"
823      * in the program arguments, we will use the DISPLAY environment
824      * variable for opening the X display (see code above):
825      */
826     fghInitialize( displayName );
827     /* will return true for VC8 (VC2005) and higher */
828 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 ) && HAVE_ERRNO
829     free ( displayName );  displayName = NULL;  /* dupenv_s allocates a string that we must free */
830 #endif
831
832     /*
833      * Geometry parsing deffered until here because we may need the screen
834      * size.
835      */
836
837     if (geometry )
838     {
839         unsigned int parsedWidth, parsedHeight;
840         int mask = XParseGeometry( geometry,
841                                    &fgState.Position.X, &fgState.Position.Y,
842                                    &parsedWidth, &parsedHeight );
843         /* TODO: Check for overflow? */
844         fgState.Size.X = parsedWidth;
845         fgState.Size.Y = parsedHeight;
846
847         if( (mask & (WidthValue|HeightValue)) == (WidthValue|HeightValue) )
848             fgState.Size.Use = GL_TRUE;
849
850         if( mask & XNegative )
851             fgState.Position.X += fgDisplay.ScreenWidth - fgState.Size.X;
852
853         if( mask & YNegative )
854             fgState.Position.Y += fgDisplay.ScreenHeight - fgState.Size.Y;
855
856         if( (mask & (XValue|YValue)) == (XValue|YValue) )
857             fgState.Position.Use = GL_TRUE;
858     }
859 }
860
861 #if TARGET_HOST_MS_WINDOWS
862 void (__cdecl *__glutExitFunc)( int return_value ) = NULL;
863
864 void FGAPIENTRY __glutInitWithExit( int *pargc, char **argv, void (__cdecl *exit_function)(int) )
865 {
866   __glutExitFunc = exit_function;
867   glutInit(pargc, argv);
868 }
869 #endif
870
871 /*
872  * Undoes all the "glutInit" stuff
873  */
874 void FGAPIENTRY glutExit ( void )
875 {
876   fgDeinitialize ();
877 }
878
879 /*
880  * Sets the default initial window position for new windows
881  */
882 void FGAPIENTRY glutInitWindowPosition( int x, int y )
883 {
884     fgState.Position.X = x;
885     fgState.Position.Y = y;
886
887     if( ( x >= 0 ) && ( y >= 0 ) )
888         fgState.Position.Use = GL_TRUE;
889     else
890         fgState.Position.Use = GL_FALSE;
891 }
892
893 /*
894  * Sets the default initial window size for new windows
895  */
896 void FGAPIENTRY glutInitWindowSize( int width, int height )
897 {
898     fgState.Size.X = width;
899     fgState.Size.Y = height;
900
901     if( ( width > 0 ) && ( height > 0 ) )
902         fgState.Size.Use = GL_TRUE;
903     else
904         fgState.Size.Use = GL_FALSE;
905 }
906
907 /*
908  * Sets the default display mode for all new windows
909  */
910 void FGAPIENTRY glutInitDisplayMode( unsigned int displayMode )
911 {
912     /* We will make use of this value when creating a new OpenGL context... */
913     fgState.DisplayMode = displayMode;
914 }
915
916
917 /* -- INIT DISPLAY STRING PARSING ------------------------------------------ */
918
919 static char* Tokens[] =
920 {
921     "alpha", "acca", "acc", "blue", "buffer", "conformant", "depth", "double",
922     "green", "index", "num", "red", "rgba", "rgb", "luminance", "stencil",
923     "single", "stereo", "samples", "slow", "win32pdf", "win32pfd", "xvisual",
924     "xstaticgray", "xgrayscale", "xstaticcolor", "xpseudocolor",
925     "xtruecolor", "xdirectcolor",
926     "xstaticgrey", "xgreyscale", "xstaticcolour", "xpseudocolour",
927     "xtruecolour", "xdirectcolour", "borderless", "aux"
928 };
929 #define NUM_TOKENS             (sizeof(Tokens) / sizeof(*Tokens))
930
931 void FGAPIENTRY glutInitDisplayString( const char* displayMode )
932 {
933     int glut_state_flag = 0 ;
934     /*
935      * Unpack a lot of options from a character string.  The options are
936      * delimited by blanks or tabs.
937      */
938     char *token ;
939     /* will return true for VC8 (VC2005) and higher */
940 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 )
941     char *next_token = NULL;
942 #endif
943     size_t len = strlen ( displayMode );
944     char *buffer = (char *)malloc ( (len+1) * sizeof(char) );
945     memcpy ( buffer, displayMode, len );
946     buffer[len] = '\0';
947
948     /* will return true for VC8 (VC2005) and higher */
949 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 )
950     token = strtok_s ( buffer, " \t", &next_token );
951 #else
952     token = strtok ( buffer, " \t" );
953 #endif
954     while ( token )
955     {
956         /* Process this token */
957         int i ;
958
959         /* Temporary fix:  Ignore any length specifications and at least
960          * process the basic token
961          * TODO:  Fix this permanently
962          */
963         size_t cleanlength = strcspn ( token, "=<>~!" );
964
965         for ( i = 0; i < NUM_TOKENS; i++ )
966         {
967             if ( strncmp ( token, Tokens[i], cleanlength ) == 0 ) break ;
968         }
969
970         switch ( i )
971         {
972         case 0 :  /* "alpha":  Alpha color buffer precision in bits */
973             glut_state_flag |= GLUT_ALPHA ;  /* Somebody fix this for me! */
974             break ;
975
976         case 1 :  /* "acca":  Red, green, blue, and alpha accumulation buffer
977                      precision in bits */
978             break ;
979
980         case 2 :  /* "acc":  Red, green, and blue accumulation buffer precision
981                      in bits with zero bits alpha */
982             glut_state_flag |= GLUT_ACCUM ;  /* Somebody fix this for me! */
983             break ;
984
985         case 3 :  /* "blue":  Blue color buffer precision in bits */
986             break ;
987
988         case 4 :  /* "buffer":  Number of bits in the color index color buffer
989                    */
990             break ;
991
992         case 5 :  /* "conformant":  Boolean indicating if the frame buffer
993                      configuration is conformant or not */
994             break ;
995
996         case 6 : /* "depth":  Number of bits of precsion in the depth buffer */
997             glut_state_flag |= GLUT_DEPTH ;  /* Somebody fix this for me! */
998             break ;
999
1000         case 7 :  /* "double":  Boolean indicating if the color buffer is
1001                      double buffered */
1002             glut_state_flag |= GLUT_DOUBLE ;
1003             break ;
1004
1005         case 8 :  /* "green":  Green color buffer precision in bits */
1006             break ;
1007
1008         case 9 :  /* "index":  Boolean if the color model is color index or not
1009                    */
1010             glut_state_flag |= GLUT_INDEX ;
1011             break ;
1012
1013         case 10 :  /* "num":  A special capability  name indicating where the
1014                       value represents the Nth frame buffer configuration
1015                       matching the description string */
1016             break ;
1017
1018         case 11 :  /* "red":  Red color buffer precision in bits */
1019             break ;
1020
1021         case 12 :  /* "rgba":  Number of bits of red, green, blue, and alpha in
1022                       the RGBA color buffer */
1023             glut_state_flag |= GLUT_RGBA ;  /* Somebody fix this for me! */
1024             break ;
1025
1026         case 13 :  /* "rgb":  Number of bits of red, green, and blue in the
1027                       RGBA color buffer with zero bits alpha */
1028             glut_state_flag |= GLUT_RGB ;  /* Somebody fix this for me! */
1029             break ;
1030
1031         case 14 :  /* "luminance":  Number of bits of red in the RGBA and zero
1032                       bits of green, blue (alpha not specified) of color buffer
1033                       precision */
1034             glut_state_flag |= GLUT_LUMINANCE ; /* Somebody fix this for me! */
1035             break ;
1036
1037         case 15 :  /* "stencil":  Number of bits in the stencil buffer */
1038             glut_state_flag |= GLUT_STENCIL;  /* Somebody fix this for me! */
1039             break ;
1040
1041         case 16 :  /* "single":  Boolean indicate the color buffer is single
1042                       buffered */
1043             glut_state_flag |= GLUT_SINGLE ;
1044             break ;
1045
1046         case 17 :  /* "stereo":  Boolean indicating the color buffer supports
1047                       OpenGL-style stereo */
1048             glut_state_flag |= GLUT_STEREO ;
1049             break ;
1050
1051         case 18 :  /* "samples":  Indicates the number of multisamples to use
1052                       based on GLX's SGIS_multisample extension (for
1053                       antialiasing) */
1054             glut_state_flag |= GLUT_MULTISAMPLE ; /*Somebody fix this for me!*/
1055             break ;
1056
1057         case 19 :  /* "slow":  Boolean indicating if the frame buffer
1058                       configuration is slow or not */
1059             break ;
1060
1061         case 20 :  /* "win32pdf": (incorrect spelling but was there before */
1062         case 21 :  /* "win32pfd":  matches the Win32 Pixel Format Descriptor by
1063                       number */
1064 #if TARGET_HOST_MS_WINDOWS
1065 #endif
1066             break ;
1067
1068         case 22 :  /* "xvisual":  matches the X visual ID by number */
1069 #if TARGET_HOST_POSIX_X11
1070 #endif
1071             break ;
1072
1073         case 23 :  /* "xstaticgray": */
1074         case 29 :  /* "xstaticgrey":  boolean indicating if the frame buffer
1075                       configuration's X visual is of type StaticGray */
1076 #if TARGET_HOST_POSIX_X11
1077 #endif
1078             break ;
1079
1080         case 24 :  /* "xgrayscale": */
1081         case 30 :  /* "xgreyscale":  boolean indicating if the frame buffer
1082                       configuration's X visual is of type GrayScale */
1083 #if TARGET_HOST_POSIX_X11
1084 #endif
1085             break ;
1086
1087         case 25 :  /* "xstaticcolor": */
1088         case 31 :  /* "xstaticcolour":  boolean indicating if the frame buffer
1089                       configuration's X visual is of type StaticColor */
1090 #if TARGET_HOST_POSIX_X11
1091 #endif
1092             break ;
1093
1094         case 26 :  /* "xpseudocolor": */
1095         case 32 :  /* "xpseudocolour":  boolean indicating if the frame buffer
1096                       configuration's X visual is of type PseudoColor */
1097 #if TARGET_HOST_POSIX_X11
1098 #endif
1099             break ;
1100
1101         case 27 :  /* "xtruecolor": */
1102         case 33 :  /* "xtruecolour":  boolean indicating if the frame buffer
1103                       configuration's X visual is of type TrueColor */
1104 #if TARGET_HOST_POSIX_X11
1105 #endif
1106             break ;
1107
1108         case 28 :  /* "xdirectcolor": */
1109         case 34 :  /* "xdirectcolour":  boolean indicating if the frame buffer
1110                       configuration's X visual is of type DirectColor */
1111 #if TARGET_HOST_POSIX_X11
1112 #endif
1113             break ;
1114
1115         case 35 :  /* "borderless":  windows should not have borders */
1116 #if TARGET_HOST_POSIX_X11
1117 #endif
1118             break ;
1119
1120         case 36 :  /* "aux":  some number of aux buffers */
1121             glut_state_flag |= GLUT_AUX;
1122             break ;
1123
1124         case 37 :  /* Unrecognized */
1125             fgWarning ( "WARNING - Display string token not recognized:  %s",
1126                         token );
1127             break ;
1128         }
1129
1130     /* will return true for VC8 (VC2005) and higher */
1131 #if TARGET_HOST_MS_WINDOWS && ( _MSC_VER >= 1400 )
1132         token = strtok_s ( NULL, " \t", &next_token );
1133 #else
1134         token = strtok ( NULL, " \t" );
1135 #endif
1136     }
1137
1138     free ( buffer );
1139
1140     /* We will make use of this value when creating a new OpenGL context... */
1141     fgState.DisplayMode = glut_state_flag;
1142 }
1143
1144 /* -- SETTING OPENGL 3.0 CONTEXT CREATION PARAMETERS ---------------------- */
1145
1146 void FGAPIENTRY glutInitContextVersion( int majorVersion, int minorVersion )
1147 {
1148     /* We will make use of these valuse when creating a new OpenGL context... */
1149     fgState.MajorVersion = majorVersion;
1150     fgState.MinorVersion = minorVersion;
1151 }
1152
1153
1154 void FGAPIENTRY glutInitContextFlags( int flags )
1155 {
1156     /* We will make use of this value when creating a new OpenGL context... */
1157     fgState.ContextFlags = flags;
1158 }
1159
1160 void FGAPIENTRY glutInitContextProfile( int profile )
1161 {
1162     /* We will make use of this value when creating a new OpenGL context... */
1163     fgState.ContextProfile = profile;
1164 }
1165
1166 /*** END OF FILE ***/