fix multithreaded OpenGL support; actually load CGL functions from OpenGL.framework
[divverent/darkplaces.git] / vid_agl.c
1 /*
2         vid_agl.c
3
4         Mac OS X OpenGL and input module, using Carbon and AGL
5
6         Copyright (C) 2005-2006  Mathieu Olivier
7
8         This program is free software; you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation; either version 2 of the License, or
11         (at your option) any later version.
12
13         This program is distributed in the hope that it will be useful,
14         but WITHOUT ANY WARRANTY; without even the implied warranty of
15         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16         GNU General Public License for more details.
17
18         You should have received a copy of the GNU General Public License
19         along with this program; if not, write to the Free Software
20         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 */
22
23
24 #include <dlfcn.h>
25 #include <signal.h>
26 #include <AGL/agl.h>
27 #include <OpenGL/OpenGL.h>
28 #include <Carbon/Carbon.h>
29 #include "vid_agl_mackeys.h" // this is SDL/src/video/maccommon/SDL_mackeys.h
30 #include "quakedef.h"
31
32 #ifndef kCGLCEMPEngine
33 #define kCGLCEMPEngine 313
34 #endif
35
36 // Tell startup code that we have a client
37 int cl_available = true;
38
39 qboolean vid_supportrefreshrate = true;
40
41 // AGL prototypes
42 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
43 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
44 GLboolean (*qaglDestroyContext) (AGLContext ctx);
45 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
46 const GLubyte* (*qaglErrorString) (GLenum code);
47 GLenum (*qaglGetError) (void);
48 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
49 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
50 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
51 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
52 void (*qaglSwapBuffers) (AGLContext ctx);
53 CGLError (*qCGLEnable) (CGLContextObj ctx, CGLContextEnable pname);
54 CGLError (*qCGLDisable) (CGLContextObj ctx, CGLContextEnable pname);
55 CGLContextObj (*qCGLGetCurrentContext) (void);
56
57 static qboolean multithreadedgl;
58 static qboolean mouse_avail = true;
59 static qboolean vid_usingmouse = false;
60 static float mouse_x, mouse_y;
61
62 static qboolean vid_isfullscreen = false;
63 static qboolean vid_usingvsync = false;
64
65 static qboolean sound_active = true;
66
67 static int scr_width, scr_height;
68
69 static cvar_t apple_multithreadedgl = {CVAR_SAVE, "apple_multithreadedgl", "0", "makes use of a second thread for the OpenGL driver (if possible) rather than using the engine thread (note: this is done automatically on most other operating systems)"};
70
71 static AGLContext context;
72 static WindowRef window;
73
74
75 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
76 {
77         *x = *y = 0;
78         *width = scr_width;
79         *height = scr_height;
80 }
81
82 static void IN_Activate( qboolean grab )
83 {
84         if (grab)
85         {
86                 if (!vid_usingmouse && mouse_avail && window)
87                 {
88                         Rect winBounds;
89                         CGPoint winCenter;
90
91                         SelectWindow(window);
92                         CGDisplayHideCursor(CGMainDisplayID());
93
94                         // Put the mouse cursor at the center of the window
95                         GetWindowBounds (window, kWindowContentRgn, &winBounds);
96                         winCenter.x = (winBounds.left + winBounds.right) / 2;
97                         winCenter.y = (winBounds.top + winBounds.bottom) / 2;
98                         CGWarpMouseCursorPosition(winCenter);
99
100                         // Lock the mouse pointer at its current position
101                         CGAssociateMouseAndMouseCursorPosition(false);
102
103                         mouse_x = mouse_y = 0;
104                         vid_usingmouse = true;
105                 }
106         }
107         else
108         {
109                 if (vid_usingmouse)
110                 {
111                         CGAssociateMouseAndMouseCursorPosition(true);
112                         CGDisplayShowCursor(CGMainDisplayID());
113
114                         vid_usingmouse = false;
115                 }
116         }
117 }
118
119 #define GAMMA_TABLE_SIZE 256
120 void VID_Finish (qboolean allowmousegrab)
121 {
122         qboolean vid_usemouse;
123         qboolean vid_usevsync;
124
125         // handle the mouse state when windowed if that's changed
126         vid_usemouse = false;
127         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
128                 vid_usemouse = true;
129         if (!vid_activewindow)
130                 vid_usemouse = false;
131         if (vid_isfullscreen)
132                 vid_usemouse = true;
133         IN_Activate(vid_usemouse);
134
135         // handle changes of the vsync option
136         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
137         if (vid_usingvsync != vid_usevsync)
138         {
139                 GLint sync = (vid_usevsync ? 1 : 0);
140
141                 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
142                 {
143                         vid_usingvsync = vid_usevsync;
144                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
145                 }
146                 else
147                         Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
148         }
149
150         if (r_render.integer)
151         {
152                 CHECKGLERROR
153                 if (r_speeds.integer || gl_finish.integer)
154                 {
155                         qglFinish();CHECKGLERROR
156                 }
157                 qaglSwapBuffers(context);
158         }
159         VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
160
161         if (apple_multithreadedgl.integer)
162         {
163                 if (!multithreadedgl)
164                 {
165                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
166                         {
167                                 CGLContextObj ctx = qCGLGetCurrentContext();
168                                 CGLError e = qCGLEnable(ctx, kCGLCEMPEngine);
169                                 if(e == kCGLNoError)
170                                         multithreadedgl = true;
171                                 else
172                                 {
173                                         Con_Printf("WARNING: can't enable multithreaded GL, error %d\n", (int) e);
174                                         Cvar_SetValueQuick(&apple_multithreadedgl, 0);
175                                 }
176                         }
177                         else
178                         {
179                                 Con_Printf("WARNING: can't enable multithreaded GL, CGL functions not present\n", (int) e);
180                                 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
181                         }
182                 }
183         }
184         else
185         {
186                 if (multithreadedgl)
187                 {
188                         if(qCGLGetCurrentContext && qCGLEnable && qCGLDisable)
189                         {
190                                 CGLContextObj ctx = qCGLGetCurrentContext();
191                                 qCGLDisable(ctx, kCGLCEMPEngine);
192                                 multithreadedgl = false;
193                         }
194                 }
195         }
196 }
197
198 int VID_SetGamma(unsigned short *ramps, int rampsize)
199 {
200         CGGammaValue table_red [GAMMA_TABLE_SIZE];
201         CGGammaValue table_green [GAMMA_TABLE_SIZE];
202         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
203         int i;
204
205         // Convert the unsigned short table into 3 float tables
206         for (i = 0; i < rampsize; i++)
207                 table_red[i] = (float)ramps[i] / 65535.0f;
208         for (i = 0; i < rampsize; i++)
209                 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
210         for (i = 0; i < rampsize; i++)
211                 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
212
213         if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
214         {
215                 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
216                 return false;
217         }
218
219         return true;
220 }
221
222 int VID_GetGamma(unsigned short *ramps, int rampsize)
223 {
224         CGGammaValue table_red [GAMMA_TABLE_SIZE];
225         CGGammaValue table_green [GAMMA_TABLE_SIZE];
226         CGGammaValue table_blue [GAMMA_TABLE_SIZE];
227         CGTableCount actualsize = 0;
228         int i;
229
230         // Get the gamma ramps from the system
231         if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
232         {
233                 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
234                 return false;
235         }
236         if (actualsize != (unsigned int)rampsize)
237         {
238                 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
239                 return false;
240         }
241
242         // Convert the 3 float tables into 1 unsigned short table
243         for (i = 0; i < rampsize; i++)
244                 ramps[i] = table_red[i] * 65535.0f;
245         for (i = 0; i < rampsize; i++)
246                 ramps[i + rampsize] = table_green[i] * 65535.0f;
247         for (i = 0; i < rampsize; i++)
248                 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
249
250         return true;
251 }
252
253 void signal_handler(int sig)
254 {
255         printf("Received signal %d, exiting...\n", sig);
256         VID_RestoreSystemGamma();
257         Sys_Quit();
258         exit(0);
259 }
260
261 void InitSig(void)
262 {
263         signal(SIGHUP, signal_handler);
264         signal(SIGINT, signal_handler);
265         signal(SIGQUIT, signal_handler);
266         signal(SIGILL, signal_handler);
267         signal(SIGTRAP, signal_handler);
268         signal(SIGIOT, signal_handler);
269         signal(SIGBUS, signal_handler);
270         signal(SIGFPE, signal_handler);
271         signal(SIGSEGV, signal_handler);
272         signal(SIGTERM, signal_handler);
273 }
274
275 void VID_Init(void)
276 {
277         InitSig(); // trap evil signals
278         Cvar_RegisterVariable(&apple_multithreadedgl);
279 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
280         if (COM_CheckParm ("-nomouse"))
281                 mouse_avail = false;
282 }
283
284 static void *prjobj = NULL;
285 static void *cglobj = NULL;
286
287 static void GL_CloseLibrary(void)
288 {
289         if (cglobj)
290                 dlclose(cglobj);
291         cglobj = NULL;
292         if (prjobj)
293                 dlclose(prjobj);
294         prjobj = NULL;
295         gl_driver[0] = 0;
296         gl_extensions = "";
297         gl_platform = "";
298         gl_platformextensions = "";
299 }
300
301 static int GL_OpenLibrary(void)
302 {
303         const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
304         const char *name2 = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
305
306         Con_Printf("Loading OpenGL driver %s\n", name);
307         GL_CloseLibrary();
308         if (!(prjobj = dlopen(name, RTLD_LAZY)))
309         {
310                 Con_Printf("Unable to open symbol list for %s\n", name);
311                 return false;
312         }
313         strlcpy(gl_driver, name, sizeof(gl_driver));
314
315         Con_Printf("Loading OpenGL driver %s\n", name2);
316         if (!(cglobj = dlopen(name2, RTLD_LAZY)))
317                 Con_Printf("Unable to open symbol list for %s; multithreaded GL disabled\n", name);
318
319         return true;
320 }
321
322 void *GL_GetProcAddress(const char *name)
323 {
324         return dlsym(prjobj, name);
325 }
326
327 static void *CGL_GetProcAddress(const char *name)
328 {
329         if(!cglobj)
330                 return NULL;
331         return dlsym(cglobj, name);
332 }
333
334 void VID_Shutdown(void)
335 {
336         if (context == NULL && window == NULL)
337                 return;
338
339         IN_Activate(false);
340         VID_RestoreSystemGamma();
341
342         if (context != NULL)
343         {
344                 qaglDestroyContext(context);
345                 context = NULL;
346         }
347
348         if (vid_isfullscreen)
349                 CGReleaseAllDisplays();
350
351         if (window != NULL)
352         {
353                 DisposeWindow(window);
354                 window = NULL;
355         }
356
357         vid_hidden = true;
358         vid_isfullscreen = false;
359
360         GL_CloseLibrary();
361         Key_ClearStates ();
362 }
363
364 // Since the event handler can be called at any time, we store the events for later processing
365 static qboolean AsyncEvent_Quitting = false;
366 static qboolean AsyncEvent_Collapsed = false;
367 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
368 {
369         OSStatus err = noErr;
370
371         switch (GetEventKind (event))
372         {
373                 case kEventWindowClosed:
374                         AsyncEvent_Quitting = true;
375                         break;
376
377                 // Docked (start)
378                 case kEventWindowCollapsing:
379                         AsyncEvent_Collapsed = true;
380                         break;
381
382                 // Undocked / restored (end)
383                 case kEventWindowExpanded:
384                         AsyncEvent_Collapsed = false;
385                         break;
386
387                 default:
388                         err = eventNotHandledErr;
389                         break;
390         }
391
392         return err;
393 }
394
395 static void VID_AppFocusChanged(qboolean windowIsActive)
396 {
397         if (vid_activewindow != windowIsActive)
398         {
399                 vid_activewindow = windowIsActive;
400                 if (!vid_activewindow)
401                         VID_RestoreSystemGamma();
402         }
403
404         if (sound_active != windowIsActive)
405         {
406                 sound_active = windowIsActive;
407                 if (sound_active)
408                         S_UnblockSound ();
409                 else
410                         S_BlockSound ();
411         }
412 }
413
414 static void VID_ProcessPendingAsyncEvents (void)
415 {
416         // Collapsed / expanded
417         if (AsyncEvent_Collapsed != vid_hidden)
418         {
419                 vid_hidden = !vid_hidden;
420                 VID_AppFocusChanged(!vid_hidden);
421         }
422
423         // Closed
424         if (AsyncEvent_Quitting)
425                 Sys_Quit();
426 }
427
428 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer)
429 {
430         *attrib++ = AGL_RGBA;
431         *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
432         *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
433         *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
434         *attrib++ = AGL_DOUBLEBUFFER;
435         *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
436
437         // if stencil is enabled, ask for alpha too
438         if (stencil)
439         {
440                 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
441                 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
442         }
443         if (fullscreen)
444                 *attrib++ = AGL_FULLSCREEN;
445         if (stereobuffer)
446                 *attrib++ = AGL_STEREO;
447         *attrib++ = AGL_NONE;
448 }
449
450 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
451 {
452     const EventTypeSpec winEvents[] =
453         {
454                 { kEventClassWindow, kEventWindowClosed },
455                 { kEventClassWindow, kEventWindowCollapsing },
456                 { kEventClassWindow, kEventWindowExpanded },
457         };
458         OSStatus carbonError;
459         Rect windowBounds;
460         CFStringRef windowTitle;
461         AGLPixelFormat pixelFormat;
462         GLint attributes [32];
463         GLenum error;
464
465         if (!GL_OpenLibrary())
466         {
467                 Con_Printf("Unable to load GL driver\n");
468                 return false;
469         }
470
471         if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
472          || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
473          || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
474          || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
475          || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
476          || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
477          || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
478          || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
479          || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
480          || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
481          || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
482         )
483         {
484                 Con_Printf("AGL functions not found\n");
485                 ReleaseWindow(window);
486                 return false;
487         }
488
489         qCGLEnable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLEnable");
490         qCGLDisable = (CGLError (*) (CGLContextObj ctx, CGLContextEnable pname)) CGL_GetProcAddress("CGLDisable");
491         qCGLGetCurrentContext = (CGLContextObj (*) (void)) CGL_GetProcAddress("CGLGetCurrentContext");
492         if(!qCGLEnable || !qCGLDisable || !qCGLGetCurrentContext)
493                 Con_Printf("CGL functions not found; disabling multithreaded OpenGL\n");
494
495         // Ignore the events from the previous window
496         AsyncEvent_Quitting = false;
497         AsyncEvent_Collapsed = false;
498
499         // Create the window, a bit towards the center of the screen
500         windowBounds.left = 100;
501         windowBounds.top = 100;
502         windowBounds.right = width + 100;
503         windowBounds.bottom = height + 100;
504         carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
505         if (carbonError != noErr || window == NULL)
506         {
507                 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
508                 return false;
509         }
510
511         // Set the window title
512         windowTitle = CFSTR("DarkPlaces AGL");
513         SetWindowTitleWithCFString(window, windowTitle);
514
515         // Install the callback function for the window events we can't get
516         // through ReceiveNextEvent (i.e. close, collapse, and expand)
517         InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
518                                                            GetEventTypeCount(winEvents), winEvents, window, NULL);
519
520         // Create the desired attribute list
521         VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer);
522
523         if (!fullscreen)
524         {
525                 // Output to Window
526                 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
527                 error = qaglGetError();
528                 if (error != AGL_NO_ERROR)
529                 {
530                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
531                                         (char *)qaglErrorString(error));
532                         ReleaseWindow(window);
533                         return false;
534                 }
535         }
536         else  // Output is fullScreen
537         {
538                 CGDirectDisplayID mainDisplay;
539                 CFDictionaryRef refDisplayMode;
540                 GDHandle gdhDisplay;
541
542                 // Get the mainDisplay and set resolution to current
543                 mainDisplay = CGMainDisplayID();
544                 CGDisplayCapture(mainDisplay);
545
546                 // TOCHECK: not sure whether or not it's necessary to change the resolution
547                 // "by hand", or if aglSetFullscreen does the job anyway
548                 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
549                 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
550                 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
551
552                 // Set pixel format with built attribs
553                 // Note: specifying a device is *required* for AGL_FullScreen
554                 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
555                 error = qaglGetError();
556                 if (error != AGL_NO_ERROR)
557                 {
558                         Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
559                                                 (char *)qaglErrorString(error));
560                         ReleaseWindow(window);
561                         return false;
562                 }
563         }
564
565         // Create a context using the pform
566         context = qaglCreateContext(pixelFormat, NULL);
567         error = qaglGetError();
568         if (error != AGL_NO_ERROR)
569         {
570                 Con_Printf("qaglCreateContext FAILED: %s\n",
571                                         (char *)qaglErrorString(error));
572         }
573
574         // Make the context the current one ('enable' it)
575         qaglSetCurrentContext(context);
576         error = qaglGetError();
577         if (error != AGL_NO_ERROR)
578         {
579                 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
580                                         (char *)qaglErrorString(error));
581                 ReleaseWindow(window);
582                 return false;
583         }
584
585         // Discard pform
586         qaglDestroyPixelFormat(pixelFormat);
587
588         // Attempt fullscreen if requested
589         if (fullscreen)
590         {
591                 qaglSetFullScreen (context, width, height, refreshrate, 0);
592                 error = qaglGetError();
593                 if (error != AGL_NO_ERROR)
594                 {
595                         Con_Printf("qaglSetFullScreen FAILED: %s\n",
596                                                 (char *)qaglErrorString(error));
597                         return false;
598                 }
599         }
600         else
601         {
602                 // Set Window as Drawable
603                 qaglSetDrawable(context, GetWindowPort(window));
604                 error = qaglGetError();
605                 if (error != AGL_NO_ERROR)
606                 {
607                         Con_Printf("qaglSetDrawable FAILED: %s\n",
608                                                 (char *)qaglErrorString(error));
609                         ReleaseWindow(window);
610                         return false;
611                 }
612         }
613
614         scr_width = width;
615         scr_height = height;
616
617         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
618                 Sys_Error("glGetString not found in %s", gl_driver);
619
620         gl_renderer = (const char *)qglGetString(GL_RENDERER);
621         gl_vendor = (const char *)qglGetString(GL_VENDOR);
622         gl_version = (const char *)qglGetString(GL_VERSION);
623         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
624         gl_platform = "AGL";
625         gl_videosyncavailable = true;
626
627         multithreadedgl = false;
628         vid_isfullscreen = fullscreen;
629         vid_usingmouse = false;
630         vid_hidden = false;
631         vid_activewindow = true;
632         sound_active = true;
633         GL_Init();
634
635         SelectWindow(window);
636         ShowWindow(window);
637
638         return true;
639 }
640
641 static void Handle_KeyMod(UInt32 keymod)
642 {
643         const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
644         {
645                 { cmdKey,                                               K_AUX1 },
646                 { shiftKey,                                             K_SHIFT },
647                 { alphaLock,                                    K_CAPSLOCK },
648                 { optionKey,                                    K_ALT },
649                 { controlKey,                                   K_CTRL },
650                 { kEventKeyModifierNumLockMask, K_NUMLOCK },
651                 { kEventKeyModifierFnMask,              K_AUX2 }
652         };
653         static UInt32 prev_keymod = 0;
654         unsigned int i;
655         UInt32 modChanges;
656
657         modChanges = prev_keymod ^ keymod;
658         if (modChanges == 0)
659                 return;
660
661         for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
662         {
663                 UInt32 keybit = keymod_events[i].keybit;
664
665                 if ((modChanges & keybit) != 0)
666                         Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
667         }
668
669         prev_keymod = keymod;
670 }
671
672 static void Handle_Key(unsigned char charcode, UInt32 mackeycode, qboolean keypressed)
673 {
674         unsigned int keycode = 0;
675         char ascii = '\0';
676
677         switch (mackeycode)
678         {
679                 case MK_ESCAPE:
680                         keycode = K_ESCAPE;
681                         break;
682                 case MK_F1:
683                         keycode = K_F1;
684                         break;
685                 case MK_F2:
686                         keycode = K_F2;
687                         break;
688                 case MK_F3:
689                         keycode = K_F3;
690                         break;
691                 case MK_F4:
692                         keycode = K_F4;
693                         break;
694                 case MK_F5:
695                         keycode = K_F5;
696                         break;
697                 case MK_F6:
698                         keycode = K_F6;
699                         break;
700                 case MK_F7:
701                         keycode = K_F7;
702                         break;
703                 case MK_F8:
704                         keycode = K_F8;
705                         break;
706                 case MK_F9:
707                         keycode = K_F9;
708                         break;
709                 case MK_F10:
710                         keycode = K_F10;
711                         break;
712                 case MK_F11:
713                         keycode = K_F11;
714                         break;
715                 case MK_F12:
716                         keycode = K_F12;
717                         break;
718                 case MK_SCROLLOCK:
719                         keycode = K_SCROLLOCK;
720                         break;
721                 case MK_PAUSE:
722                         keycode = K_PAUSE;
723                         break;
724                 case MK_BACKSPACE:
725                         keycode = K_BACKSPACE;
726                         break;
727                 case MK_INSERT:
728                         keycode = K_INS;
729                         break;
730                 case MK_HOME:
731                         keycode = K_HOME;
732                         break;
733                 case MK_PAGEUP:
734                         keycode = K_PGUP;
735                         break;
736                 case MK_NUMLOCK:
737                         keycode = K_NUMLOCK;
738                         break;
739                 case MK_KP_EQUALS:
740                         keycode = K_KP_EQUALS;
741                         break;
742                 case MK_KP_DIVIDE:
743                         keycode = K_KP_DIVIDE;
744                         break;
745                 case MK_KP_MULTIPLY:
746                         keycode = K_KP_MULTIPLY;
747                         break;
748                 case MK_TAB:
749                         keycode = K_TAB;
750                         break;
751                 case MK_DELETE:
752                         keycode = K_DEL;
753                         break;
754                 case MK_END:
755                         keycode = K_END;
756                         break;
757                 case MK_PAGEDOWN:
758                         keycode = K_PGDN;
759                         break;
760                 case MK_KP7:
761                         keycode = K_KP_7;
762                         break;
763                 case MK_KP8:
764                         keycode = K_KP_8;
765                         break;
766                 case MK_KP9:
767                         keycode = K_KP_9;
768                         break;
769                 case MK_KP_MINUS:
770                         keycode = K_KP_MINUS;
771                         break;
772                 case MK_CAPSLOCK:
773                         keycode = K_CAPSLOCK;
774                         break;
775                 case MK_RETURN:
776                         keycode = K_ENTER;
777                         break;
778                 case MK_KP4:
779                         keycode = K_KP_4;
780                         break;
781                 case MK_KP5:
782                         keycode = K_KP_5;
783                         break;
784                 case MK_KP6:
785                         keycode = K_KP_6;
786                         break;
787                 case MK_KP_PLUS:
788                         keycode = K_KP_PLUS;
789                         break;
790                 case MK_KP1:
791                         keycode = K_KP_1;
792                         break;
793                 case MK_KP2:
794                         keycode = K_KP_2;
795                         break;
796                 case MK_KP3:
797                         keycode = K_KP_3;
798                         break;
799                 case MK_KP_ENTER:
800                 case MK_IBOOK_ENTER:
801                         keycode = K_KP_ENTER;
802                         break;
803                 case MK_KP0:
804                         keycode = K_KP_0;
805                         break;
806                 case MK_KP_PERIOD:
807                         keycode = K_KP_PERIOD;
808                         break;
809                 default:
810                         switch(charcode)
811                         {
812                                 case kUpArrowCharCode:
813                                         keycode = K_UPARROW;
814                                         break;
815                                 case kLeftArrowCharCode:
816                                         keycode = K_LEFTARROW;
817                                         break;
818                                 case kDownArrowCharCode:
819                                         keycode = K_DOWNARROW;
820                                         break;
821                                 case kRightArrowCharCode:
822                                         keycode = K_RIGHTARROW;
823                                         break;
824                                 case 0:
825                                 case 191:
826                                         // characters 0 and 191 are sent by the mouse buttons (?!)
827                                         break;
828                                 default:
829                                         if ('A' <= charcode && charcode <= 'Z')
830                                         {
831                                                 keycode = charcode + ('a' - 'A');  // lowercase it
832                                                 ascii = charcode;
833                                         }
834                                         else if (charcode >= 32)
835                                         {
836                                                 keycode = charcode;
837                                                 ascii = charcode;
838                                         }
839                                         else
840                                                 Con_Printf(">> UNKNOWN char/keycode: %d/%u <<\n", charcode, (unsigned) mackeycode);
841                         }
842         }
843
844         if (keycode != 0)
845                 Key_Event(keycode, ascii, keypressed);
846 }
847
848 void Sys_SendKeyEvents(void)
849 {
850         EventRef theEvent;
851         EventTargetRef theTarget;
852
853         // Start by processing the asynchronous events we received since the previous frame
854         VID_ProcessPendingAsyncEvents();
855
856         theTarget = GetEventDispatcherTarget();
857         while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
858         {
859                 UInt32 eventClass = GetEventClass(theEvent);
860                 UInt32 eventKind = GetEventKind(theEvent);
861
862                 switch (eventClass)
863                 {
864                         case kEventClassMouse:
865                         {
866                                 EventMouseButton theButton;
867                                 int key;
868
869                                 switch (eventKind)
870                                 {
871                                         case kEventMouseDown:
872                                         case kEventMouseUp:
873                                                 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
874                                                 switch (theButton)
875                                                 {
876                                                         default:
877                                                         case kEventMouseButtonPrimary:
878                                                                 key = K_MOUSE1;
879                                                                 break;
880                                                         case kEventMouseButtonSecondary:
881                                                                 key = K_MOUSE2;
882                                                                 break;
883                                                         case kEventMouseButtonTertiary:
884                                                                 key = K_MOUSE3;
885                                                                 break;
886                                                 }
887                                                 Key_Event(key, '\0', eventKind == kEventMouseDown);
888                                                 break;
889
890                                         // Note: These two events are mutual exclusives
891                                         // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
892                                         case kEventMouseMoved:
893                                         case kEventMouseDragged:
894                                         {
895                                                 HIPoint deltaPos;
896
897                                                 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
898
899                                                 mouse_x += deltaPos.x;
900                                                 mouse_y += deltaPos.y;
901                                                 break;
902                                         }
903
904                                         case kEventMouseWheelMoved:
905                                         {
906                                                 SInt32 delta;
907                                                 unsigned int wheelEvent;
908
909                                                 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
910
911                                                 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
912                                                 Key_Event(wheelEvent, 0, true);
913                                                 Key_Event(wheelEvent, 0, false);
914                                                 break;
915                                         }
916
917                                         default:
918                                                 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
919                                                 break;
920                                 }
921                         }
922
923                         case kEventClassKeyboard:
924                         {
925                                 char charcode;
926                                 UInt32 keycode;
927
928                                 switch (eventKind)
929                                 {
930                                         case kEventRawKeyDown:
931                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
932                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
933                                                 Handle_Key(charcode, keycode, true);
934                                                 break;
935
936                                         case kEventRawKeyRepeat:
937                                                 break;
938
939                                         case kEventRawKeyUp:
940                                                 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
941                                                 GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
942                                                 Handle_Key(charcode, keycode, false);
943                                                 break;
944
945                                         case kEventRawKeyModifiersChanged:
946                                         {
947                                                 UInt32 keymod = 0;
948                                                 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
949                                                 Handle_KeyMod(keymod);
950                                                 break;
951                                         }
952
953                                         case kEventHotKeyPressed:
954                                                 break;
955
956                                         case kEventHotKeyReleased:
957                                                 break;
958
959                                         case kEventMouseWheelMoved:
960                                                 break;
961
962                                         default:
963                                                 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
964                                                 break;
965                                 }
966                                 break;
967                         }
968
969                         case kEventClassTextInput:
970                                 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
971                                 break;
972
973                         case kEventClassApplication:
974                                 switch (eventKind)
975                                 {
976                                         case kEventAppActivated :
977                                                 VID_AppFocusChanged(true);
978                                                 break;
979                                         case kEventAppDeactivated:
980                                                 VID_AppFocusChanged(false);
981                                                 break;
982                                         case kEventAppQuit:
983                                                 Sys_Quit();
984                                                 break;
985                                         case kEventAppActiveWindowChanged:
986                                                 break;
987                                         default:
988                                                 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
989                                                 break;
990                                 }
991                                 break;
992
993                         case kEventClassAppleEvent:
994                                 switch (eventKind)
995                                 {
996                                         case kEventAppleEvent :
997                                                 break;
998                                         default:
999                                                 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1000                                                 break;
1001                                 }
1002                                 break;
1003
1004                         case kEventClassWindow:
1005                                 switch (eventKind)
1006                                 {
1007                                         case kEventWindowUpdate :
1008                                                 break;
1009                                         default:
1010                                                 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
1011                                                 break;
1012                                 }
1013                                 break;
1014
1015                         case kEventClassControl:
1016                                 break;
1017
1018                         default:
1019                                 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
1020                                                         eventClass >> 24, (eventClass >> 16) & 0xFF,
1021                                                         (eventClass >> 8) & 0xFF, eventClass & 0xFF,
1022                                                         eventKind);*/
1023                                 break;
1024                 }
1025
1026                 SendEventToEventTarget (theEvent, theTarget);
1027                 ReleaseEvent(theEvent);
1028         }
1029 }
1030
1031 void IN_Move (void)
1032 {
1033         if (mouse_avail)
1034         {
1035                 in_mouse_x = mouse_x;
1036                 in_mouse_y = mouse_y;
1037         }
1038         mouse_x = 0;
1039         mouse_y = 0;
1040 }