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