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 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
42 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
43 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
44 GLboolean (*qaglSetInteger) (AGLContext ctx, GLenum pname, const GLint *params);
45 void (*qaglSwapBuffers) (AGLContext ctx);
47 static qboolean mouse_avail = true;
48 static qboolean vid_usingmouse = false;
49 static float mouse_x, mouse_y;
51 static qboolean vid_isfullscreen = false;
52 static qboolean vid_usingvsync = false;
54 static int scr_width, scr_height;
56 static AGLContext context;
57 static WindowRef window;
60 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
67 static void IN_Activate( qboolean grab )
71 if (!vid_usingmouse && mouse_avail && window)
77 CGDisplayHideCursor(CGMainDisplayID());
79 // Put the mouse cursor at the center of the window
80 GetWindowBounds (window, kWindowContentRgn, &winBounds);
81 winCenter.x = (winBounds.left + winBounds.right) / 2;
82 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
83 CGWarpMouseCursorPosition(winCenter);
85 // Lock the mouse pointer at its current position
86 CGAssociateMouseAndMouseCursorPosition(false);
88 mouse_x = mouse_y = 0;
89 vid_usingmouse = true;
96 CGAssociateMouseAndMouseCursorPosition(true);
97 CGDisplayShowCursor(CGMainDisplayID());
99 vid_usingmouse = false;
104 #define GAMMA_TABLE_SIZE 256
105 void VID_Finish (qboolean allowmousegrab)
107 qboolean vid_usemouse;
108 qboolean vid_usevsync;
110 // handle the mouse state when windowed if that's changed
111 vid_usemouse = false;
112 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
114 if (!vid_activewindow)
115 vid_usemouse = false;
116 if (vid_isfullscreen)
118 IN_Activate(vid_usemouse);
120 // handle changes of the vsync option
121 vid_usevsync = (vid_vsync.integer && !cls.timedemo);
122 if (vid_usingvsync != vid_usevsync)
124 GLint sync = (vid_usevsync ? 1 : 0);
126 if (qaglSetInteger(context, AGL_SWAP_INTERVAL, &sync) == GL_TRUE)
128 vid_usingvsync = vid_usevsync;
129 Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
132 Con_Printf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
135 if (r_render.integer)
137 if (r_speeds.integer || gl_finish.integer)
139 qaglSwapBuffers(context);
141 VID_UpdateGamma(false, GAMMA_TABLE_SIZE);
144 int VID_SetGamma(unsigned short *ramps, int rampsize)
146 CGGammaValue table_red [GAMMA_TABLE_SIZE];
147 CGGammaValue table_green [GAMMA_TABLE_SIZE];
148 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
151 // Convert the unsigned short table into 3 float tables
152 for (i = 0; i < rampsize; i++)
153 table_red[i] = (float)ramps[i] / 65535.0f;
154 for (i = 0; i < rampsize; i++)
155 table_green[i] = (float)ramps[i + rampsize] / 65535.0f;
156 for (i = 0; i < rampsize; i++)
157 table_blue[i] = (float)ramps[i + 2 * rampsize] / 65535.0f;
159 if (CGSetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue) != CGDisplayNoErr)
161 Con_Print("VID_SetGamma: ERROR: CGSetDisplayTransferByTable failed!\n");
168 int VID_GetGamma(unsigned short *ramps, int rampsize)
170 CGGammaValue table_red [GAMMA_TABLE_SIZE];
171 CGGammaValue table_green [GAMMA_TABLE_SIZE];
172 CGGammaValue table_blue [GAMMA_TABLE_SIZE];
173 CGTableCount actualsize = 0;
176 // Get the gamma ramps from the system
177 if (CGGetDisplayTransferByTable(CGMainDisplayID(), rampsize, table_red, table_green, table_blue, &actualsize) != CGDisplayNoErr)
179 Con_Print("VID_GetGamma: ERROR: CGGetDisplayTransferByTable failed!\n");
182 if (actualsize != rampsize)
184 Con_Printf("VID_GetGamma: ERROR: invalid gamma table size (%u != %u)\n", actualsize, rampsize);
188 // Convert the 3 float tables into 1 unsigned short table
189 for (i = 0; i < rampsize; i++)
190 ramps[i] = table_red[i] * 65535.0f;
191 for (i = 0; i < rampsize; i++)
192 ramps[i + rampsize] = table_green[i] * 65535.0f;
193 for (i = 0; i < rampsize; i++)
194 ramps[i + 2 * rampsize] = table_blue[i] * 65535.0f;
199 void signal_handler(int sig)
201 printf("Received signal %d, exiting...\n", sig);
202 VID_RestoreSystemGamma();
209 signal(SIGHUP, signal_handler);
210 signal(SIGINT, signal_handler);
211 signal(SIGQUIT, signal_handler);
212 signal(SIGILL, signal_handler);
213 signal(SIGTRAP, signal_handler);
214 signal(SIGIOT, signal_handler);
215 signal(SIGBUS, signal_handler);
216 signal(SIGFPE, signal_handler);
217 signal(SIGSEGV, signal_handler);
218 signal(SIGTERM, signal_handler);
223 InitSig(); // trap evil signals
224 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
225 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
229 static void *prjobj = NULL;
231 static void GL_CloseLibrary(void)
239 gl_platformextensions = "";
242 static int GL_OpenLibrary(void)
244 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
246 Con_Printf("Loading OpenGL driver %s\n", name);
248 if (!(prjobj = dlopen(name, RTLD_LAZY)))
250 Con_Printf("Unable to open symbol list for %s\n", name);
253 strcpy(gl_driver, name);
257 void *GL_GetProcAddress(const char *name)
259 return dlsym(prjobj, name);
262 void VID_Shutdown(void)
264 if (context == NULL || window == NULL)
268 VID_RestoreSystemGamma();
272 qaglDestroyContext(context);
278 DisposeWindow(window);
283 vid_isfullscreen = false;
289 // Since the event handler can be called at any time, we store the events for later processing
290 static qboolean AsyncEvent_Quitting = false;
291 static qboolean AsyncEvent_Collapsed = false;
292 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
294 OSStatus err = noErr;
296 switch (GetEventKind (event))
298 case kEventWindowClosed:
299 AsyncEvent_Quitting = true;
303 case kEventWindowCollapsing:
304 AsyncEvent_Collapsed = true;
307 // Undocked / restored (end)
308 case kEventWindowExpanded:
309 AsyncEvent_Collapsed = false;
313 err = eventNotHandledErr;
320 static void VID_ProcessPendingAsyncEvents (void)
322 // Collapsed / expanded
323 if (AsyncEvent_Collapsed != vid_hidden)
325 vid_hidden = !vid_hidden;
326 vid_activewindow = false;
327 VID_RestoreSystemGamma();
331 if (AsyncEvent_Quitting)
337 static void VID_BuildAGLAttrib(GLint *attrib, GLint stencil, qboolean fullscreen)
339 *attrib++ = AGL_RGBA;
340 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
341 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
342 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
343 *attrib++ = AGL_DOUBLEBUFFER;
344 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
346 // if stencil is enabled, ask for alpha too
349 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
350 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
353 *attrib++ = AGL_FULLSCREEN;
354 *attrib++ = AGL_NONE;
357 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate)
359 const EventTypeSpec winEvents[] =
361 { kEventClassWindow, kEventWindowClosed },
362 { kEventClassWindow, kEventWindowCollapsing },
363 { kEventClassWindow, kEventWindowExpanded },
365 OSStatus carbonError;
367 AGLPixelFormat pixelFormat;
368 GLint attributes [32];
371 // FullScreen Display stuff
372 GDHandle gdhDisplay; // = GetMainDevice(); /*deprecated*/
373 CGDirectDisplayID mainDisplay = CGMainDisplayID();
375 if (!GL_OpenLibrary())
377 Con_Printf("Unable to load GL driver\n");
381 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
382 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
383 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
384 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
385 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
386 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
387 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
388 || (qaglSetInteger = (GLboolean (*) (AGLContext ctx, GLenum pname, const GLint *params))GL_GetProcAddress("aglSetInteger")) == NULL
389 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
392 Con_Printf("AGL functions not found\n");
393 ReleaseWindow(window);
397 // Ignore the events from the previous window
398 AsyncEvent_Quitting = false;
399 AsyncEvent_Collapsed = false;
401 // Create the window, a bit towards the center of the screen
402 windowBounds.left = 100;
403 windowBounds.top = 100;
404 windowBounds.right = width + 100;
405 windowBounds.bottom = height + 100;
406 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
407 if (carbonError != noErr || window == NULL)
409 Con_Printf("Unable to create window (error %d)\n", carbonError);
413 // Set the window title
414 CFStringRef windowTitle = CFSTR("DarkPlaces AGL");
415 SetWindowTitleWithCFString(window, windowTitle);
416 CFRelease(windowTitle);
418 // Install the callback function for the window events we can't get
419 // through ReceiveNextEvent (i.e. close, collapse, and expand)
420 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
421 GetEventTypeCount(winEvents), winEvents, window, NULL);
423 // Create the desired attribute list
424 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
429 // Set pixel format with built attribs
430 // Note: use NULL then must use 0
431 pixelFormat = qaglChoosePixelFormat(NULL, 0, attributes);
432 error = aglGetError();
433 if (error != AGL_NO_ERROR)
435 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
436 (char *)aglErrorString(error));
437 ReleaseWindow(window);
444 // Output is FullScreen
445 // Get the mainDisplay and set resolution to current
446 CGDisplayCapture (mainDisplay);
447 CFDictionaryRef refDisplayMode = CGDisplayBestModeForParameters (mainDisplay, bpp, width, height, NULL);
448 CGDisplaySwitchToMode (mainDisplay, refDisplayMode);
449 DMGetGDeviceByDisplayID ((DisplayIDType)mainDisplay, &gdhDisplay, false);
451 // Set pixel format with built attribs
452 // Note: specifying a device is *required* for AGL_FullScreen
453 pixelFormat = qaglChoosePixelFormat(&gdhDisplay, 1, attributes);
454 error = aglGetError();
455 if (error != AGL_NO_ERROR)
457 Con_Printf("qaglChoosePixelFormat FAILED: %s\n",
458 (char *)aglErrorString(error));
459 ReleaseWindow(window);
464 // Create a context using the pform
465 context = qaglCreateContext(pixelFormat, NULL);
466 error = aglGetError();
467 if (error != AGL_NO_ERROR)
469 Con_Printf("qaglCreateContext FAILED: %s\n",
470 (char *)aglErrorString(error));
473 // Make the context the current one ('enable' it)
474 qaglSetCurrentContext(context);
475 error = aglGetError();
476 if (error != AGL_NO_ERROR)
478 Con_Printf("qaglSetCurrentContext FAILED: %s\n",
479 (char *)aglErrorString(error));
480 ReleaseWindow(window);
485 qaglDestroyPixelFormat(pixelFormat);
487 // Attempt fullscreen if requested
490 qaglSetFullScreen (context, width, height, refreshrate, 0);
491 error = aglGetError();
492 if (error != AGL_NO_ERROR)
494 Con_Printf("qaglSetFullScreen FAILED: %s\n",
495 (char *)aglErrorString(error));
498 vid_isfullscreen = false;
502 // FullScreen Success
503 vid_isfullscreen = true;
509 // Note: this _is_ a Window != FullScreen
510 // Set Window as Drawable
511 qaglSetDrawable(context, GetWindowPort(window));
512 error = aglGetError();
513 if (error != AGL_NO_ERROR)
515 Con_Printf("qaglSetDrawable FAILED: %s\n",
516 (char *)aglErrorString(error));
517 ReleaseWindow(window);
526 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
527 Sys_Error("glGetString not found in %s", gl_driver);
529 gl_renderer = (const char *)qglGetString(GL_RENDERER);
530 gl_vendor = (const char *)qglGetString(GL_VENDOR);
531 gl_version = (const char *)qglGetString(GL_VERSION);
532 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
534 gl_videosyncavailable = true;
536 vid_usingmouse = false;
538 vid_activewindow = true;
541 SelectWindow(window);
547 static void Handle_KeyMod(UInt32 keymod)
549 static UInt32 prev_keymod = 0;
550 UInt32 modChanges = prev_keymod ^ keymod;
552 if ((modChanges & cmdKey) != 0)
554 Key_Event(K_AUX1, '\0', (keymod & cmdKey) != 0);
556 if ((modChanges & shiftKey) != 0 || (modChanges & rightShiftKey) != 0)
558 Key_Event(K_SHIFT, '\0', (keymod & shiftKey) != 0);
560 if ((modChanges & alphaLock) != 0)
562 Key_Event(K_CAPSLOCK, '\0', (keymod & alphaLock) != 0);
564 if ((modChanges & optionKey) != 0 || (modChanges & rightOptionKey) != 0)
566 Key_Event(K_ALT, '\0', (keymod & optionKey) != 0);
568 if ((modChanges & controlKey) != 0 || (modChanges & rightControlKey) != 0)
570 Key_Event(K_CTRL, '\0', (keymod & controlKey) != 0);
572 if ((modChanges & kEventKeyModifierNumLockMask) != 0)
574 Key_Event(K_NUMLOCK, '\0', (keymod & kEventKeyModifierNumLockMask) != 0);
576 if ((modChanges & kEventKeyModifierFnMask) != 0)
578 Key_Event(K_AUX2, '\0', (keymod & kEventKeyModifierFnMask) != 0);
581 prev_keymod = keymod;
584 static void Handle_Key(unsigned char charcode, qboolean keypressed)
586 unsigned int keycode = 0;
595 keycode = K_KP_ENTER;
600 case kBackspaceCharCode:
601 keycode = K_BACKSPACE;
606 case kPageUpCharCode:
609 case kPageDownCharCode:
612 case kReturnCharCode:
615 case kEscapeCharCode:
618 case kLeftArrowCharCode:
619 keycode = K_LEFTARROW;
621 case kRightArrowCharCode:
622 keycode = K_RIGHTARROW;
624 case kUpArrowCharCode:
627 case kDownArrowCharCode :
628 keycode = K_DOWNARROW;
630 case kDeleteCharCode:
635 // characters 0 and 191 are sent by the mouse buttons (?!)
638 if ('A' <= charcode && charcode <= 'Z')
640 keycode = charcode + ('a' - 'A'); // lowercase it
643 else if (charcode >= 32)
649 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
653 Key_Event(keycode, ascii, keypressed);
656 void Sys_SendKeyEvents(void)
659 EventTargetRef theTarget;
661 // Start by processing the asynchronous events we received since the previous frame
662 VID_ProcessPendingAsyncEvents();
664 theTarget = GetEventDispatcherTarget();
665 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
667 UInt32 eventClass = GetEventClass(theEvent);
668 UInt32 eventKind = GetEventKind(theEvent);
672 case kEventClassMouse:
674 EventMouseButton theButton;
679 case kEventMouseDown:
681 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
685 case kEventMouseButtonPrimary:
688 case kEventMouseButtonSecondary:
691 case kEventMouseButtonTertiary:
695 Key_Event(key, '\0', eventKind == kEventMouseDown);
698 // Note: These two events are mutual exclusives
699 // Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
700 case kEventMouseMoved:
701 case kEventMouseDragged:
705 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
707 mouse_x += deltaPos.x;
708 mouse_y += deltaPos.y;
712 case kEventMouseWheelMoved:
715 unsigned int wheelEvent;
717 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
719 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
720 Key_Event(wheelEvent, 0, true);
721 Key_Event(wheelEvent, 0, false);
726 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
731 case kEventClassKeyboard:
737 case kEventRawKeyDown:
738 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
739 Handle_Key(keycode, true);
742 case kEventRawKeyRepeat:
746 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
747 Handle_Key(keycode, false);
750 case kEventRawKeyModifiersChanged:
753 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
754 Handle_KeyMod(keymod);
758 case kEventHotKeyPressed:
761 case kEventHotKeyReleased:
764 case kEventMouseWheelMoved:
768 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
774 case kEventClassTextInput:
775 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
778 case kEventClassApplication:
781 case kEventAppActivated :
782 vid_activewindow = true;
784 case kEventAppDeactivated:
785 vid_activewindow = false;
786 VID_RestoreSystemGamma();
791 case kEventAppActiveWindowChanged:
794 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
799 case kEventClassAppleEvent:
802 case kEventAppleEvent :
805 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
810 case kEventClassWindow:
813 case kEventWindowUpdate :
816 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
821 case kEventClassControl:
825 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
826 eventClass >> 24, (eventClass >> 16) & 0xFF,
827 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
832 SendEventToEventTarget (theEvent, theTarget);
833 ReleaseEvent(theEvent);
841 in_mouse_x = mouse_x;
842 in_mouse_y = mouse_y;