4 Mac OS X OpenGL and input module, using Carbon and AGL
6 Copyright (C) 2005 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;
35 AGLPixelFormat (*qaglChoosePixelFormat) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList);
36 AGLContext (*qaglCreateContext) (AGLPixelFormat pix, AGLContext share);
37 GLboolean (*qaglDestroyContext) (AGLContext ctx);
38 void (*qaglDestroyPixelFormat) (AGLPixelFormat pix);
39 GLboolean (*qaglSetCurrentContext) (AGLContext ctx);
40 GLboolean (*qaglSetDrawable) (AGLContext ctx, AGLDrawable draw);
41 GLboolean (*qaglSetFullScreen) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device);
42 void (*qaglSwapBuffers) (AGLContext ctx);
44 static qboolean mouse_avail = true;
45 static qboolean vid_usingmouse = false;
46 static float mouse_x, mouse_y;
48 static qboolean vid_isfullscreen = false;
50 static int scr_width, scr_height;
52 static AGLContext context;
53 static WindowRef window;
56 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
63 static void IN_Activate( qboolean grab )
67 if (!vid_usingmouse && mouse_avail && window)
75 // Put the mouse cursor at the center of the window
76 GetWindowBounds (window, kWindowContentRgn, &winBounds);
77 winCenter.x = (winBounds.left + winBounds.right) / 2;
78 winCenter.y = (winBounds.top + winBounds.bottom) / 2;
79 CGWarpMouseCursorPosition(winCenter);
81 // Lock the mouse pointer at its current position
82 CGAssociateMouseAndMouseCursorPosition(false);
84 mouse_x = mouse_y = 0;
85 vid_usingmouse = true;
92 CGAssociateMouseAndMouseCursorPosition(true);
95 vid_usingmouse = false;
100 void VID_Finish (void)
102 qboolean vid_usemouse;
104 // handle the mouse state when windowed if that's changed
105 vid_usemouse = false;
106 if (vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
108 if (!vid_activewindow)
109 vid_usemouse = false;
110 if (vid_isfullscreen)
112 IN_Activate(vid_usemouse);
114 if (r_render.integer)
116 if (r_speeds.integer || gl_finish.integer)
118 qaglSwapBuffers(context);
122 int VID_SetGamma(unsigned short *ramps)
128 int VID_GetGamma(unsigned short *ramps)
134 void signal_handler(int sig)
136 printf("Received signal %d, exiting...\n", sig);
137 VID_RestoreSystemGamma();
144 signal(SIGHUP, signal_handler);
145 signal(SIGINT, signal_handler);
146 signal(SIGQUIT, signal_handler);
147 signal(SIGILL, signal_handler);
148 signal(SIGTRAP, signal_handler);
149 signal(SIGIOT, signal_handler);
150 signal(SIGBUS, signal_handler);
151 signal(SIGFPE, signal_handler);
152 signal(SIGSEGV, signal_handler);
153 signal(SIGTERM, signal_handler);
158 InitSig(); // trap evil signals
159 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
160 if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
164 static void *prjobj = NULL;
166 static void GL_CloseLibrary(void)
174 gl_platformextensions = "";
177 static int GL_OpenLibrary(void)
179 const char *name = "/System/Library/Frameworks/AGL.framework/AGL";
181 Con_Printf("Loading OpenGL driver %s\n", name);
183 if (!(prjobj = dlopen(name, RTLD_LAZY)))
185 Con_Printf("Unable to open symbol list for %s\n", name);
188 strcpy(gl_driver, name);
192 void *GL_GetProcAddress(const char *name)
194 return dlsym(prjobj, name);
197 void VID_Shutdown(void)
199 if (context == NULL || window == NULL)
203 VID_RestoreSystemGamma();
207 qaglDestroyContext(context);
213 DisposeWindow(window);
218 vid_isfullscreen = false;
224 // Since the event handler can be called at any time, we store the events for later processing
225 static qboolean AsyncEvent_Quitting = false;
226 static qboolean AsyncEvent_Collapsed = false;
227 static OSStatus MainWindowEventHandler (EventHandlerCallRef nextHandler, EventRef event, void *userData)
229 OSStatus err = noErr;
231 switch (GetEventKind (event))
233 case kEventWindowClosed:
234 //Con_Printf(">> kEventWindowClosed (received) <<\n");
235 AsyncEvent_Quitting = true;
239 case kEventWindowCollapsing:
240 //Con_Printf(">> kEventWindowCollapsing (received) <<\n");
241 AsyncEvent_Collapsed = true;
244 // Undocked / restored (end)
245 case kEventWindowExpanded:
246 //Con_Printf(">> kEventWindowExpanded (received) <<\n");
247 AsyncEvent_Collapsed = false;
251 err = eventNotHandledErr;
258 static void VID_ProcessPendingAsyncEvents (void)
260 // Collapsed / expanded
261 if (AsyncEvent_Collapsed != vid_hidden)
265 Con_Printf(">> kEventWindowExpanded (processed) <<\n");
267 Con_Printf(">> kEventWindowCollapsing (processed) <<\n");
270 vid_hidden = !vid_hidden;
271 vid_activewindow = false;
272 VID_RestoreSystemGamma();
276 if (AsyncEvent_Quitting)
278 //Con_Printf(">> kEventWindowClosed (processed) <<\n");
283 static void VID_BuildAGLAttrib(GLint *attrib, int stencil, qboolean fullscreen)
285 *attrib++ = AGL_RGBA;
286 *attrib++ = AGL_RED_SIZE;*attrib++ = 1;
287 *attrib++ = AGL_GREEN_SIZE;*attrib++ = 1;
288 *attrib++ = AGL_BLUE_SIZE;*attrib++ = 1;
289 *attrib++ = AGL_DOUBLEBUFFER;
290 *attrib++ = AGL_DEPTH_SIZE;*attrib++ = 1;
291 // if stencil is enabled, ask for alpha too
294 *attrib++ = AGL_STENCIL_SIZE;*attrib++ = 8;
295 *attrib++ = AGL_ALPHA_SIZE;*attrib++ = 1;
298 *attrib++ = AGL_FULLSCREEN;
299 *attrib++ = AGL_NONE;
302 int VID_InitMode(int fullscreen, int width, int height, int bpp)
304 const EventTypeSpec winEvents[] =
306 { kEventClassWindow, kEventWindowClosed },
307 { kEventClassWindow, kEventWindowCollapsing },
308 { kEventClassWindow, kEventWindowExpanded },
310 OSStatus carbonError;
313 AGLPixelFormat pixelFormat;
314 GLint attributes [32];
316 if (!GL_OpenLibrary())
318 Con_Printf("Unable to load GL driver\n");
322 if ((qaglChoosePixelFormat = (AGLPixelFormat (*) (const AGLDevice *gdevs, GLint ndev, const GLint *attribList))GL_GetProcAddress("aglChoosePixelFormat")) == NULL
323 || (qaglCreateContext = (AGLContext (*) (AGLPixelFormat pix, AGLContext share))GL_GetProcAddress("aglCreateContext")) == NULL
324 || (qaglDestroyContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglDestroyContext")) == NULL
325 || (qaglDestroyPixelFormat = (void (*) (AGLPixelFormat pix))GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
326 || (qaglSetCurrentContext = (GLboolean (*) (AGLContext ctx))GL_GetProcAddress("aglSetCurrentContext")) == NULL
327 || (qaglSetDrawable = (GLboolean (*) (AGLContext ctx, AGLDrawable draw))GL_GetProcAddress("aglSetDrawable")) == NULL
328 || (qaglSetFullScreen = (GLboolean (*) (AGLContext ctx, GLsizei width, GLsizei height, GLsizei freq, GLint device))GL_GetProcAddress("aglSetFullScreen")) == NULL
329 || (qaglSwapBuffers = (void (*) (AGLContext ctx))GL_GetProcAddress("aglSwapBuffers")) == NULL
332 Con_Printf("AGL functions not found\n");
333 ReleaseWindow(window);
337 // Ignore the events from the previous window
338 AsyncEvent_Quitting = false;
339 AsyncEvent_Collapsed = false;
342 SetRect(&windowBounds, 0, 0, width, height);
343 OffsetRect(&windowBounds, 100, 100); // move it a bit towards the center of the screen
344 carbonError = CreateNewWindow(kDocumentWindowClass, kWindowStandardFloatingAttributes | kWindowStandardHandlerAttribute, &windowBounds, &window);
345 if (carbonError != noErr || window == NULL)
347 Con_Printf("Unable to create window (error %d)\n", carbonError);
351 // Set the window title
352 CFStringRef windowTitle = CFSTR("DarkPlaces AGL");
353 SetWindowTitleWithCFString(window, windowTitle);
354 CFRelease(windowTitle);
356 // Install the callback function for the window events we can't get
357 // through ReceiveNextEvent (i.e. close, collapse, and expand)
358 InstallWindowEventHandler (window, NewEventHandlerUPP (MainWindowEventHandler),
359 GetEventTypeCount(winEvents), winEvents, window, NULL);
361 screen = GetGWorldDevice(GetWindowPort(window));
364 Con_Printf("Unable to get GDevice for window\n");
365 ReleaseWindow(window);
369 // Create and set pixel format
370 VID_BuildAGLAttrib(attributes, bpp == 32, fullscreen);
371 pixelFormat = qaglChoosePixelFormat(&screen, 1, attributes);
372 if (pixelFormat == NULL)
374 Con_Printf("Unable to create pixel format\n");
375 ReleaseWindow(window);
379 // Set context and show the window
380 context = qaglCreateContext(pixelFormat, NULL);
382 Sys_Error ("aglCreateContext failed");
385 if (!qaglSetFullScreen (context, width, height, 0, 0))
386 Sys_Error("aglSetFullScreen failed");
387 vid_isfullscreen = true;
391 if (!qaglSetDrawable(context, GetWindowPort(window)))
392 Sys_Error ("aglSetDrawable failed");
394 if (!qaglSetCurrentContext(context))
395 Sys_Error ("aglSetCurrentContext failed");
396 qaglDestroyPixelFormat(pixelFormat);
401 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
402 Sys_Error("glGetString not found in %s", gl_driver);
404 gl_renderer = (const char *)qglGetString(GL_RENDERER);
405 gl_vendor = (const char *)qglGetString(GL_VENDOR);
406 gl_version = (const char *)qglGetString(GL_VERSION);
407 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
409 gl_videosyncavailable = false;
411 vid_usingmouse = false;
413 vid_activewindow = true;
416 SelectWindow(window);
422 static void Handle_KeyMod(UInt32 keymod)
424 static UInt32 prev_keymod = 0;
425 UInt32 modChanges = prev_keymod ^ keymod;
427 if ((modChanges & cmdKey) != 0)
429 Key_Event(K_AUX1, '\0', (keymod & cmdKey) != 0);
431 if ((modChanges & shiftKey) != 0 || (modChanges & rightShiftKey) != 0)
433 Key_Event(K_SHIFT, '\0', (keymod & shiftKey) != 0);
435 if ((modChanges & alphaLock) != 0)
437 Key_Event(K_CAPSLOCK, '\0', (keymod & alphaLock) != 0);
439 if ((modChanges & optionKey) != 0 || (modChanges & rightOptionKey) != 0)
441 Key_Event(K_ALT, '\0', (keymod & optionKey) != 0);
443 if ((modChanges & controlKey) != 0 || (modChanges & rightControlKey) != 0)
445 Key_Event(K_CTRL, '\0', (keymod & controlKey) != 0);
447 if ((modChanges & kEventKeyModifierNumLockMask) != 0)
449 Key_Event(K_NUMLOCK, '\0', (keymod & kEventKeyModifierNumLockMask) != 0);
451 if ((modChanges & kEventKeyModifierFnMask) != 0)
453 Key_Event(K_AUX2, '\0', (keymod & kEventKeyModifierFnMask) != 0);
456 prev_keymod = keymod;
459 static void Handle_Key(unsigned char charcode, qboolean keypressed)
461 unsigned int keycode = 0;
470 keycode = K_KP_ENTER;
475 case kBackspaceCharCode:
476 keycode = K_BACKSPACE;
481 case kPageUpCharCode:
484 case kPageDownCharCode:
487 case kReturnCharCode:
490 case kEscapeCharCode:
493 case kLeftArrowCharCode:
494 keycode = K_LEFTARROW;
496 case kRightArrowCharCode:
497 keycode = K_RIGHTARROW;
499 case kUpArrowCharCode:
502 case kDownArrowCharCode :
503 keycode = K_DOWNARROW;
505 case kDeleteCharCode:
509 // char 191 is sent by the mouse buttons (?!)
512 if ('A' <= charcode && charcode <= 'Z')
514 keycode = charcode + ('a' - 'A'); // lowercase it
517 else if (32 <= charcode)
523 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
527 Key_Event(keycode, ascii, keypressed);
530 void Sys_SendKeyEvents(void)
533 EventTargetRef theTarget;
535 // Start by processing the asynchronous events we received since the previous frame
536 VID_ProcessPendingAsyncEvents();
538 theTarget = GetEventDispatcherTarget();
539 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
541 UInt32 eventClass = GetEventClass(theEvent);
542 UInt32 eventKind = GetEventKind(theEvent);
546 case kEventClassMouse:
548 EventMouseButton theButton;
553 case kEventMouseDown:
555 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
559 case kEventMouseButtonPrimary:
561 //Con_Printf(">> kEventMouseButtonPrimary <<\n");
563 case kEventMouseButtonSecondary:
565 //Con_Printf(">> kEventMouseButtonSecondary <<\n");
567 case kEventMouseButtonTertiary:
569 //Con_Printf(">> kEventMouseButtonTertiary <<\n");
572 Key_Event(key, '\0', eventKind == kEventMouseDown);
575 case kEventMouseMoved:
579 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
580 //Con_Printf(">> kEventMouseMoved (%f, %f) <<\n", deltaPos.x, deltaPos.y);
582 mouse_x += deltaPos.x;
583 mouse_y += deltaPos.y;
587 case kEventMouseWheelMoved:
590 unsigned int wheelEvent;
592 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
593 //Con_Printf(">> kEventMouseWheelMoved (delta: %d) <<\n", delta);
595 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
596 Key_Event(wheelEvent, 0, true);
597 Key_Event(wheelEvent, 0, false);
601 case kEventMouseDragged:
602 //Con_Printf(">> kEventMouseDragged <<\n");
606 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
611 case kEventClassKeyboard:
617 case kEventRawKeyDown:
618 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
619 Handle_Key(keycode, true);
620 //Con_Printf(">> kEventRawKeyDown (%d) <<\n", keycode);
623 case kEventRawKeyRepeat:
624 //Con_Printf(">> kEventRawKeyRepeat <<\n");
628 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
629 Handle_Key(keycode, false);
630 //Con_Printf(">> kEventRawKeyUp (%d) <<\n", keycode);
633 case kEventRawKeyModifiersChanged:
636 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
637 Handle_KeyMod(keymod);
638 //Con_Printf(">> kEventRawKeyModifiersChanged (0x%08X) <<\n", keymod);
642 case kEventHotKeyPressed:
643 //Con_Printf(">> kEventHotKeyPressed <<\n");
646 case kEventHotKeyReleased:
647 //Con_Printf(">> kEventHotKeyReleased <<\n");
650 case kEventMouseWheelMoved:
651 //Con_Printf(">> kEventMouseWheelMoved - via a keyboard event (!?) <<\n");
655 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
661 case kEventClassTextInput:
662 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
665 case kEventClassApplication:
668 case kEventAppActivated :
669 //Con_Printf(">> kEventAppActivated <<\n");
670 vid_activewindow = true;
672 case kEventAppDeactivated:
673 //Con_Printf(">> kEventAppDeactivated <<\n");
674 vid_activewindow = false;
675 VID_RestoreSystemGamma();
678 //Con_Printf(">> kEventAppQuit <<\n");
681 case kEventAppActiveWindowChanged:
682 //Con_Printf(">> kEventAppActiveWindowChanged <<\n");
685 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
690 case kEventClassAppleEvent:
693 case kEventAppleEvent :
694 //Con_Printf(">> kEventAppleEvent <<\n");
697 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
702 case kEventClassWindow:
705 case kEventWindowUpdate :
706 //Con_Printf(">> kEventWindowUpdate <<\n");
709 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
714 case kEventClassControl:
715 //Con_Printf(">> kEventClassControl (%d) <<\n", eventKind);
719 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
720 eventClass >> 24, (eventClass >> 16) & 0xFF,
721 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
726 SendEventToEventTarget (theEvent, theTarget);
727 ReleaseEvent(theEvent);
735 in_mouse_x = mouse_x;
736 in_mouse_y = mouse_y;