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