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 = GL_GetProcAddress("aglChoosePixelFormat")) == NULL
323 || (qaglCreateContext = GL_GetProcAddress("aglCreateContext")) == NULL
324 || (qaglDestroyContext = GL_GetProcAddress("aglDestroyContext")) == NULL
325 || (qaglDestroyPixelFormat = GL_GetProcAddress("aglDestroyPixelFormat")) == NULL
326 || (qaglSetCurrentContext = GL_GetProcAddress("aglSetCurrentContext")) == NULL
327 || (qaglSetDrawable = GL_GetProcAddress("aglSetDrawable")) == NULL
328 || (qaglSetFullScreen = GL_GetProcAddress("aglSetFullScreen")) == NULL
329 || (qaglSwapBuffers = 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);
381 qaglDestroyPixelFormat(pixelFormat);
383 Sys_Error ("aglCreateContext failed\n");
384 if (!qaglSetDrawable(context, GetWindowPort(window)))
385 Sys_Error ("aglSetDrawable failed\n");
386 if (!qaglSetCurrentContext(context))
387 Sys_Error ("aglSetCurrentContext failed\n");
392 if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
393 Sys_Error("glGetString not found in %s", gl_driver);
397 if (!qaglSetFullScreen (context, width, height, 0, 0))
398 Sys_Error("aglSetFullScreen failed\n");
399 vid_isfullscreen = true;
402 gl_renderer = qglGetString(GL_RENDERER);
403 gl_vendor = qglGetString(GL_VENDOR);
404 gl_version = qglGetString(GL_VERSION);
405 gl_extensions = qglGetString(GL_EXTENSIONS);
407 gl_videosyncavailable = false;
409 vid_usingmouse = false;
411 vid_activewindow = true;
414 SelectWindow(window);
420 static void Handle_KeyMod(UInt32 keymod)
422 static UInt32 prev_keymod = 0;
423 UInt32 modChanges = prev_keymod ^ keymod;
425 if ((modChanges & cmdKey) != 0)
427 Key_Event(K_AUX1, '\0', (keymod & cmdKey) != 0);
429 if ((modChanges & shiftKey) != 0 || (modChanges & rightShiftKey) != 0)
431 Key_Event(K_SHIFT, '\0', (keymod & shiftKey) != 0);
433 if ((modChanges & alphaLock) != 0)
435 Key_Event(K_CAPSLOCK, '\0', (keymod & alphaLock) != 0);
437 if ((modChanges & optionKey) != 0 || (modChanges & rightOptionKey) != 0)
439 Key_Event(K_ALT, '\0', (keymod & optionKey) != 0);
441 if ((modChanges & controlKey) != 0 || (modChanges & rightControlKey) != 0)
443 Key_Event(K_CTRL, '\0', (keymod & controlKey) != 0);
445 if ((modChanges & kEventKeyModifierNumLockMask) != 0)
447 Key_Event(K_NUMLOCK, '\0', (keymod & kEventKeyModifierNumLockMask) != 0);
449 if ((modChanges & kEventKeyModifierFnMask) != 0)
451 Key_Event(K_AUX2, '\0', (keymod & kEventKeyModifierFnMask) != 0);
454 prev_keymod = keymod;
457 static void Handle_Key(qbyte charcode, qboolean keypressed)
459 unsigned int keycode = 0;
468 keycode = K_KP_ENTER;
473 case kBackspaceCharCode:
474 keycode = K_BACKSPACE;
479 case kPageUpCharCode:
482 case kPageDownCharCode:
485 case kReturnCharCode:
488 case kEscapeCharCode:
491 case kLeftArrowCharCode:
492 keycode = K_LEFTARROW;
494 case kRightArrowCharCode:
495 keycode = K_RIGHTARROW;
497 case kUpArrowCharCode:
500 case kDownArrowCharCode :
501 keycode = K_DOWNARROW;
503 case kDeleteCharCode:
507 // char 191 is sent by the mouse buttons (?!)
510 if ('A' <= charcode && charcode <= 'Z')
512 keycode = charcode + ('a' - 'A'); // lowercase it
515 else if (32 <= charcode && charcode <= 126)
521 Con_Printf(">> UNKNOWN charcode: %d <<\n", charcode);
525 Key_Event(keycode, ascii, keypressed);
528 void Sys_SendKeyEvents(void)
531 EventTargetRef theTarget;
533 // Start by processing the asynchronous events we received since the previous frame
534 VID_ProcessPendingAsyncEvents();
536 theTarget = GetEventDispatcherTarget();
537 while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
539 UInt32 eventClass = GetEventClass(theEvent);
540 UInt32 eventKind = GetEventKind(theEvent);
544 case kEventClassMouse:
546 EventMouseButton theButton;
551 case kEventMouseDown:
553 GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
557 case kEventMouseButtonPrimary:
559 //Con_Printf(">> kEventMouseButtonPrimary <<\n");
561 case kEventMouseButtonSecondary:
563 //Con_Printf(">> kEventMouseButtonSecondary <<\n");
565 case kEventMouseButtonTertiary:
567 //Con_Printf(">> kEventMouseButtonTertiary <<\n");
570 Key_Event(key, '\0', eventKind == kEventMouseDown);
573 case kEventMouseMoved:
577 GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
578 //Con_Printf(">> kEventMouseMoved (%f, %f) <<\n", deltaPos.x, deltaPos.y);
580 mouse_x += deltaPos.x;
581 mouse_y += deltaPos.y;
585 case kEventMouseWheelMoved:
588 unsigned int wheelEvent;
590 GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);
591 //Con_Printf(">> kEventMouseWheelMoved (delta: %d) <<\n", delta);
593 wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
594 Key_Event(wheelEvent, 0, true);
595 Key_Event(wheelEvent, 0, false);
599 case kEventMouseDragged:
600 //Con_Printf(">> kEventMouseDragged <<\n");
604 Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %d) <<\n", eventKind);
609 case kEventClassKeyboard:
615 case kEventRawKeyDown:
616 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
617 Handle_Key(keycode, true);
618 //Con_Printf(">> kEventRawKeyDown (%d) <<\n", keycode);
621 case kEventRawKeyRepeat:
622 //Con_Printf(">> kEventRawKeyRepeat <<\n");
626 GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(keycode), NULL, &keycode);
627 Handle_Key(keycode, false);
628 //Con_Printf(">> kEventRawKeyUp (%d) <<\n", keycode);
631 case kEventRawKeyModifiersChanged:
634 GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
635 Handle_KeyMod(keymod);
636 //Con_Printf(">> kEventRawKeyModifiersChanged (0x%08X) <<\n", keymod);
640 case kEventHotKeyPressed:
641 //Con_Printf(">> kEventHotKeyPressed <<\n");
644 case kEventHotKeyReleased:
645 //Con_Printf(">> kEventHotKeyReleased <<\n");
648 case kEventMouseWheelMoved:
649 //Con_Printf(">> kEventMouseWheelMoved - via a keyboard event (!?) <<\n");
653 Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %d) <<\n", eventKind);
659 case kEventClassTextInput:
660 Con_Printf(">> kEventClassTextInput (%d) <<\n", eventKind);
663 case kEventClassApplication:
666 case kEventAppActivated :
667 //Con_Printf(">> kEventAppActivated <<\n");
668 vid_activewindow = true;
670 case kEventAppDeactivated:
671 //Con_Printf(">> kEventAppDeactivated <<\n");
672 vid_activewindow = false;
673 VID_RestoreSystemGamma();
676 //Con_Printf(">> kEventAppQuit <<\n");
679 case kEventAppActiveWindowChanged:
680 //Con_Printf(">> kEventAppActiveWindowChanged <<\n");
683 Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %d) <<\n", eventKind);
688 case kEventClassAppleEvent:
691 case kEventAppleEvent :
692 //Con_Printf(">> kEventAppleEvent <<\n");
695 Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %d) <<\n", eventKind);
700 case kEventClassWindow:
703 case kEventWindowUpdate :
704 //Con_Printf(">> kEventWindowUpdate <<\n");
707 Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %d) <<\n", eventKind);
712 case kEventClassControl:
713 //Con_Printf(">> kEventClassControl (%d) <<\n", eventKind);
717 /*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
718 eventClass >> 24, (eventClass >> 16) & 0xFF,
719 (eventClass >> 8) & 0xFF, eventClass & 0xFF,
724 SendEventToEventTarget (theEvent, theTarget);
725 ReleaseEvent(theEvent);
733 in_mouse_x = mouse_x;
734 in_mouse_y = mouse_y;