cleaned up vid_dga code, removed vid_dga_mouseaccel cvar as it did the
[divverent/darkplaces.git] / vid_glx.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20 #include <signal.h>
21
22 #include <dlfcn.h>
23
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <GL/glx.h>
27
28 #include <X11/keysym.h>
29 #include <X11/cursorfont.h>
30
31 #include <X11/extensions/XShm.h>
32 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
33 #include <X11/extensions/xf86dga.h>
34 #endif
35 #include <X11/extensions/xf86vmode.h>
36
37 #include "quakedef.h"
38
39 // Tell startup code that we have a client
40 int cl_available = true;
41
42 // note: if we used the XRandR extension we could support refresh rates
43 qboolean vid_supportrefreshrate = false;
44
45 //GLX prototypes
46 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
47 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
48 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
49 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
50 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
51 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
52
53 //GLX_ARB_get_proc_address
54 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
55
56 static dllfunction_t getprocaddressfuncs[] =
57 {
58         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
59         {NULL, NULL}
60 };
61
62 //GLX_SGI_swap_control
63 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
64
65 static dllfunction_t swapcontrolfuncs[] =
66 {
67         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
68         {NULL, NULL}
69 };
70
71 static Display *vidx11_display = NULL;
72 static int vidx11_screen;
73 static Window win;
74 static GLXContext ctx = NULL;
75
76 Atom wm_delete_window_atom;
77
78 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
79 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
80                     PointerMotionMask | ButtonMotionMask)
81 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
82                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
83                 LeaveWindowMask)
84
85
86 static qboolean mouse_avail = true;
87 static qboolean vid_usingmouse = false;
88 static qboolean vid_usingvsync = false;
89 static qboolean vid_usevsync = false;
90 static qboolean vid_x11_hardwaregammasupported = false;
91 static qboolean vid_x11_dgasupported = false;
92 static int vid_x11_gammarampsize = 0;
93 static float    mouse_x, mouse_y;
94 static int p_mouse_x, p_mouse_y;
95
96 #if !defined(__APPLE__) && !defined(SUNOS)
97 // FIXME: vid_dga_mouseaccel is poorly named, it is actually the multiplier for mouse movement, not an acceleration (which would be a power function or something)
98 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1", "make use of DGA mouse input"};
99 #endif
100
101 qboolean vidmode_ext = false;
102
103 static int win_x, win_y;
104
105 static XF86VidModeModeInfo init_vidmode;
106 static qboolean vid_isfullscreen = false;
107
108 static Visual *vidx11_visual;
109 static Colormap vidx11_colormap;
110
111 /*-----------------------------------------------------------------------*/
112
113 static int XLateKey(XKeyEvent *ev, char *ascii)
114 {
115         int key = 0;
116         char buf[64];
117         KeySym keysym, shifted;
118
119         keysym = XLookupKeysym (ev, 0);
120         XLookupString(ev, buf, sizeof buf, &shifted, 0);
121         *ascii = buf[0];
122
123         switch(keysym)
124         {
125                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
126                 case XK_Page_Up:         key = K_PGUP; break;
127
128                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
129                 case XK_Page_Down:       key = K_PGDN; break;
130
131                 case XK_KP_Home: key = K_KP_HOME; break;
132                 case XK_Home:    key = K_HOME; break;
133
134                 case XK_KP_End:  key = K_KP_END; break;
135                 case XK_End:     key = K_END; break;
136
137                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
138                 case XK_Left:    key = K_LEFTARROW; break;
139
140                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
141                 case XK_Right:  key = K_RIGHTARROW;             break;
142
143                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
144                 case XK_Down:    key = K_DOWNARROW; break;
145
146                 case XK_KP_Up:   key = K_KP_UPARROW; break;
147                 case XK_Up:              key = K_UPARROW;        break;
148
149                 case XK_Escape: key = K_ESCAPE;         break;
150
151                 case XK_KP_Enter: key = K_KP_ENTER;     break;
152                 case XK_Return: key = K_ENTER;           break;
153
154                 case XK_Tab:            key = K_TAB;                     break;
155
156                 case XK_F1:              key = K_F1;                            break;
157
158                 case XK_F2:              key = K_F2;                            break;
159
160                 case XK_F3:              key = K_F3;                            break;
161
162                 case XK_F4:              key = K_F4;                            break;
163
164                 case XK_F5:              key = K_F5;                            break;
165
166                 case XK_F6:              key = K_F6;                            break;
167
168                 case XK_F7:              key = K_F7;                            break;
169
170                 case XK_F8:              key = K_F8;                            break;
171
172                 case XK_F9:              key = K_F9;                            break;
173
174                 case XK_F10:            key = K_F10;                     break;
175
176                 case XK_F11:            key = K_F11;                     break;
177
178                 case XK_F12:            key = K_F12;                     break;
179
180                 case XK_BackSpace: key = K_BACKSPACE; break;
181
182                 case XK_KP_Delete: key = K_KP_DEL; break;
183                 case XK_Delete: key = K_DEL; break;
184
185                 case XK_Pause:  key = K_PAUSE;           break;
186
187                 case XK_Shift_L:
188                 case XK_Shift_R:        key = K_SHIFT;          break;
189
190                 case XK_Execute:
191                 case XK_Control_L:
192                 case XK_Control_R:      key = K_CTRL;            break;
193
194                 case XK_Alt_L:
195                 case XK_Meta_L:
196                 case XK_ISO_Level3_Shift:
197                 case XK_Alt_R:
198                 case XK_Meta_R: key = K_ALT;                    break;
199
200                 case XK_KP_Begin: key = K_KP_5; break;
201
202                 case XK_Insert:key = K_INS; break;
203                 case XK_KP_Insert: key = K_KP_INS; break;
204
205                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
206                 case XK_KP_Add:  key = K_KP_PLUS; break;
207                 case XK_KP_Subtract: key = K_KP_MINUS; break;
208                 case XK_KP_Divide: key = K_KP_SLASH; break;
209
210                 case XK_section:        key = '~'; break;
211
212                 default:
213                         if (keysym < 32)
214                                 break;
215
216                         if (keysym >= 'A' && keysym <= 'Z')
217                                 key = keysym - 'A' + 'a';
218                         else
219                                 key = keysym;
220
221                         break;
222         }
223
224         return key;
225 }
226
227 static Cursor CreateNullCursor(Display *display, Window root)
228 {
229         Pixmap cursormask;
230         XGCValues xgc;
231         GC gc;
232         XColor dummycolour;
233         Cursor cursor;
234
235         cursormask = XCreatePixmap(display, root, 1, 1, 1);
236         xgc.function = GXclear;
237         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
238         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
239         dummycolour.pixel = 0;
240         dummycolour.red = 0;
241         dummycolour.flags = 04;
242         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
243         XFreePixmap(display,cursormask);
244         XFreeGC(display,gc);
245         return cursor;
246 }
247
248 static void IN_Activate (qboolean grab)
249 {
250         if (!vidx11_display)
251                 return;
252         if (grab)
253         {
254                 if (!vid_usingmouse && mouse_avail && win)
255                 {
256                         XWindowAttributes attribs_1;
257                         XSetWindowAttributes attribs_2;
258
259                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
260                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
261                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
262
263                 // inviso cursor
264                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
265
266                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
267
268 #if !defined(__APPLE__) && !defined(SUNOS)
269                         if (vid_dga.integer && vid_x11_dgasupported)
270                         {
271                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
272                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
273                         }
274                         else
275 #endif
276                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
277
278                         if (vid_grabkeyboard.integer || vid_isfullscreen)
279                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
280
281                         mouse_x = mouse_y = 0;
282                         cl_ignoremousemove = true;
283                         vid_usingmouse = true;
284                 }
285         }
286         else
287         {
288                 if (vid_usingmouse)
289                 {
290 #if !defined(__APPLE__) && !defined(SUNOS)
291                         if (vid_x11_dgasupported)
292                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
293 #endif
294
295                         XUngrabPointer(vidx11_display, CurrentTime);
296                         XUngrabKeyboard(vidx11_display, CurrentTime);
297
298                         // inviso cursor
299                         if (win)
300                                 XUndefineCursor(vidx11_display, win);
301
302                         cl_ignoremousemove = true;
303                         vid_usingmouse = false;
304                 }
305         }
306 }
307
308 static keynum_t buttonremap[18] =
309 {
310         K_MOUSE1,
311         K_MOUSE3,
312         K_MOUSE2,
313         K_MWHEELUP,
314         K_MWHEELDOWN,
315         K_MOUSE4,
316         K_MOUSE5,
317         K_MOUSE6,
318         K_MOUSE7,
319         K_MOUSE8,
320         K_MOUSE9,
321         K_MOUSE10,
322         K_MOUSE11,
323         K_MOUSE12,
324         K_MOUSE13,
325         K_MOUSE14,
326         K_MOUSE15,
327         K_MOUSE16,
328 };
329
330 static void HandleEvents(void)
331 {
332         XEvent event;
333         int key;
334         char ascii;
335         qboolean dowarp = false;
336
337         if (!vidx11_display)
338                 return;
339
340         while (XPending(vidx11_display))
341         {
342                 XNextEvent(vidx11_display, &event);
343
344                 switch (event.type)
345                 {
346                 case KeyPress:
347                         // key pressed
348                         key = XLateKey (&event.xkey, &ascii);
349                         Key_Event(key, ascii, true);
350                         break;
351
352                 case KeyRelease:
353                         // key released
354                         key = XLateKey (&event.xkey, &ascii);
355                         Key_Event(key, ascii, false);
356                         break;
357
358                 case MotionNotify:
359                         // mouse moved
360                         if (vid_usingmouse)
361                         {
362 #if !defined(__APPLE__) && !defined(SUNOS)
363                                 if (vid_dga.integer == 1 && vid_x11_dgasupported)
364                                 {
365                                         mouse_x += event.xmotion.x_root;
366                                         mouse_y += event.xmotion.y_root;
367                                 }
368                                 else
369 #endif
370                                 {
371
372                                         if (!event.xmotion.send_event)
373                                         {
374                                                 mouse_x += event.xmotion.x - p_mouse_x;
375                                                 mouse_y += event.xmotion.y - p_mouse_y;
376                                                 if (abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
377                                                         dowarp = true;
378                                         }
379                                         p_mouse_x = event.xmotion.x;
380                                         p_mouse_y = event.xmotion.y;
381                                 }
382                         }
383                         //else
384                         //      ui_mouseupdate(event.xmotion.x, event.xmotion.y);
385                         break;
386
387                 case ButtonPress:
388                         // mouse button pressed
389                         if (event.xbutton.button <= 18)
390                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
391                         else
392                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
393                         break;
394
395                 case ButtonRelease:
396                         // mouse button released
397                         if (event.xbutton.button <= 18)
398                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
399                         else
400                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
401                         break;
402
403                 case CreateNotify:
404                         // window created
405                         win_x = event.xcreatewindow.x;
406                         win_y = event.xcreatewindow.y;
407                         break;
408
409                 case ConfigureNotify:
410                         // window changed size/location
411                         win_x = event.xconfigure.x;
412                         win_y = event.xconfigure.y;
413                         break;
414                 case DestroyNotify:
415                         // window has been destroyed
416                         Sys_Quit(0);
417                         break;
418                 case ClientMessage:
419                         // window manager messages
420                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
421                                 Sys_Quit(0);
422                         break;
423                 case MapNotify:
424                         // window restored
425                         vid_hidden = false;
426                         VID_RestoreSystemGamma();
427                         break;
428                 case UnmapNotify:
429                         // window iconified/rolledup/whatever
430                         vid_hidden = true;
431                         VID_RestoreSystemGamma();
432                         break;
433                 case FocusIn:
434                         // window is now the input focus
435                         vid_activewindow = true;
436                         break;
437                 case FocusOut:
438                         // window is no longer the input focus
439                         vid_activewindow = false;
440                         VID_RestoreSystemGamma();
441                         break;
442                 case EnterNotify:
443                         // mouse entered window
444                         break;
445                 case LeaveNotify:
446                         // mouse left window
447                         break;
448                 }
449         }
450
451         if (dowarp)
452         {
453                 /* move the mouse to the window center again */
454                 p_mouse_x = vid.width / 2;
455                 p_mouse_y = vid.height / 2;
456                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
457         }
458 }
459
460 static void *prjobj = NULL;
461
462 static void GL_CloseLibrary(void)
463 {
464         if (prjobj)
465                 dlclose(prjobj);
466         prjobj = NULL;
467         gl_driver[0] = 0;
468         qglXGetProcAddressARB = NULL;
469         gl_extensions = "";
470         gl_platform = "";
471         gl_platformextensions = "";
472 }
473
474 static int GL_OpenLibrary(const char *name)
475 {
476         Con_Printf("Loading OpenGL driver %s\n", name);
477         GL_CloseLibrary();
478         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
479         {
480                 Con_Printf("Unable to open symbol list for %s\n", name);
481                 return false;
482         }
483         strlcpy(gl_driver, name, sizeof(gl_driver));
484         return true;
485 }
486
487 void *GL_GetProcAddress(const char *name)
488 {
489         void *p = NULL;
490         if (qglXGetProcAddressARB != NULL)
491                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
492         if (p == NULL)
493                 p = (void *) dlsym(prjobj, name);
494         return p;
495 }
496
497 void VID_Shutdown(void)
498 {
499         if (!ctx || !vidx11_display)
500                 return;
501
502         if (vidx11_display)
503         {
504                 IN_Activate(false);
505                 VID_RestoreSystemGamma();
506
507                 // FIXME: glXDestroyContext here?
508                 if (vid_isfullscreen)
509                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
510                 if (win)
511                         XDestroyWindow(vidx11_display, win);
512                 XCloseDisplay(vidx11_display);
513         }
514         vid_hidden = true;
515         vid_isfullscreen = false;
516         vidx11_display = NULL;
517         win = 0;
518         ctx = NULL;
519
520         GL_CloseLibrary();
521         Key_ClearStates ();
522 }
523
524 void signal_handler(int sig)
525 {
526         Con_Printf("Received signal %d, exiting...\n", sig);
527         VID_RestoreSystemGamma();
528         Sys_Quit(1);
529 }
530
531 void InitSig(void)
532 {
533         signal(SIGHUP, signal_handler);
534         signal(SIGINT, signal_handler);
535         signal(SIGQUIT, signal_handler);
536         signal(SIGILL, signal_handler);
537         signal(SIGTRAP, signal_handler);
538         signal(SIGIOT, signal_handler);
539         signal(SIGBUS, signal_handler);
540         signal(SIGFPE, signal_handler);
541         signal(SIGSEGV, signal_handler);
542         signal(SIGTERM, signal_handler);
543 }
544
545 void VID_Finish (qboolean allowmousegrab)
546 {
547         qboolean vid_usemouse;
548
549         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
550         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
551         {
552                 vid_usingvsync = vid_usevsync;
553                 if (qglXSwapIntervalSGI (vid_usevsync))
554                         Con_Print("glXSwapIntervalSGI didn't accept the vid_vsync change, it will take effect on next vid_restart (GLX_SGI_swap_control does not allow turning off vsync)\n");
555         }
556
557         // handle the mouse state when windowed if that's changed
558         vid_usemouse = false;
559         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
560                 vid_usemouse = true;
561         if (!vid_activewindow)
562                 vid_usemouse = false;
563         if (vid_isfullscreen)
564                 vid_usemouse = true;
565         IN_Activate(vid_usemouse);
566
567         if (r_render.integer)
568         {
569                 CHECKGLERROR
570                 if (r_speeds.integer || gl_finish.integer)
571                 {
572                         qglFinish();CHECKGLERROR
573                 }
574                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
575         }
576
577         if (vid_x11_hardwaregammasupported)
578                 VID_UpdateGamma(false, vid_x11_gammarampsize);
579 }
580
581 int VID_SetGamma(unsigned short *ramps, int rampsize)
582 {
583         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
584 }
585
586 int VID_GetGamma(unsigned short *ramps, int rampsize)
587 {
588         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
589 }
590
591 void VID_Init(void)
592 {
593 #if !defined(__APPLE__) && !defined(SUNOS)
594         Cvar_RegisterVariable (&vid_dga);
595 #endif
596         InitSig(); // trap evil signals
597 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
598         if (COM_CheckParm ("-nomouse"))
599                 mouse_avail = false;
600 }
601
602 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer)
603 {
604         *attrib++ = GLX_RGBA;
605         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
606         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
607         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
608         *attrib++ = GLX_DOUBLEBUFFER;
609         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
610         // if stencil is enabled, ask for alpha too
611         if (stencil)
612         {
613                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
614                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
615         }
616         if (stereobuffer)
617                 *attrib++ = GLX_STEREO;
618         *attrib++ = None;
619 }
620
621 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
622 {
623         int i;
624         int attrib[32];
625         XSetWindowAttributes attr;
626         unsigned long mask;
627         Window root;
628         XVisualInfo *visinfo;
629         int MajorVersion, MinorVersion;
630         const char *drivername;
631
632 #if defined(__APPLE__) && defined(__MACH__)
633         drivername = "/usr/X11R6/lib/libGL.1.dylib";
634 #else
635         drivername = "libGL.so.1";
636 #endif
637 // COMMANDLINEOPTION: Linux GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
638 // COMMANDLINEOPTION: BSD GLX: -gl_driver <drivername> selects a GL driver library, default is libGL.so.1, useful only for using fxmesa or similar, if you don't know what this is for, you don't need it
639 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
640         i = COM_CheckParm("-gl_driver");
641         if (i && i < com_argc - 1)
642                 drivername = com_argv[i + 1];
643         if (!GL_OpenLibrary(drivername))
644         {
645                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
646                 return false;
647         }
648
649         if (!(vidx11_display = XOpenDisplay(NULL)))
650         {
651                 Con_Print("Couldn't open the X display\n");
652                 return false;
653         }
654
655         vidx11_screen = DefaultScreen(vidx11_display);
656         root = RootWindow(vidx11_display, vidx11_screen);
657
658         // Get video mode list
659         MajorVersion = MinorVersion = 0;
660         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
661                 vidmode_ext = false;
662         else
663         {
664                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
665                 vidmode_ext = true;
666         }
667
668         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
669          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
670          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
671          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
672          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
673          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
674         {
675                 Con_Printf("glX functions not found in %s\n", gl_driver);
676                 return false;
677         }
678
679         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer);
680         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
681         if (!visinfo)
682         {
683                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
684                 return false;
685         }
686
687         if (vidmode_ext)
688         {
689                 int best_fit, best_dist, dist, x, y;
690
691                 // Are we going fullscreen?  If so, let's change video mode
692                 if (fullscreen)
693                 {
694                         XF86VidModeModeLine *current_vidmode;
695                         XF86VidModeModeInfo **vidmodes;
696                         int num_vidmodes;
697
698                         // This nice hack comes from the SDL source code
699                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
700                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
701
702                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
703                         best_dist = 9999999;
704                         best_fit = -1;
705
706                         for (i = 0; i < num_vidmodes; i++)
707                         {
708                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
709                                         continue;
710
711                                 x = width - vidmodes[i]->hdisplay;
712                                 y = height - vidmodes[i]->vdisplay;
713                                 dist = (x * x) + (y * y);
714                                 if (dist < best_dist)
715                                 {
716                                         best_dist = dist;
717                                         best_fit = i;
718                                 }
719                         }
720
721                         if (best_fit != -1)
722                         {
723                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
724                                 // to width/height =, so the window will take the full area of
725                                 // the mode chosen
726                                 width = vidmodes[best_fit]->hdisplay;
727                                 height = vidmodes[best_fit]->vdisplay;
728
729                                 // change to the mode
730                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
731                                 vid_isfullscreen = true;
732
733                                 // Move the viewport to top left
734                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
735                         }
736                         else
737                                 fullscreen = 0;
738
739                         free(vidmodes);
740                 }
741         }
742
743         // LordHavoc: save the visual for use in gamma ramp settings later
744         vidx11_visual = visinfo->visual;
745
746         /* window attributes */
747         attr.background_pixel = 0;
748         attr.border_pixel = 0;
749         // LordHavoc: save the colormap for later, too
750         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
751         attr.event_mask = X_MASK;
752         if (vid_isfullscreen)
753         {
754                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
755                 attr.override_redirect = True;
756                 attr.backing_store = NotUseful;
757                 attr.save_under = False;
758         }
759         else
760                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
761
762         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
763         XStoreName(vidx11_display, win, gamename);
764         XMapWindow(vidx11_display, win);
765
766         // LordHavoc: making the close button on a window do the right thing
767         // seems to involve this mess, sigh...
768         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
769         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
770
771         if (vid_isfullscreen)
772         {
773                 XMoveWindow(vidx11_display, win, 0, 0);
774                 XRaiseWindow(vidx11_display, win);
775                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
776                 XFlush(vidx11_display);
777                 // Move the viewport to top left
778                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
779         }
780
781         //XSync(vidx11_display, False);
782
783         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
784         if (!ctx)
785         {
786                 Con_Printf ("glXCreateContext failed\n");
787                 return false;
788         }
789
790         if (!qglXMakeCurrent(vidx11_display, win, ctx))
791         {
792                 Con_Printf ("glXMakeCurrent failed\n");
793                 return false;
794         }
795
796         XSync(vidx11_display, False);
797
798         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
799         {
800                 Con_Printf ("glGetString not found in %s\n", gl_driver);
801                 return false;
802         }
803
804         gl_renderer = (const char *)qglGetString(GL_RENDERER);
805         gl_vendor = (const char *)qglGetString(GL_VENDOR);
806         gl_version = (const char *)qglGetString(GL_VERSION);
807         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
808         gl_platform = "GLX";
809         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
810
811         gl_videosyncavailable = false;
812
813 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
814 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
815 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
816         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
817 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
818 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
819 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
820         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
821
822         vid_usingmouse = false;
823         vid_usingvsync = false;
824         vid_hidden = false;
825         vid_activewindow = true;
826         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
827 #if !defined(__APPLE__) && !defined(SUNOS)
828         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
829         if (!vid_x11_dgasupported)
830                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
831 #endif
832         GL_Init();
833         return true;
834 }
835
836 void Sys_SendKeyEvents(void)
837 {
838         static qboolean sound_active = true;
839
840         // enable/disable sound on focus gain/loss
841         if (!vid_activewindow && sound_active)
842         {
843                 S_BlockSound ();
844                 sound_active = false;
845         }
846         else if (vid_activewindow && !sound_active)
847         {
848                 S_UnblockSound ();
849                 sound_active = true;
850         }
851
852         HandleEvents();
853 }
854
855 void IN_Move (void)
856 {
857         if (mouse_avail)
858         {
859                 in_mouse_x = mouse_x;
860                 in_mouse_y = mouse_y;
861         }
862         mouse_x = 0;
863         mouse_y = 0;
864 }