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