a0f2b95bdfb17f213ee3b7a2a153fbcfa58d04c3
[freeglut] / src / fg_internal.h
1 /*
2  * fg_internal.h
3  *
4  * The freeglut library private include file.
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 #ifndef  FREEGLUT_INTERNAL_H
29 #define  FREEGLUT_INTERNAL_H
30
31 #ifdef HAVE_CONFIG_H
32 #    include "config.h"
33 #endif
34
35 #include "fg_version.h"
36
37 /* Freeglut is intended to function under all Unix/X11 and Win32 platforms. */
38 /* XXX: Don't all MS-Windows compilers (except Cygwin) have _WIN32 defined?
39  * XXX: If so, remove the first set of defined()'s below.
40  */
41 #if !defined(TARGET_HOST_POSIX_X11) && !defined(TARGET_HOST_MS_WINDOWS) && !defined(TARGET_HOST_MAC_OSX) && !defined(TARGET_HOST_SOLARIS)
42 #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__) \
43     || defined(_WIN32) || defined(_WIN32_WCE) \
44     || ( defined(__CYGWIN__) && defined(X_DISPLAY_MISSING) )
45 #   define  TARGET_HOST_MS_WINDOWS 1
46
47 #elif defined (__ANDROID__)
48 #   define  TARGET_HOST_ANDROID  1
49
50 #elif defined (__QNXNTO__) || defined (__PLAYBOOK__)
51 #   define  TARGET_HOST_BLACKBERRY  1
52
53 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__sun)
54 #   if defined(FREEGLUT_WAYLAND)
55 #      define  TARGET_HOST_POSIX_WAYLAND  1
56 #   else
57 #      define  TARGET_HOST_POSIX_X11  1
58 #   endif
59
60 #elif defined(__APPLE__)
61 /* This is a placeholder until we get native OSX support ironed out -- JFF 11/18/09 */
62 #   define  TARGET_HOST_POSIX_X11  1
63 /* #   define  TARGET_HOST_MAC_OSX    1 */
64
65 #else
66 #   error "Unrecognized target host!"
67
68 #endif
69 #endif
70
71 /* Detect both SunPro and gcc compilers on Sun Solaris */
72 #if defined (__SVR4) && defined (__sun)
73 #   define TARGET_HOST_SOLARIS 1
74 #endif
75
76 #ifndef TARGET_HOST_MS_WINDOWS
77 #   define  TARGET_HOST_MS_WINDOWS     0
78 #endif
79
80 #ifndef TARGET_HOST_ANDROID
81 #   define  TARGET_HOST_ANDROID        0
82 #endif
83
84 #ifndef TARGET_HOST_BLACKBERRY
85 #   define  TARGET_HOST_BLACKBERRY     0
86 #endif
87
88 #ifndef  TARGET_HOST_POSIX_WAYLAND
89 #   define  TARGET_HOST_POSIX_WAYLAND  0
90 #endif
91
92 #ifndef  TARGET_HOST_POSIX_X11
93 #   define  TARGET_HOST_POSIX_X11      0
94 #endif
95
96 #ifndef  TARGET_HOST_MAC_OSX
97 #   define  TARGET_HOST_MAC_OSX        0
98 #endif
99
100 #ifndef  TARGET_HOST_SOLARIS
101 #   define  TARGET_HOST_SOLARIS        0
102 #endif
103
104 /* -- FIXED CONFIGURATION LIMITS ------------------------------------------- */
105
106 #define  FREEGLUT_MAX_MENUS            3
107
108 /* These files should be available on every platform. */
109 #include <stdio.h>
110 #include <string.h>
111 #include <math.h>
112 #include <stdlib.h>
113 #include <stdarg.h>
114
115 /* These are included based on autoconf directives. */
116 #ifdef HAVE_SYS_TYPES_H
117 #    include <sys/types.h>
118 #endif
119 #ifdef HAVE_UNISTD_H
120 #    include <unistd.h>
121 #endif
122 #ifdef TIME_WITH_SYS_TIME
123 #    include <sys/time.h>
124 #    include <time.h>
125 #elif defined(HAVE_SYS_TIME_H)
126 #    include <sys/time.h>
127 #else
128 #    include <time.h>
129 #endif
130
131 /* -- AUTOCONF HACKS --------------------------------------------------------*/
132
133 /* XXX: Update autoconf to avoid these.
134  * XXX: Are non-POSIX platforms intended not to use autoconf?
135  * If so, perhaps there should be a config_guess.h for them. Alternatively,
136  * config guesses could be placed above, just after the config.h exclusion.
137  */
138 #if defined(__FreeBSD__) || defined(__NetBSD__)
139 #    define HAVE_USB_JS 1
140 #    if defined(__NetBSD__) || ( defined(__FreeBSD__) && __FreeBSD_version >= 500000)
141 #        define HAVE_USBHID_H 1
142 #    endif
143 #endif
144
145 #if defined(_MSC_VER) || defined(__WATCOMC__)
146 /* strdup() is non-standard, for all but POSIX-2001 */
147 #define strdup   _strdup
148 #endif
149
150 /* M_PI is non-standard (defined by BSD, not ISO-C) */
151 #ifndef M_PI
152 #    define  M_PI  3.14159265358979323846
153 #endif
154
155 #ifdef HAVE_STDBOOL_H
156 #    include <stdbool.h>
157 #    ifndef TRUE
158 #        define TRUE true
159 #    endif
160 #    ifndef FALSE
161 #        define FALSE false
162 #    endif
163 #else
164 #    ifndef TRUE
165 #        define  TRUE  1
166 #    endif
167 #    ifndef FALSE
168 #        define  FALSE  0
169 #    endif
170 #endif
171
172 /* General defines */
173 #define INVALID_MODIFIERS 0xffffffff
174
175 /* FreeGLUT internal time type */
176 #if defined(HAVE_STDINT_H)
177 #   include <stdint.h>
178     typedef uint64_t fg_time_t;
179 #elif defined(HAVE_INTTYPES_H)
180 #   include <inttypes.h>
181     typedef uint64_t fg_time_t;
182 #elif defined(HAVE_U__INT64)
183     typedef unsigned __int64 fg_time_t;
184 #elif defined(HAVE_ULONG_LONG)
185     typedef unsigned long long fg_time_t;
186 #else
187     typedef unsigned long fg_time_t;
188 #endif
189
190 #ifndef __fg_unused
191 # ifdef __GNUC__
192 #  define __fg_unused __attribute__((unused))
193 # else
194 #  define __fg_unused
195 # endif
196 #endif
197
198 /* Platform-specific includes */
199 #if TARGET_HOST_POSIX_WAYLAND
200 #include "wayland/fg_internal_wl.h"
201 #endif
202 #if TARGET_HOST_POSIX_X11
203 #include "x11/fg_internal_x11.h"
204 #endif
205 #if TARGET_HOST_MS_WINDOWS
206 #include "mswin/fg_internal_mswin.h"
207 #endif
208 #if TARGET_HOST_ANDROID
209 #include "android/fg_internal_android.h"
210 #endif
211 #if TARGET_HOST_BLACKBERRY
212 #include "blackberry/fg_internal_blackberry.h"
213 #endif
214
215
216 /* -- GLOBAL TYPE DEFINITIONS ---------------------------------------------- */
217
218 /* Freeglut callbacks type definitions */
219 typedef void (* FGCBDisplay       )( void );
220 typedef void (* FGCBReshape       )( int, int );
221 typedef void (* FGCBPosition      )( int, int );
222 typedef void (* FGCBVisibility    )( int );
223 typedef void (* FGCBKeyboard      )( unsigned char, int, int );
224 typedef void (* FGCBKeyboardUp    )( unsigned char, int, int );
225 typedef void (* FGCBSpecial       )( int, int, int );
226 typedef void (* FGCBSpecialUp     )( int, int, int );
227 typedef void (* FGCBMouse         )( int, int, int, int );
228 typedef void (* FGCBMouseWheel    )( int, int, int, int );
229 typedef void (* FGCBMotion        )( int, int );
230 typedef void (* FGCBPassive       )( int, int );
231 typedef void (* FGCBEntry         )( int );
232 typedef void (* FGCBWindowStatus  )( int );
233 typedef void (* FGCBJoystick      )( unsigned int, int, int, int );
234 typedef void (* FGCBOverlayDisplay)( void );
235 typedef void (* FGCBSpaceMotion   )( int, int, int );
236 typedef void (* FGCBSpaceRotation )( int, int, int );
237 typedef void (* FGCBSpaceButton   )( int, int );
238 typedef void (* FGCBDials         )( int, int );
239 typedef void (* FGCBButtonBox     )( int, int );
240 typedef void (* FGCBTabletMotion  )( int, int );
241 typedef void (* FGCBTabletButton  )( int, int, int, int );
242 typedef void (* FGCBDestroy       )( void );    /* Used for both window and menu destroy callbacks */
243
244 typedef void (* FGCBMultiEntry   )( int, int );
245 typedef void (* FGCBMultiButton  )( int, int, int, int, int );
246 typedef void (* FGCBMultiMotion  )( int, int, int );
247 typedef void (* FGCBMultiPassive )( int, int, int );
248
249 typedef void (* FGCBInitContext)();
250 typedef void (* FGCBAppStatus)(int);
251
252 /* The global callbacks type definitions */
253 typedef void (* FGCBIdle          )( void );
254 typedef void (* FGCBTimer         )( int );
255 typedef void (* FGCBMenuState     )( int );
256 typedef void (* FGCBMenuStatus    )( int, int, int );
257
258 /* The callback used when creating/using menus */
259 typedef void (* FGCBMenu          )( int );
260
261 /* The FreeGLUT error/warning handler type definition */
262 typedef void (* FGError           ) ( const char *fmt, va_list ap);
263 typedef void (* FGWarning         ) ( const char *fmt, va_list ap);
264
265
266 /* A list structure */
267 typedef struct tagSFG_List SFG_List;
268 struct tagSFG_List
269 {
270     void *First;
271     void *Last;
272 };
273
274 /* A list node structure */
275 typedef struct tagSFG_Node SFG_Node;
276 struct tagSFG_Node
277 {
278     void *Next;
279     void *Prev;
280 };
281
282 /* A helper structure holding two ints and a boolean */
283 typedef struct tagSFG_XYUse SFG_XYUse;
284 struct tagSFG_XYUse
285 {
286     GLint           X, Y;               /* The two integers...               */
287     GLboolean       Use;                /* ...and a single boolean.          */
288 };
289
290 /*
291  * An enumeration containing the state of the GLUT execution:
292  * initializing, running, or stopping
293  */
294 typedef enum
295 {
296   GLUT_EXEC_STATE_INIT,
297   GLUT_EXEC_STATE_RUNNING,
298   GLUT_EXEC_STATE_STOP
299 } fgExecutionState ;
300
301 /* This structure holds different freeglut settings */
302 typedef struct tagSFG_State SFG_State;
303 struct tagSFG_State
304 {
305     SFG_XYUse        Position;             /* The default windows' position  */
306     SFG_XYUse        Size;                 /* The default windows' size      */
307     unsigned int     DisplayMode;          /* Display mode for new windows   */
308
309     GLboolean        Initialised;          /* freeglut has been initialised  */
310
311     int              DirectContext;        /* Direct rendering state         */
312
313     GLboolean        ForceIconic;          /* New top windows are iconified  */
314     GLboolean        UseCurrentContext;    /* New windows share with current */
315
316     GLboolean        GLDebugSwitch;        /* OpenGL state debugging switch  */
317     GLboolean        XSyncSwitch;          /* X11 sync protocol switch       */
318
319     int              KeyRepeat;            /* Global key repeat mode.        */
320     int              Modifiers;            /* Current ALT/SHIFT/CTRL state   */
321
322     GLuint           FPSInterval;          /* Interval between FPS printfs   */
323     GLuint           SwapCount;            /* Count of glutSwapBuffer calls  */
324     GLuint           SwapTime;             /* Time of last SwapBuffers       */
325
326     fg_time_t        Time;                 /* Time that glutInit was called  */
327     SFG_List         Timers;               /* The freeglut timer hooks       */
328     SFG_List         FreeTimers;           /* The unused timer hooks         */
329
330     FGCBIdle         IdleCallback;         /* The global idle callback       */
331
332     int              ActiveMenus;          /* Num. of currently active menus */
333     FGCBMenuState    MenuStateCallback;    /* Menu callbacks are global      */
334     FGCBMenuStatus   MenuStatusCallback;
335     void*            MenuFont;             /* Font to be used for newly created menus */
336
337     SFG_XYUse        GameModeSize;         /* Game mode screen's dimensions  */
338     int              GameModeDepth;        /* The pixel depth for game mode  */
339     int              GameModeRefresh;      /* The refresh rate for game mode */
340
341     int              ActionOnWindowClose; /* Action when user closes window  */
342
343     fgExecutionState ExecState;           /* Used for GLUT termination       */
344     char            *ProgramName;         /* Name of the invoking program    */
345     GLboolean        JoysticksInitialised;  /* Only initialize if application calls for them */
346     int              NumActiveJoysticks;    /* Number of active joysticks (callback defined and positive pollrate) -- if zero, don't poll joysticks */
347     GLboolean        InputDevsInitialised;  /* Only initialize if application calls for them */
348
349         int              MouseWheelTicks;      /* Number of ticks the mouse wheel has turned */
350
351     int              AuxiliaryBufferNumber;  /* Number of auxiliary buffers */
352     int              SampleNumber;         /*  Number of samples per pixel  */
353
354     GLboolean        SkipStaleMotion;      /* skip stale motion events */
355
356     GLboolean        StrokeFontDrawJoinDots;/* Draw dots between line segments of stroke fonts? */
357     GLboolean        AllowNegativeWindowPosition; /* GLUT, by default, doesn't allow negative window positions. Enable it? */
358
359     int              MajorVersion;         /* Major OpenGL context version  */
360     int              MinorVersion;         /* Minor OpenGL context version  */
361     int              ContextFlags;         /* OpenGL context flags          */
362     int              ContextProfile;       /* OpenGL context profile        */
363     int              HasOpenGL20;          /* fgInitGL2 could find all OpenGL 2.0 functions */
364     FGError          ErrorFunc;            /* User defined error handler    */
365     FGWarning        WarningFunc;          /* User defined warning handler  */
366 };
367
368 /* The structure used by display initialization in fg_init.c */
369 typedef struct tagSFG_Display SFG_Display;
370 struct tagSFG_Display
371 {
372         SFG_PlatformDisplay pDisplay;
373
374     int             ScreenWidth;        /* The screen's width in pixels      */
375     int             ScreenHeight;       /* The screen's height in pixels     */
376     int             ScreenWidthMM;      /* The screen's width in milimeters  */
377     int             ScreenHeightMM;     /* The screen's height in milimeters */
378 };
379
380
381 /* The user can create any number of timer hooks */
382 typedef struct tagSFG_Timer SFG_Timer;
383 struct tagSFG_Timer
384 {
385     SFG_Node        Node;
386     int             ID;                 /* The timer ID integer              */
387     FGCBTimer       Callback;           /* The timer callback                */
388     fg_time_t       TriggerTime;        /* The timer trigger time            */
389 };
390
391 /*
392  * A window and its OpenGL context. The contents of this structure
393  * are highly dependent on the target operating system we aim at...
394  */
395 typedef struct tagSFG_Context SFG_Context;
396 struct tagSFG_Context
397 {
398     SFG_WindowHandleType  Handle;    /* The window's handle                 */
399     SFG_WindowContextType Context;   /* The window's OpenGL/WGL context     */
400
401         SFG_PlatformContext pContext;    /* The window's FBConfig (X11) or device context (Windows) */
402
403     int             DoubleBuffered;  /* Treat the window as double-buffered */
404
405     /* When drawing geometry to vertex attribute buffers, user specifies
406      * the attribute indices for vertices, normals and/or texture coords
407      * to freeglut. Those are stored here
408      */
409     GLint           attribute_v_coord;
410     GLint           attribute_v_normal;
411     GLint           attribute_v_texture;
412 };
413
414
415 /*
416  * Bitmasks indicating the different kinds of
417  * actions that can be scheduled for a window.
418  */
419 #define GLUT_INIT_WORK        (1<<0)
420 #define GLUT_VISIBILITY_WORK  (1<<1)
421 #define GLUT_POSITION_WORK    (1<<2)
422 #define GLUT_SIZE_WORK        (1<<3)
423 #define GLUT_ZORDER_WORK      (1<<4)
424 #define GLUT_FULL_SCREEN_WORK (1<<5)
425 #define GLUT_DISPLAY_WORK     (1<<6)
426
427 /*
428  * An enumeration containing the state of the GLUT execution:
429  * initializing, running, or stopping
430  */
431 typedef enum
432 {
433   DesireHiddenState,
434   DesireIconicState,
435   DesireNormalState
436 } fgDesiredVisibility ;
437
438 /*
439  *  There is considerable confusion about the "right thing to
440  *  do" concerning window  size and position.  GLUT itself is
441  *  not consistent between Windows and UNIX/X11; since
442  *  platform independence is a virtue for "freeglut", we
443  *  decided to break with GLUT's behaviour.
444  *
445  *  Under UNIX/X11, it is apparently not possible to get the
446  *  window border sizes in order to subtract them off the
447  *  window's initial position until some time after the window
448  *  has been created.  Therefore we decided on the following
449  *  behaviour, both under Windows and under UNIX/X11:
450  *  - When you create a window with position (x,y) and size
451  *    (w,h), the upper left hand corner of the outside of the
452  *    window is at (x,y) and the size of the drawable area is
453  *    (w,h).
454  *  - When you query the size and position of the window--as
455  *    is happening here for Windows--"freeglut" will return
456  *    the size of the drawable area--the (w,h) that you
457  *    specified when you created the window--and the coordinates
458  *    of the upper left hand corner of the drawable area, i.e.
459  *    of the client rect--which is NOT the (x,y) you specified.
460  */
461 typedef struct tagSFG_WindowState SFG_WindowState;
462 struct tagSFG_WindowState   /* as per notes above, sizes always refer to the client area (thus without the window decorations) */
463 {
464     /* window state - size, position, look */
465     int             Xpos;               /* Window's top-left of client area, X-coordinate */
466     int             Ypos;               /* Window's top-left of client area, Y-coordinate */
467     int             Width;              /* Window's width in pixels          */
468     int             Height;             /* The same about the height         */
469     GLboolean       Visible;            /* Is the window visible now? Not using fgVisibilityState as we only care if visible or not */
470     int             Cursor;             /* The currently selected cursor style */
471     GLboolean       IsFullscreen;       /* is the window fullscreen?         */
472
473     /* FreeGLUT operations are deferred, that is, window moving, resizing,
474      * Z-order changing, making full screen or not do not happen immediately
475      * upon the user's request, but only in the next iteration of the main
476      * loop, before the display callback is called. This allows multiple
477      * reshape, position, etc requests to be combined into one and is
478      * compatible with the way GLUT does things. Callbacks get triggered
479      * based on the feedback/messages/notifications from the window manager.
480      * Below here we define what work should be done, as well as the relevant
481      * parameters for this work.
482      */
483     unsigned int    WorkMask;           /* work (resize, etc) to be done on the window */
484     int             DesiredXpos;        /* desired X location */
485     int             DesiredYpos;        /* desired Y location */
486     int             DesiredWidth;       /* desired window width */
487     int             DesiredHeight;      /* desired window height */
488     int             DesiredZOrder;      /* desired window Z Order position */
489     fgDesiredVisibility DesiredVisibility;/* desired visibility (hidden, iconic, shown/normal) */
490
491         SFG_PlatformWindowState pWState;    /* Window width/height (X11) or rectangle/style (Windows) from before a resize, and other stuff only needed on specific platforms */
492
493     long            JoystickPollRate;   /* The joystick polling rate         */
494     fg_time_t       JoystickLastPoll;   /* When the last poll happened       */
495
496     int             MouseX, MouseY;     /* The most recent mouse position    */
497
498     GLboolean       IgnoreKeyRepeat;    /* Whether to ignore key repeat.     */
499
500     GLboolean       VisualizeNormals;   /* When drawing objects, draw vectors representing the normals as well? */
501 };
502
503
504 /*
505  * A generic function pointer.  We should really use the GLUTproc type
506  * defined in freeglut_ext.h, but if we include that header in this file
507  * a bunch of other stuff (font-related) blows up!
508  */
509 typedef void (*SFG_Proc)();
510
511
512 /*
513  * SET_WCB() is used as:
514  *
515  *     SET_WCB( window, cbname, func );
516  *
517  * ...where {window} is the freeglut window to set the callback,
518  *          {cbname} is the window-specific callback to set,
519  *          {func} is a function-pointer.
520  *
521  * Originally, {FETCH_WCB( ... ) = func} was rather sloppily used,
522  * but this can cause warnings because the FETCH_WCB() macro type-
523  * casts its result, and a type-cast value shouldn't be an lvalue.
524  *
525  * The {if( FETCH_WCB( ... ) != func )} test is to do type-checking
526  * and for no other reason.  Since it's hidden in the macro, the
527  * ugliness is felt to be rather benign.
528  */
529 #define SET_WCB(window,cbname,func)                            \
530 do                                                             \
531 {                                                              \
532     if( FETCH_WCB( window, cbname ) != (SFG_Proc)(func) )      \
533         (((window).CallBacks[WCB_ ## cbname]) = (SFG_Proc)(func)); \
534 } while( 0 )
535
536 /*
537  * FETCH_WCB() is used as:
538  *
539  *     FETCH_WCB( window, cbname );
540  *
541  * ...where {window} is the freeglut window to fetch the callback from,
542  *          {cbname} is the window-specific callback to fetch.
543  *
544  * The result is correctly type-cast to the callback function pointer
545  * type.
546  */
547 #define FETCH_WCB(window,cbname) \
548     ((window).CallBacks[WCB_ ## cbname])
549
550 /*
551  * INVOKE_WCB() is used as:
552  *
553  *     INVOKE_WCB( window, cbname, ( arg_list ) );
554  *
555  * ...where {window} is the freeglut window,
556  *          {cbname} is the window-specific callback to be invoked,
557  *          {(arg_list)} is the parameter list.
558  *
559  * The callback is invoked as:
560  *
561  *    callback( arg_list );
562  *
563  * ...so the parentheses are REQUIRED in the {arg_list}.
564  *
565  * NOTE that it does a sanity-check and also sets the
566  * current window.
567  *
568  */
569 #if TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE) /* FIXME: also WinCE? */
570 #define INVOKE_WCB(window,cbname,arg_list)    \
571 do                                            \
572 {                                             \
573     if( FETCH_WCB( window, cbname ) )         \
574     {                                         \
575         FGCB ## cbname func = (FGCB ## cbname)(FETCH_WCB( window, cbname )); \
576         fgSetWindow( &window );               \
577         func arg_list;                        \
578     }                                         \
579 } while( 0 )
580 #else
581 #define INVOKE_WCB(window,cbname,arg_list)    \
582 do                                            \
583 {                                             \
584     if( FETCH_WCB( window, cbname ) )         \
585     {                                         \
586         fgSetWindow( &window );               \
587         ((FGCB ## cbname)FETCH_WCB( window, cbname )) arg_list; \
588     }                                         \
589 } while( 0 )
590 #endif
591
592 /*
593  * The window callbacks the user can supply us with. Should be kept portable.
594  *
595  * This enumeration provides the freeglut CallBack numbers.
596  * The symbolic constants are indices into a window's array of
597  * function callbacks.  The names are formed by splicing a common
598  * prefix onto the callback's base name.  (This was originally
599  * done so that an early stage of development could live side-by-
600  * side with the old callback code.  The old callback code used
601  * the bare callback's name as a structure member, so I used a
602  * prefix for the array index name.)
603  */
604 enum
605 {
606     WCB_Display,
607     WCB_Reshape,
608     WCB_Position,
609     WCB_Keyboard,
610     WCB_KeyboardUp,
611     WCB_Special,
612     WCB_SpecialUp,
613     WCB_Mouse,
614     WCB_MouseWheel,
615     WCB_Motion,
616     WCB_Passive,
617     WCB_Entry,
618     WCB_Visibility,
619     WCB_WindowStatus,
620     WCB_Joystick,
621     WCB_Destroy,
622
623     /* Multi-Pointer X and touch related */
624     WCB_MultiEntry,
625     WCB_MultiButton,
626     WCB_MultiMotion,
627     WCB_MultiPassive,
628
629     /* Mobile platforms LifeCycle */
630     WCB_InitContext,
631     WCB_AppStatus,
632
633     /* Presently ignored */
634     WCB_Select,
635     WCB_OverlayDisplay,
636     WCB_SpaceMotion,     /* presently implemented only on UNIX/X11 */
637     WCB_SpaceRotation,   /* presently implemented only on UNIX/X11 */
638     WCB_SpaceButton,     /* presently implemented only on UNIX/X11 */
639     WCB_Dials,
640     WCB_ButtonBox,
641     WCB_TabletMotion,
642     WCB_TabletButton,
643
644     /* Always make this the LAST one */
645     TOTAL_CALLBACKS
646 };
647
648
649 /* This structure holds the OpenGL rendering context for all the menu windows */
650 typedef struct tagSFG_MenuContext SFG_MenuContext;
651 struct tagSFG_MenuContext
652 {
653     SFG_WindowContextType MContext;       /* The menu window's WGL context   */
654 };
655
656 /* This structure describes a menu */
657 typedef struct tagSFG_Window SFG_Window;
658 typedef struct tagSFG_MenuEntry SFG_MenuEntry;
659 typedef struct tagSFG_Menu SFG_Menu;
660 struct tagSFG_Menu
661 {
662     SFG_Node            Node;
663     void               *UserData;     /* User data passed back at callback   */
664     int                 ID;           /* The global menu ID                  */
665     SFG_List            Entries;      /* The menu entries list               */
666     FGCBMenu            Callback;     /* The menu callback                   */
667     FGCBDestroy         Destroy;      /* Destruction callback                */
668     GLboolean           IsActive;     /* Is the menu selected?               */
669     void*               Font;         /* Font to be used for displaying this menu */
670     int                 Width;        /* Menu box width in pixels            */
671     int                 Height;       /* Menu box height in pixels           */
672     int                 X, Y;         /* Menu box raster position            */
673
674     SFG_MenuEntry      *ActiveEntry;  /* Currently active entry in the menu  */
675     SFG_Window         *Window;       /* Window for menu                     */
676     SFG_Window         *ParentWindow; /* Window in which the menu is invoked */
677 };
678
679 /* This is a menu entry */
680 struct tagSFG_MenuEntry
681 {
682     SFG_Node            Node;
683     int                 ID;                     /* The menu entry ID (local) */
684     int                 Ordinal;                /* The menu's ordinal number */
685     char*               Text;                   /* The text to be displayed  */
686     SFG_Menu*           SubMenu;                /* Optional sub-menu tree    */
687     GLboolean           IsActive;               /* Is the entry highlighted? */
688     int                 Width;                  /* Label's width in pixels   */
689 };
690
691 /*
692  * A window, making part of freeglut windows hierarchy.
693  * Should be kept portable.
694  *
695  * NOTE that ActiveMenu is set to menu itself if the window is a menu.
696  */
697 struct tagSFG_Window
698 {
699     SFG_Node            Node;
700     int                 ID;                     /* Window's ID number        */
701
702     SFG_Context         Window;                 /* Window and OpenGL context */
703     SFG_WindowState     State;                  /* The window state          */
704     SFG_Proc            CallBacks[ TOTAL_CALLBACKS ]; /* Array of window callbacks */
705     void               *UserData ;              /* For use by user           */
706
707     SFG_Menu*       Menu[ FREEGLUT_MAX_MENUS ]; /* Menus appended to window  */
708     SFG_Menu*       ActiveMenu;                 /* The window's active menu  */
709
710     SFG_Window*         Parent;                 /* The parent to this window */
711     SFG_List            Children;               /* The subwindows d.l. list  */
712
713     GLboolean           IsMenu;                 /* Set to 1 if we are a menu */
714 };
715
716
717 /* A linked list structure of windows */
718 typedef struct tagSFG_WindowList SFG_WindowList ;
719 struct tagSFG_WindowList
720 {
721     SFG_Node node;
722     SFG_Window *window ;
723 };
724
725 /* This holds information about all the windows, menus etc. */
726 typedef struct tagSFG_Structure SFG_Structure;
727 struct tagSFG_Structure
728 {
729     SFG_List        Windows;         /* The global windows list            */
730     SFG_List        Menus;           /* The global menus list              */
731     SFG_List        WindowsToDestroy;
732
733     SFG_Window*     CurrentWindow;   /* The currently set window          */
734     SFG_Menu*       CurrentMenu;     /* Same, but menu...                 */
735
736     SFG_MenuContext* MenuContext;    /* OpenGL rendering context for menus */
737
738     SFG_Window*      GameModeWindow; /* The game mode window               */
739
740     int              WindowID;       /* The window ID for the next window to be created */
741     int              MenuID;         /* The menu ID for the next menu to be created */
742 };
743
744 /*
745  * This structure is used for the enumeration purposes.
746  * You can easily extend its functionalities by declaring
747  * a structure containing enumerator's contents and custom
748  * data, then casting its pointer to (SFG_Enumerator *).
749  */
750 typedef struct tagSFG_Enumerator SFG_Enumerator;
751 struct tagSFG_Enumerator
752 {
753     GLboolean   found;                          /* Used to terminate search  */
754     void*       data;                           /* Custom data pointer       */
755 };
756 typedef void (* FGCBWindowEnumerator  )( SFG_Window *, SFG_Enumerator * );
757 typedef void (* FGCBMenuEnumerator  )( SFG_Menu *, SFG_Enumerator * );
758
759 /* The bitmap font structure */
760 typedef struct tagSFG_Font SFG_Font;
761 struct tagSFG_Font
762 {
763     char*           Name;         /* The source font name             */
764     int             Quantity;     /* Number of chars in font          */
765     int             Height;       /* Height of the characters         */
766     const GLubyte** Characters;   /* The characters mapping           */
767
768     float           xorig, yorig; /* Relative origin of the character */
769 };
770
771 /* The stroke font structures */
772
773 typedef struct tagSFG_StrokeVertex SFG_StrokeVertex;
774 struct tagSFG_StrokeVertex
775 {
776     GLfloat         X, Y;
777 };
778
779 typedef struct tagSFG_StrokeStrip SFG_StrokeStrip;
780 struct tagSFG_StrokeStrip
781 {
782     int             Number;
783     const SFG_StrokeVertex* Vertices;
784 };
785
786 typedef struct tagSFG_StrokeChar SFG_StrokeChar;
787 struct tagSFG_StrokeChar
788 {
789     GLfloat         Right;
790     int             Number;
791     const SFG_StrokeStrip* Strips;
792 };
793
794 typedef struct tagSFG_StrokeFont SFG_StrokeFont;
795 struct tagSFG_StrokeFont
796 {
797     char*           Name;                       /* The source font name      */
798     int             Quantity;                   /* Number of chars in font   */
799     GLfloat         Height;                     /* Height of the characters  */
800     const SFG_StrokeChar** Characters;          /* The characters mapping    */
801 };
802
803
804 /* -- JOYSTICK-SPECIFIC STRUCTURES AND TYPES ------------------------------- */
805 /*
806  * Initial defines from "js.h" starting around line 33 with the existing "fg_joystick.c"
807  * interspersed
808  */
809
810 #if TARGET_HOST_MACINTOSH
811 #    include <InputSprocket.h>
812 #endif
813
814 #if TARGET_HOST_MAC_OSX
815 #    include <mach/mach.h>
816 #    include <IOKit/IOkitLib.h>
817 #    include <IOKit/hid/IOHIDLib.h>
818 #endif
819
820 /* XXX It might be better to poll the operating system for the numbers of buttons and
821  * XXX axes and then dynamically allocate the arrays.
822  */
823 #define _JS_MAX_BUTTONS 32
824
825 #if TARGET_HOST_MACINTOSH
826 #    define _JS_MAX_AXES  9
827 typedef struct tagSFG_PlatformJoystick SFG_PlatformJoystick;
828 struct tagSFG_PlatformJoystick
829 {
830 #define  ISP_NUM_AXIS    9
831 #define  ISP_NUM_NEEDS  41
832     ISpElementReference isp_elem  [ ISP_NUM_NEEDS ];
833     ISpNeed             isp_needs [ ISP_NUM_NEEDS ];
834 };
835 #endif
836
837 #if TARGET_HOST_MAC_OSX
838 #    define _JS_MAX_AXES 16
839 typedef struct tagSFG_PlatformJoystick SFG_PlatformJoystick;
840 struct tagSFG_PlatformJoystick
841 {
842     IOHIDDeviceInterface ** hidDev;
843     IOHIDElementCookie buttonCookies[41];
844     IOHIDElementCookie axisCookies[_JS_MAX_AXES];
845 /* The next two variables are not used anywhere */
846 /*    long minReport[_JS_MAX_AXES],
847  *         maxReport[_JS_MAX_AXES];
848  */
849 };
850 #endif
851
852
853 /*
854  * Definition of "SFG_Joystick" structure -- based on JS's "jsJoystick" object class.
855  * See "js.h" lines 80-178.
856  */
857 typedef struct tagSFG_Joystick SFG_Joystick;
858 struct tagSFG_Joystick
859 {
860         SFG_PlatformJoystick pJoystick;
861
862     int          id;
863     GLboolean    error;
864     char         name [ 128 ];
865     int          num_axes;
866     int          num_buttons;
867
868     float dead_band[ _JS_MAX_AXES ];
869     float saturate [ _JS_MAX_AXES ];
870     float center   [ _JS_MAX_AXES ];
871     float max      [ _JS_MAX_AXES ];
872     float min      [ _JS_MAX_AXES ];
873 };
874
875
876
877 /* -- GLOBAL VARIABLES EXPORTS --------------------------------------------- */
878
879 /* Freeglut display related stuff (initialized once per session) */
880 extern SFG_Display fgDisplay;
881
882 /* Freeglut internal structure */
883 extern SFG_Structure fgStructure;
884
885 /* The current freeglut settings */
886 extern SFG_State fgState;
887
888
889 /* -- PRIVATE FUNCTION DECLARATIONS ---------------------------------------- */
890
891 /*
892  * A call to this function makes us sure that the Display and Structure
893  * subsystems have been properly initialized and are ready to be used
894  */
895 #define  FREEGLUT_EXIT_IF_NOT_INITIALISED( string )               \
896   if ( ! fgState.Initialised )                                    \
897   {                                                               \
898     fgError ( " ERROR:  Function <%s> called"                     \
899               " without first calling 'glutInit'.", (string) ) ;  \
900   }
901
902 #define  FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED( string )  \
903   if ( ! fgState.Initialised )                                      \
904   {                                                                 \
905     fgError ( " ERROR:  Internal <%s> function called"              \
906               " without first calling 'glutInit'.", (string) ) ;    \
907   }
908
909 #define  FREEGLUT_INTERNAL_ERROR_EXIT( cond, string, function )  \
910   if ( ! ( cond ) )                                              \
911   {                                                              \
912     fgError ( " ERROR:  Internal error <%s> in function %s",     \
913               (string), (function) ) ;                           \
914   }
915
916 /*
917  * Following definitions are somewhat similar to GLib's,
918  * but do not generate any log messages:
919  */
920 #define  freeglut_return_if_fail( expr ) \
921     if( !(expr) )                        \
922         return;
923 #define  freeglut_return_val_if_fail( expr, val ) \
924     if( !(expr) )                                 \
925         return val ;
926
927 /*
928  * A call to those macros assures us that there is a current
929  * window set, respectively:
930  */
931 #define  FREEGLUT_EXIT_IF_NO_WINDOW( string )                               \
932   if ( ! fgStructure.CurrentWindow &&                                       \
933        ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION ) )  \
934   {                                                                         \
935     fgError ( " ERROR:  Function <%s> called"                               \
936               " with no current window defined.", (string) ) ;              \
937   }
938
939 /*
940  * The deinitialize function gets called on glutMainLoop() end. It should clean up
941  * everything inside of the freeglut
942  */
943 void fgDeinitialize( void );
944
945 /*
946  * Those two functions are used to create/destroy the freeglut internal
947  * structures. This actually happens when calling glutInit() and when
948  * quitting the glutMainLoop() (which actually happens, when all windows
949  * have been closed).
950  */
951 void fgCreateStructure( void );
952 void fgDestroyStructure( void );
953
954 /*
955  * Window creation, opening, closing and destruction.
956  * Also CallBack clearing/initialization.
957  * Defined in fg_structure.c, fg_window.c.
958  */
959 SFG_Window* fgCreateWindow( SFG_Window* parent, const char* title,
960                             GLboolean positionUse, int x, int y,
961                             GLboolean sizeUse, int w, int h,
962                             GLboolean gameMode, GLboolean isMenu );
963 void        fgSetWindow ( SFG_Window *window );
964 void        fgOpenWindow( SFG_Window* window, const char* title,
965                           GLboolean positionUse, int x, int y,
966                           GLboolean sizeUse, int w, int h,
967                           GLboolean gameMode, GLboolean isSubWindow );
968 void        fgCloseWindow( SFG_Window* window );
969 void        fgAddToWindowDestroyList ( SFG_Window* window );
970 void        fgCloseWindows ();
971 void        fgDestroyWindow( SFG_Window* window );
972
973 /* Menu creation and destruction. Defined in fg_structure.c */
974 SFG_Menu*   fgCreateMenu( FGCBMenu menuCallback );
975 void        fgDestroyMenu( SFG_Menu* menu );
976
977 /* Joystick device management functions, defined in fg_joystick.c */
978 int         fgJoystickDetect( void );
979 void        fgInitialiseJoysticks( void );
980 void        fgJoystickClose( void );
981 void        fgJoystickPollWindow( SFG_Window* window );
982
983 /* InputDevice Initialisation and Closure */
984 int         fgInputDeviceDetect( void );
985 void        fgInitialiseInputDevices( void );
986 void        fgInputDeviceClose( void );
987
988 /* spaceball device functions, defined in fg_spaceball.c */
989 void        fgInitialiseSpaceball( void );
990 void        fgSpaceballClose( void );
991 void        fgSpaceballSetWindow( SFG_Window *window );
992
993 int         fgHasSpaceball( void );
994 int         fgSpaceballNumButtons( void );
995
996 /* Setting the cursor for a given window */
997 void fgSetCursor ( SFG_Window *window, int cursorID );
998
999 /*
1000  * Helper function to enumerate through all registered windows
1001  * and one to enumerate all of a window's subwindows...
1002  *
1003  * The GFunc callback for those functions will be defined as:
1004  *
1005  *      void enumCallback( gpointer window, gpointer enumerator );
1006  *
1007  * where window is the enumerated (sub)window pointer (SFG_Window *),
1008  * and userData is the a custom user-supplied pointer. Functions
1009  * are defined and exported from fg_structure.c file.
1010  */
1011 void fgEnumWindows( FGCBWindowEnumerator enumCallback, SFG_Enumerator* enumerator );
1012 void fgEnumSubWindows( SFG_Window* window, FGCBWindowEnumerator enumCallback,
1013                        SFG_Enumerator* enumerator );
1014
1015 /*
1016  * fgWindowByHandle returns a (SFG_Window *) value pointing to the
1017  * first window in the queue matching the specified window handle.
1018  * The function is defined in fg_structure.c file.
1019  */
1020 SFG_Window* fgWindowByHandle( SFG_WindowHandleType hWindow );
1021
1022 /*
1023  * This function is similar to the previous one, except it is
1024  * looking for a specified (sub)window identifier. The function
1025  * is defined in fg_structure.c file.
1026  */
1027 SFG_Window* fgWindowByID( int windowID );
1028
1029 /*
1030  * Looks up a menu given its ID. This is easier than fgWindowByXXX
1031  * as all menus are placed in a single doubly linked list...
1032  */
1033 SFG_Menu* fgMenuByID( int menuID );
1034
1035 /*
1036  * Returns active menu, if any. Assumption: only one menu active throughout application at any one time.
1037  * This is easier than fgWindowByXXX as all menus are placed in one doubly linked list...
1038  */
1039 SFG_Menu* fgGetActiveMenu( );
1040
1041 /*
1042  * The menu activation and deactivation the code. This is the meat
1043  * of the menu user interface handling code...
1044  */
1045 void fgUpdateMenuHighlight ( SFG_Menu *menu );
1046 GLboolean fgCheckActiveMenu ( SFG_Window *window, int button, GLboolean pressed,
1047                               int mouse_x, int mouse_y );
1048 void fgDeactivateMenu( SFG_Window *window );
1049
1050 /*
1051  * This function gets called just before the buffers swap, so that
1052  * freeglut can display the pull-down menus via OpenGL. The function
1053  * is defined in fg_menu.c file.
1054  */
1055 void fgDisplayMenu( void );
1056
1057 /* Elapsed time as per glutGet(GLUT_ELAPSED_TIME). */
1058 fg_time_t fgElapsedTime( void );
1059
1060 /* System time in milliseconds */
1061 fg_time_t fgSystemTime(void);
1062
1063 /* List functions */
1064 void fgListInit(SFG_List *list);
1065 void fgListAppend(SFG_List *list, SFG_Node *node);
1066 void fgListRemove(SFG_List *list, SFG_Node *node);
1067 int fgListLength(SFG_List *list);
1068 void fgListInsert(SFG_List *list, SFG_Node *next, SFG_Node *node);
1069
1070 /* Error Message functions */
1071 void fgError( const char *fmt, ... );
1072 void fgWarning( const char *fmt, ... );
1073
1074 SFG_Proc fgPlatformGetProcAddress( const char *procName );
1075
1076 /* pushing attribute/value pairs into an array */
1077 #define ATTRIB(a) attributes[where++]=(a)
1078 #define ATTRIB_VAL(a,v) {ATTRIB(a); ATTRIB(v);}
1079
1080 int fghMapBit( int mask, int from, int to );
1081 int fghIsLegacyContextRequested( void );
1082 void fghContextCreationError( void );
1083 int fghNumberOfAuxBuffersRequested( void );
1084
1085 #endif /* FREEGLUT_INTERNAL_H */
1086
1087 /*** END OF FILE ***/