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