4 Mac OS X OpenGL and input module, using Carbon and AGL
6 Copyright (C) 2005-2006 Mathieu Olivier
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.
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.
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
27 #include <Carbon/Carbon.h>
31 // Tell startup code that we have a client
32 int cl_available = true;
34 qboolean vid_supportrefreshrate = true;
37 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
38 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
39 GLboolean (*qaglDestroyContext) (AGLContext ctx);
40 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
41 const GLubyte* (*qaglErrorString) (GLenum code);
42 GLenum (*qaglGetError) (void);
43 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
44 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
45 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
46 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
47 void (*qaglSwapBuffers) (AGLContext ctx);
49 static qboolean multithreadedgl;
50 static qboolean mouse_avail = true;
51 static qboolean vid_usingmouse = false;
52 static float mouse_x, mouse_y;
54 static qboolean vid_isfullscreen = false;
55 static qboolean vid_usingvsync = false;
57 static qboolean sound_active = true;
59 static int scr_width, scr_height;
61 static cvar_t apple_multithreadedgl = {CVAR_SAVE, "apple_multithreadedgl", "0", "makes use of a second thread for the OpenGL driver (if possible) rather than using the engine thread (note: this is done automatically on most other operating systems)"};
63 static AGLContext context;
64 static WindowRef window;
67 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
74 static void IN_Activate( qboolean grab )
78 if (!vid_usingmouse && mouse_avail && window)
84 CGDisplayHideCursor(CGMainDisplayID());
86 // Put the mouse cursor at the center of the window
87 GetWindowBounds (window, kWindowContentRgn, &winBounds);
88 winCenter.x = (winBounds.left + winBounds.right) / 2;
89 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
90 CGWarpMouseCursorPosition(winCenter);
92 // Lock the mouse pointer at its current position
93 CGAssociateMouseAndMouseCursorPosition(false);
95 mouse_x = mouse_y = 0;
96 vid_usingmouse = true;
103 CGAssociateMouseAndMouseCursorPosition(true);
104 CGDisplayShowCursor(CGMainDisplayID());
106 vid_usingmouse = false;
111 #define GAMMA_TABLE_SIZE 256
112 void VID_Finish (qboolean allowmousegrab)
114 qboolean vid_usemouse;
115 qboolean vid_usevsync;
117 // handle the mouse state when windowed if that's changed
118 vid_usemouse = false;
119 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
121 if (!vid_activewindow)
122 vid_usemouse = false;
123 if (vid_isfullscreen)
125 IN_Activate(vid_usemouse);
127 // handle changes of the vsync option
128 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
129 if (vid_usingvsync != vid_usevsync)
131 GLint sync = (vid_usevsync ? 1 : 0);
133 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
135 vid_usingvsync = vid_usevsync;
136 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
139 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
142 if (r_render.integer)
145 if (r_speeds.integer || gl_finish.integer)
147 qglFinish();CHECKGLERROR
149 qaglSwapBuffers(context);
151 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
153 #ifdef kCGLCEMPEngine
154 if (apple_multithreadedgl.integer)
156 if (!multithreadedgl)
159 CGLContextObj ctx = CGLGetCurrentContext();
160 err = CGLEnable(ctx, kCGLEMPEngine);
161 if (err == kCGLNoError)
162 multithreadedgl = true;
164 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
171 multithreadedgl = false;
172 CGLDisable(ctx, kCGLEMPEngine);
176 if (apple_multithreadedgl.integer)
177 Cvar_SetValueQuick(&apple_multithreadedgl, 0);
181 int VID_SetGamma(unsigned short *ramps, int rampsize)
183 CGGammaValue table_red [GAMMA_TABLE_SIZE];
184 CGGammaValue table_green [GAMMA_TABLE_SIZE];
185 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
188 // Convert the unsigned short table into 3 float tables
189 for (i = 0; i < rampsize; i++)
190 table_red[i] = (float)ramps[i] / 65535.0f;
191 for (i = 0; i < rampsize; i++)
192 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
193 for (i = 0; i < rampsize; i++)
194 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
196 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
198 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
205 int VID_GetGamma(unsigned short *ramps, int rampsize)
207 CGGammaValue table_red [GAMMA_TABLE_SIZE];
208 CGGammaValue table_green [GAMMA_TABLE_SIZE];
209 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
210 CGTableCount actualsize = 0;
213 // Get the gamma ramps from the system
214 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
216 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
219 if (actualsize != (unsigned int)rampsize)
221 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
225 // Convert the 3 float tables into 1 unsigned short table
226 for (i = 0; i < rampsize; i++)
227 ramps[i] = table_red[i] * 65535.0f;
228 for (i = 0; i < rampsize; i++)
229 ramps[i + rampsize] = table_green[i] * 65535.0f;
230 for (i = 0; i < rampsize; i++)
231 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
236 void signal_handler(int sig)
238 printf("Received signal %d, exiting...\n", sig);
239 VID_RestoreSystemGamma();
246 signal(SIGHUP, signal_handler);
247 signal(SIGINT, signal_handler);
248 signal(SIGQUIT, signal_handler);
249 signal(SIGILL, signal_handler);
250 signal(SIGTRAP, signal_handler);
251 signal(SIGIOT, signal_handler);
252 signal(SIGBUS, signal_handler);
253 signal(SIGFPE, signal_handler);
254 signal(SIGSEGV, signal_handler);
255 signal(SIGTERM, signal_handler);
260 InitSig(); // trap evil signals
261 Cvar_RegisterVariable(&apple_multithreadedgl);
262 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
263 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
267 static void *prjobj = NULL;
269 static void GL_CloseLibrary(void)
277 gl_platformextensions = "";
280 static int GL_OpenLibrary(void)
282 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
284 Con_Printf("Loading OpenGL driver %s\n", name);
286 if (!(prjobj = dlopen(name, RTLD_LAZY)))
288 Con_Printf("Unable to open symbol list for %s\n", name);
291 strlcpy(gl_driver, name, sizeof(gl_driver));
295 void *GL_GetProcAddress(const char *name)
297 return dlsym(prjobj, name);
300 void VID_Shutdown(void)
302 if (context == NULL && window == NULL)
306 VID_RestoreSystemGamma();
310 qaglDestroyContext(context);
314 if (vid_isfullscreen)
315 CGReleaseAllDisplays();
319 DisposeWindow(window);
324 vid_isfullscreen = false;
330 // Since the event handler can be called at any time, we store the events for later processing
331 static qboolean AsyncEvent_Quitting = false;
332 static qboolean AsyncEvent_Collapsed = false;
333 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
335 OSStatus err = noErr;
337 switch (GetEventKind (event))
339 case kEventWindowClosed:
340 AsyncEvent_Quitting = true;
344 case kEventWindowCollapsing:
345 AsyncEvent_Collapsed = true;
348 // Undocked / restored (end)
349 case kEventWindowExpanded:
350 AsyncEvent_Collapsed = false;
354 err = eventNotHandledErr;
361 static void VID_AppFocusChanged(qboolean windowIsActive)
363 if (vid_activewindow != windowIsActive)
365 vid_activewindow = windowIsActive;
366 if (!vid_activewindow)
367 VID_RestoreSystemGamma();
370 if (sound_active != windowIsActive)
372 sound_active = windowIsActive;
380 static void VID_ProcessPendingAsyncEvents (void)
382 // Collapsed / expanded
383 if (AsyncEvent_Collapsed != vid_hidden)
385 vid_hidden = !vid_hidden;
386 VID_AppFocusChanged(!vid_hidden);
390 if (AsyncEvent_Quitting)
394 static void VID_BuildAGLAttrib(GLint *attrib, qboolean stencil, qboolean fullscreen, qboolean stereobuffer)
396 *attrib++ = AGL_RGBA;
397 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
398 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
399 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
400 *attrib++ = AGL_DOUBLEBUFFER;
401 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
403 // if stencil is enabled, ask for alpha too
406 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
407 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
410 *attrib++ = AGL_FULLSCREEN;
412 *attrib++ = AGL_STEREO;
413 *attrib++ = AGL_NONE;
416 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
418 const EventTypeSpec winEvents[] =
420 { kEventClassWindow, kEventWindowClosed },
421 { kEventClassWindow, kEventWindowCollapsing },
422 { kEventClassWindow, kEventWindowExpanded },
424 OSStatus carbonError;
426 CFStringRef windowTitle;
427 AGLPixelFormat pixelFormat;
428 GLint attributes [32];
431 if (!GL_OpenLibrary())
433 Con_Printf("Unable to load GL driver\n");
437 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
438 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
439 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
440 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
441 || (qaglErrorString = (const GLubyte* (*) (GLenum code))GL_GetProcAddress("aglErrorString")) == NULL
442 || (qaglGetError = (GLenum (*) (void))GL_GetProcAddress("aglGetError")) == NULL
443 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
444 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
445 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
446 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
447 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
450 Con_Printf("AGL functions not found\n");
451 ReleaseWindow(window);
455 // Ignore the events from the previous window
456 AsyncEvent_Quitting = false;
457 AsyncEvent_Collapsed = false;
459 // Create the window, a bit towards the center of the screen
460 windowBounds.left = 100;
461 windowBounds.top = 100;
462 windowBounds.right = width + 100;
463 windowBounds.bottom = height + 100;
464 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
465 if (carbonError != noErr || window == NULL)
467 Con_Printf("Unable to create window (error %u)\n", (unsigned)carbonError);
471 // Set the window title
472 windowTitle = CFSTR("DarkPlaces AGL");
473 SetWindowTitleWithCFString(window, windowTitle);
475 // Install the callback function for the window events we can't get
476 // through ReceiveNextEvent (i.e. close, collapse, and expand)
477 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
478 GetEventTypeCount(winEvents), winEvents, window, NULL);
480 // Create the desired attribute list
481 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen, stereobuffer);
486 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
487 error = qaglGetError();
488 if (error != AGL_NO_ERROR)
490 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
491 (char *)qaglErrorString(error));
492 ReleaseWindow(window);
496 else // Output is fullScreen
498 CGDirectDisplayID mainDisplay;
499 CFDictionaryRef refDisplayMode;
502 // Get the mainDisplay and set resolution to current
503 mainDisplay = CGMainDisplayID();
504 CGDisplayCapture(mainDisplay);
506 // TOCHECK: not sure whether or not it's necessary to change the resolution
507 // "by hand", or if aglSetFullscreen does the job anyway
508 refDisplayMode = CGDisplayBestModeForParametersAndRefreshRate(mainDisplay, bpp, width, height, refreshrate, NULL);
509 CGDisplaySwitchToMode(mainDisplay, refDisplayMode);
510 DMGetGDeviceByDisplayID((DisplayIDType)mainDisplay, &gdhDisplay, false);
512 // Set pixel format with built attribs
513 // Note: specifying a device is *required* for AGL_FullScreen
514 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
515 error = qaglGetError();
516 if (error != AGL_NO_ERROR)
518 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
519 (char *)qaglErrorString(error));
520 ReleaseWindow(window);
525 // Create a context using the pform
526 context = qaglCreateContext(pixelFormat, NULL);
527 error = qaglGetError();
528 if (error != AGL_NO_ERROR)
530 Con_Printf("qaglCreateContext FAILED: %s\n",
531 (char *)qaglErrorString(error));
534 // Make the context the current one ('enable' it)
535 qaglSetCurrentContext(context);
536 error = qaglGetError();
537 if (error != AGL_NO_ERROR)
539 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
540 (char *)qaglErrorString(error));
541 ReleaseWindow(window);
546 qaglDestroyPixelFormat(pixelFormat);
548 // Attempt fullscreen if requested
551 qaglSetFullScreen (context, width, height, refreshrate, 0);
552 error = qaglGetError();
553 if (error != AGL_NO_ERROR)
555 Con_Printf("qaglSetFullScreen FAILED: %s\n",
556 (char *)qaglErrorString(error));
562 // Set Window as Drawable
563 qaglSetDrawable(context, GetWindowPort(window));
564 error = qaglGetError();
565 if (error != AGL_NO_ERROR)
567 Con_Printf("qaglSetDrawable FAILED: %s\n",
568 (char *)qaglErrorString(error));
569 ReleaseWindow(window);
577 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
578 Sys_Error("glGetString not found in %s", gl_driver);
580 gl_renderer = (const char *)qglGetString(GL_RENDERER);
581 gl_vendor = (const char *)qglGetString(GL_VENDOR);
582 gl_version = (const char *)qglGetString(GL_VERSION);
583 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
585 gl_videosyncavailable = true;
587 multithreadedgl = false;
588 vid_isfullscreen = fullscreen;
589 vid_usingmouse = false;
591 vid_activewindow = true;
595 SelectWindow(window);
601 static void Handle_KeyMod(UInt32 keymod)
603 const struct keymod_to_event_s { UInt32 keybit; keynum_t event; } keymod_events [] =
606 { shiftKey, K_SHIFT },
607 { alphaLock, K_CAPSLOCK },
608 { optionKey, K_ALT },
609 { controlKey, K_CTRL },
610 { kEventKeyModifierNumLockMask, K_NUMLOCK },
611 { kEventKeyModifierFnMask, K_AUX2 }
613 static UInt32 prev_keymod = 0;
617 modChanges = prev_keymod ^ keymod;
621 for (i = 0; i < sizeof(keymod_events) / sizeof(keymod_events[0]); i++)
623 UInt32 keybit = keymod_events[i].keybit;
625 if ((modChanges & keybit) != 0)
626 Key_Event(keymod_events[i].event, '\0', (keymod & keybit) != 0);
629 prev_keymod = keymod;
632 static void Handle_Key(unsigned char charcode, qboolean keypressed)
634 unsigned int keycode = 0;
643 keycode = K_KP_ENTER;
648 case kBackspaceCharCode:
649 keycode = K_BACKSPACE;
654 case kPageUpCharCode:
657 case kPageDownCharCode:
660 case kReturnCharCode:
663 case kEscapeCharCode:
666 case kLeftArrowCharCode:
667 keycode = K_LEFTARROW;
669 case kRightArrowCharCode:
670 keycode = K_RIGHTARROW;
672 case kUpArrowCharCode:
675 case kDownArrowCharCode :
676 keycode = K_DOWNARROW;
678 case kDeleteCharCode:
683 // characters 0 and 191 are sent by the mouse buttons (?!)
686 if ('A' <= charcode && charcode <= 'Z')
688 keycode = charcode + ('a' - 'A'); // lowercase it
691 else if (charcode >= 32)
697 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
701 Key_Event(keycode, ascii, keypressed);
704 void Sys_SendKeyEvents(void)
707 EventTargetRef theTarget;
709 // Start by processing the asynchronous events we received since the previous frame
710 VID_ProcessPendingAsyncEvents();
712 theTarget = GetEventDispatcherTarget();
713 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
715 UInt32 eventClass = GetEventClass(theEvent);
716 UInt32 eventKind = GetEventKind(theEvent);
720 case kEventClassMouse:
722 EventMouseButton theButton;
727 case kEventMouseDown:
729 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
733 case kEventMouseButtonPrimary:
736 case kEventMouseButtonSecondary:
739 case kEventMouseButtonTertiary:
743 Key_Event(key, '\0', eventKind == kEventMouseDown);
746 // Note: These two events are mutual exclusives
747 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
748 case kEventMouseMoved:
749 case kEventMouseDragged:
753 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
755 mouse_x += deltaPos.x;
756 mouse_y += deltaPos.y;
760 case kEventMouseWheelMoved:
763 unsigned int wheelEvent;
765 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
767 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
768 Key_Event(wheelEvent, 0, true);
769 Key_Event(wheelEvent, 0, false);
774 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
779 case kEventClassKeyboard:
785 case kEventRawKeyDown:
786 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
787 Handle_Key(keycode, true);
790 case kEventRawKeyRepeat:
794 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
795 Handle_Key(keycode, false);
798 case kEventRawKeyModifiersChanged:
801 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
802 Handle_KeyMod(keymod);
806 case kEventHotKeyPressed:
809 case kEventHotKeyReleased:
812 case kEventMouseWheelMoved:
816 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
822 case kEventClassTextInput:
823 Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
826 case kEventClassApplication:
829 case kEventAppActivated :
830 VID_AppFocusChanged(true);
832 case kEventAppDeactivated:
833 VID_AppFocusChanged(false);
838 case kEventAppActiveWindowChanged:
841 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
846 case kEventClassAppleEvent:
849 case kEventAppleEvent :
852 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
857 case kEventClassWindow:
860 case kEventWindowUpdate :
863 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
868 case kEventClassControl:
872 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
873 eventClass >> 24, (eventClass >> 16) & 0xFF,
874 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
879 SendEventToEventTarget (theEvent, theTarget);
880 ReleaseEvent(theEvent);
888 in_mouse_x = mouse_x;
889 in_mouse_y = mouse_y;