Fix the event mask so that the gamma is reset when DP loses the focus or
[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 <termios.h>
21 //#include <sys/ioctl.h>
22 //#include <sys/stat.h>
23 //#include <sys/vt.h>
24 //#include <stdarg.h>
25 //#include <stdio.h>
26 #include <signal.h>
27
28 #include <dlfcn.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/Xutil.h>
32 #include <GL/glx.h>
33
34 #include <X11/keysym.h>
35 #include <X11/cursorfont.h>
36
37 #include <X11/extensions/XShm.h>
38 #include <X11/extensions/xf86dga.h>
39 #include <X11/extensions/xf86vmode.h>
40
41 #include "quakedef.h"
42
43 int cl_available = true;
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_video_sync
63 GLint (GLAPIENTRY *qglXGetVideoSyncSGI)(GLuint *count);
64 GLint (GLAPIENTRY *qglXWaitVideoSyncSGI)(GLint divisor, GLint remainder, GLuint *count);
65
66 static dllfunction_t videosyncfuncs[] =
67 {
68         {"glXGetVideoSyncSGI", (void **) &qglXGetVideoSyncSGI},
69         {"glXWaitVideoSyncSGI", (void **) &qglXWaitVideoSyncSGI},
70         {NULL, NULL}
71 };
72
73 static Display *vidx11_display = NULL;
74 static int vidx11_screen;
75 static Window win;
76 static GLXContext ctx = NULL;
77
78 Atom wm_delete_window_atom;
79
80 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
81 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
82                     PointerMotionMask | ButtonMotionMask)
83 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
84                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
85                 LeaveWindowMask)
86
87
88 static qboolean         mouse_avail = true;
89 static qboolean         mouse_active = false, usingmouse = false;
90 static float    mouse_x, mouse_y;
91 static int p_mouse_x, p_mouse_y;
92
93 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
94 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
95
96 qboolean vidmode_ext = false;
97
98 static int win_x, win_y;
99
100 static int scr_width, scr_height;
101
102 static XF86VidModeModeInfo **vidmodes;
103 static int num_vidmodes;
104 static qboolean vidmode_active = false;
105
106 static Visual *vidx11_visual;
107 static Colormap vidx11_colormap;
108
109 /*-----------------------------------------------------------------------*/
110
111 static int XLateKey(XKeyEvent *ev)
112 {
113         int key = 0;
114         char buf[64];
115         KeySym keysym;
116
117         XLookupString(ev, buf, sizeof buf, &keysym, 0);
118
119         switch(keysym)
120         {
121                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
122                 case XK_Page_Up:         key = K_PGUP; break;
123
124                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
125                 case XK_Page_Down:       key = K_PGDN; break;
126
127                 case XK_KP_Home: key = K_KP_HOME; break;
128                 case XK_Home:    key = K_HOME; break;
129
130                 case XK_KP_End:  key = K_KP_END; break;
131                 case XK_End:     key = K_END; break;
132
133                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
134                 case XK_Left:    key = K_LEFTARROW; break;
135
136                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
137                 case XK_Right:  key = K_RIGHTARROW;             break;
138
139                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
140                 case XK_Down:    key = K_DOWNARROW; break;
141
142                 case XK_KP_Up:   key = K_KP_UPARROW; break;
143                 case XK_Up:              key = K_UPARROW;        break;
144
145                 case XK_Escape: key = K_ESCAPE;         break;
146
147                 case XK_KP_Enter: key = K_KP_ENTER;     break;
148                 case XK_Return: key = K_ENTER;           break;
149
150                 case XK_Tab:            key = K_TAB;                     break;
151
152                 case XK_F1:              key = K_F1;                            break;
153
154                 case XK_F2:              key = K_F2;                            break;
155
156                 case XK_F3:              key = K_F3;                            break;
157
158                 case XK_F4:              key = K_F4;                            break;
159
160                 case XK_F5:              key = K_F5;                            break;
161
162                 case XK_F6:              key = K_F6;                            break;
163
164                 case XK_F7:              key = K_F7;                            break;
165
166                 case XK_F8:              key = K_F8;                            break;
167
168                 case XK_F9:              key = K_F9;                            break;
169
170                 case XK_F10:            key = K_F10;                     break;
171
172                 case XK_F11:            key = K_F11;                     break;
173
174                 case XK_F12:            key = K_F12;                     break;
175
176                 case XK_BackSpace: key = K_BACKSPACE; break;
177
178                 case XK_KP_Delete: key = K_KP_DEL; break;
179                 case XK_Delete: key = K_DEL; break;
180
181                 case XK_Pause:  key = K_PAUSE;           break;
182
183                 case XK_Shift_L:
184                 case XK_Shift_R:        key = K_SHIFT;          break;
185
186                 case XK_Execute:
187                 case XK_Control_L:
188                 case XK_Control_R:      key = K_CTRL;            break;
189
190                 case XK_Alt_L:
191                 case XK_Meta_L:
192                 case XK_Alt_R:
193                 case XK_Meta_R: key = K_ALT;                    break;
194
195                 case XK_KP_Begin: key = K_KP_5; break;
196
197                 case XK_Insert:key = K_INS; break;
198                 case XK_KP_Insert: key = K_KP_INS; break;
199
200                 case XK_KP_Multiply: key = '*'; break;
201                 case XK_KP_Add:  key = K_KP_PLUS; break;
202                 case XK_KP_Subtract: key = K_KP_MINUS; break;
203                 case XK_KP_Divide: key = K_KP_SLASH; break;
204
205 #if 0
206                 case 0x021: key = '1';break;/* [!] */
207                 case 0x040: key = '2';break;/* [@] */
208                 case 0x023: key = '3';break;/* [#] */
209                 case 0x024: key = '4';break;/* [$] */
210                 case 0x025: key = '5';break;/* [%] */
211                 case 0x05e: key = '6';break;/* [^] */
212                 case 0x026: key = '7';break;/* [&] */
213                 case 0x02a: key = '8';break;/* [*] */
214                 case 0x028: key = '9';;break;/* [(] */
215                 case 0x029: key = '0';break;/* [)] */
216                 case 0x05f: key = '-';break;/* [_] */
217                 case 0x02b: key = '=';break;/* [+] */
218                 case 0x07c: key = '\'';break;/* [|] */
219                 case 0x07d: key = '[';break;/* [}] */
220                 case 0x07b: key = ']';break;/* [{] */
221                 case 0x022: key = '\'';break;/* ["] */
222                 case 0x03a: key = ';';break;/* [:] */
223                 case 0x03f: key = '/';break;/* [?] */
224                 case 0x03e: key = '.';break;/* [>] */
225                 case 0x03c: key = ',';break;/* [<] */
226 #endif
227
228                 default:
229                         key = *(unsigned char*)buf;
230                         if (key >= 'A' && key <= 'Z')
231                                 key = key - 'A' + 'a';
232                         break;
233         }
234
235         return key;
236 }
237
238 static Cursor CreateNullCursor(Display *display, Window root)
239 {
240         Pixmap cursormask;
241         XGCValues xgc;
242         GC gc;
243         XColor dummycolour;
244         Cursor cursor;
245
246         cursormask = XCreatePixmap(display, root, 1, 1, 1);
247         xgc.function = GXclear;
248         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
249         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
250         dummycolour.pixel = 0;
251         dummycolour.red = 0;
252         dummycolour.flags = 04;
253         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
254         XFreePixmap(display,cursormask);
255         XFreeGC(display,gc);
256         return cursor;
257 }
258
259 static void install_grabs(void)
260 {
261         XWindowAttributes attribs_1;
262         XSetWindowAttributes attribs_2;
263
264         XGetWindowAttributes(vidx11_display, win, &attribs_1);
265         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
266         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
267
268 // inviso cursor
269         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
270
271         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
272
273         if (vid_dga.integer)
274         {
275                 int MajorVersion, MinorVersion;
276
277                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
278                 {
279                         // unable to query, probalby not supported
280                         Con_Printf( "Failed to detect XF86DGA Mouse\n" );
281                         vid_dga.integer = 0;
282                 }
283                 else
284                 {
285                         vid_dga.integer = 1;
286                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
287                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
288                 }
289         }
290         else
291                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
292
293         XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
294
295         mouse_active = true;
296         mouse_x = mouse_y = 0;
297 }
298
299 static void uninstall_grabs(void)
300 {
301         if (!vidx11_display || !win)
302                 return;
303
304         if (vid_dga.integer == 1)
305                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
306
307         XUngrabPointer(vidx11_display, CurrentTime);
308         XUngrabKeyboard(vidx11_display, CurrentTime);
309
310 // inviso cursor
311         XUndefineCursor(vidx11_display, win);
312
313         mouse_active = false;
314 }
315
316 static void HandleEvents(void)
317 {
318         XEvent event;
319         qboolean dowarp = false;
320
321         if (!vidx11_display)
322                 return;
323
324         while (XPending(vidx11_display))
325         {
326                 XNextEvent(vidx11_display, &event);
327
328                 switch (event.type)
329                 {
330                 case KeyPress:
331                         // key pressed
332                         Key_Event(XLateKey(&event.xkey), true);
333                         break;
334
335                 case KeyRelease:
336                         // key released
337                         Key_Event(XLateKey(&event.xkey), false);
338                         break;
339
340                 case MotionNotify:
341                         // mouse moved
342                         if (usingmouse)
343                         {
344                                 if (vid_dga.integer == 1)
345                                 {
346                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
347                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
348                                 }
349                                 else
350                                 {
351
352                                         if (!event.xmotion.send_event)
353                                         {
354                                                 mouse_x += event.xmotion.x - p_mouse_x;
355                                                 mouse_y += event.xmotion.y - p_mouse_y;
356                                                 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
357                                                         dowarp = true;
358                                         }
359                                         p_mouse_x = event.xmotion.x;
360                                         p_mouse_y = event.xmotion.y;
361                                 }
362                         }
363                         else
364                                 ui_mouseupdate(event.xmotion.x, event.xmotion.y);
365                         break;
366
367                 case ButtonPress:
368                         // mouse button pressed
369                         switch(event.xbutton.button)
370                         {
371                         case 1:
372                                 Key_Event(K_MOUSE1, true);
373                                 break;
374                         case 2:
375                                 Key_Event(K_MOUSE3, true);
376                                 break;
377                         case 3:
378                                 Key_Event(K_MOUSE2, true);
379                                 break;
380                         case 4:
381                                 Key_Event(K_MWHEELUP, true);
382                                 break;
383                         case 5:
384                                 Key_Event(K_MWHEELDOWN, true);
385                                 break;
386                         case 6:
387                                 Key_Event(K_MOUSE4, true);
388                                 break;
389                         case 7:
390                                 Key_Event(K_MOUSE5, true);
391                                 break;
392                         case 8:
393                                 Key_Event(K_MOUSE6, true);
394                                 break;
395                         case 9:
396                                 Key_Event(K_MOUSE7, true);
397                                 break;
398                         case 10:
399                                 Key_Event(K_MOUSE8, true);
400                                 break;
401                         case 11:
402                                 Key_Event(K_MOUSE9, true);
403                                 break;
404                         case 12:
405                                 Key_Event(K_MOUSE10, true);
406                                 break;
407                         default:
408                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-12 expected\n", event.xbutton.button);
409                                 break;
410                         }
411                         break;
412
413                 case ButtonRelease:
414                         // mouse button released
415                         switch(event.xbutton.button)
416                         {
417                         case 1:
418                                 Key_Event(K_MOUSE1, false);
419                                 break;
420                         case 2:
421                                 Key_Event(K_MOUSE3, false);
422                                 break;
423                         case 3:
424                                 Key_Event(K_MOUSE2, false);
425                                 break;
426                         case 4:
427                                 Key_Event(K_MWHEELUP, false);
428                                 break;
429                         case 5:
430                                 Key_Event(K_MWHEELDOWN, false);
431                                 break;
432                         case 6:
433                                 Key_Event(K_MOUSE4, false);
434                                 break;
435                         case 7:
436                                 Key_Event(K_MOUSE5, false);
437                                 break;
438                         case 8:
439                                 Key_Event(K_MOUSE6, false);
440                                 break;
441                         case 9:
442                                 Key_Event(K_MOUSE7, false);
443                                 break;
444                         case 10:
445                                 Key_Event(K_MOUSE8, false);
446                                 break;
447                         case 11:
448                                 Key_Event(K_MOUSE9, false);
449                                 break;
450                         case 12:
451                                 Key_Event(K_MOUSE10, false);
452                                 break;
453                         default:
454                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-12 expected\n", event.xbutton.button);
455                                 break;
456                         }
457                         break;
458
459                 case CreateNotify:
460                         // window created
461                         win_x = event.xcreatewindow.x;
462                         win_y = event.xcreatewindow.y;
463                         break;
464
465                 case ConfigureNotify:
466                         // window changed size/location
467                         win_x = event.xconfigure.x;
468                         win_y = event.xconfigure.y;
469                         break;
470                 case DestroyNotify:
471                         // window has been destroyed
472                         Sys_Quit();
473                         break;
474                 case ClientMessage:
475                         // window manager messages
476                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
477                                 Sys_Quit();
478                         break;
479                 case MapNotify:
480                         // window restored
481                         vid_hidden = false;
482                         vid_allowhwgamma = true;
483                         break;
484                 case UnmapNotify:
485                         // window iconified/rolledup/whatever
486                         vid_hidden = true;
487                         vid_allowhwgamma = false;
488                         VID_RestoreSystemGamma();
489                         break;
490                 case FocusIn:
491                         // window is now the input focus
492                         vid_allowhwgamma = true;
493                         break;
494                 case FocusOut:
495                         // window is no longer the input focus
496                         vid_allowhwgamma = false;
497                         VID_RestoreSystemGamma();
498                         break;
499                 case EnterNotify:
500                         // mouse entered window
501                         vid_allowhwgamma = true;
502                         break;
503                 case LeaveNotify:
504                         // mouse left window
505                         vid_allowhwgamma = false;
506                         VID_RestoreSystemGamma();
507                         break;
508                 }
509         }
510
511         if (dowarp)
512         {
513                 /* move the mouse to the window center again */
514                 p_mouse_x = scr_width / 2;
515                 p_mouse_y = scr_height / 2;
516                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
517         }
518
519 }
520
521 static void IN_DeactivateMouse( void )
522 {
523         if (!mouse_avail || !vidx11_display || !win)
524                 return;
525
526         if (mouse_active)
527         {
528                 uninstall_grabs();
529                 mouse_active = false;
530         }
531 }
532
533 static void IN_ActivateMouse( void )
534 {
535         if (!mouse_avail || !vidx11_display || !win)
536                 return;
537
538         if (!mouse_active)
539         {
540                 mouse_x = mouse_y = 0; // don't spazz
541                 install_grabs();
542                 mouse_active = true;
543         }
544 }
545
546 void VID_Shutdown(void)
547 {
548         if (!ctx || !vidx11_display)
549                 return;
550
551         vid_hidden = true;
552         usingmouse = false;
553         if (vidx11_display)
554         {
555                 VID_RestoreSystemGamma();
556                 uninstall_grabs();
557
558                 // FIXME: glXDestroyContext here?
559                 if (vidmode_active)
560                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[0]);
561                 if (win)
562                         XDestroyWindow(vidx11_display, win);
563                 XCloseDisplay(vidx11_display);
564         }
565         vidmode_active = false;
566         vidx11_display = NULL;
567         win = 0;
568         ctx = NULL;
569
570         GL_CloseLibrary();
571 }
572
573 void signal_handler(int sig)
574 {
575         printf("Received signal %d, exiting...\n", sig);
576         VID_RestoreSystemGamma();
577         Sys_Quit();
578         exit(0);
579 }
580
581 void InitSig(void)
582 {
583         signal(SIGHUP, signal_handler);
584         signal(SIGINT, signal_handler);
585         signal(SIGQUIT, signal_handler);
586         signal(SIGILL, signal_handler);
587         signal(SIGTRAP, signal_handler);
588         signal(SIGIOT, signal_handler);
589         signal(SIGBUS, signal_handler);
590         signal(SIGFPE, signal_handler);
591         signal(SIGSEGV, signal_handler);
592         signal(SIGTERM, signal_handler);
593 }
594
595 /*
596 =================
597 VID_GetWindowSize
598 =================
599 */
600 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
601 {
602         *x = *y = 0;
603         *width = scr_width;
604         *height = scr_height;
605 }
606
607 void VID_Finish (void)
608 {
609         int usemouse;
610         if (r_render.integer)
611         {
612                 qglFinish();
613                 qglXSwapBuffers(vidx11_display, win);
614         }
615
616 // handle the mouse state when windowed if that's changed
617         usemouse = false;
618         if (vid_mouse.integer && !key_consoleactive)
619                 usemouse = true;
620         if (vidmode_active)
621                 usemouse = true;
622         if (usemouse)
623         {
624                 if (!usingmouse)
625                 {
626                         usingmouse = true;
627                         IN_ActivateMouse ();
628                 }
629         }
630         else
631         {
632                 if (usingmouse)
633                 {
634                         usingmouse = false;
635                         IN_DeactivateMouse ();
636                 }
637         }
638 }
639
640 int VID_SetGamma(unsigned short *ramps)
641 {
642         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
643 }
644
645 int VID_GetGamma(unsigned short *ramps)
646 {
647         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
648 }
649
650 void VID_Init(void)
651 {
652         Cvar_RegisterVariable (&vid_dga);
653         Cvar_RegisterVariable (&vid_dga_mouseaccel);
654         InitSig(); // trap evil signals
655         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
656                 mouse_avail = false;
657 }
658
659 void VID_BuildGLXAttrib(int *attrib, int stencil)
660 {
661         *attrib++ = GLX_RGBA;
662         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
663         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
664         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
665         *attrib++ = GLX_DOUBLEBUFFER;
666         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
667         // if stencil is enabled, ask for alpha too
668         if (stencil)
669         {
670                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
671                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
672         }
673         *attrib++ = None;
674 }
675
676 int VID_InitMode(int fullscreen, int width, int height, int bpp, int stencil)
677 {
678         int i;
679         int attrib[32];
680         XSetWindowAttributes attr;
681         unsigned long mask;
682         Window root;
683         XVisualInfo *visinfo;
684         int MajorVersion, MinorVersion;
685         const char *drivername;
686
687         drivername = "libGL.so.1";
688         i = COM_CheckParm("-gl_driver");
689         if (i && i < com_argc - 1)
690                 drivername = com_argv[i + 1];
691         if (!GL_OpenLibrary(drivername))
692         {
693                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
694                 return false;
695         }
696
697         if (!(vidx11_display = XOpenDisplay(NULL)))
698         {
699                 Con_Printf("Couldn't open the X display\n");
700                 return false;
701         }
702
703         vidx11_screen = DefaultScreen(vidx11_display);
704         root = RootWindow(vidx11_display, vidx11_screen);
705
706         // Get video mode list
707         MajorVersion = MinorVersion = 0;
708         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
709                 vidmode_ext = false;
710         else
711         {
712                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
713                 vidmode_ext = true;
714         }
715
716         if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
717          || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
718          || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
719          || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
720          || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
721         {
722                 Con_Printf("glX functions not found in %s\n", gl_driver);
723                 return false;
724         }
725
726         VID_BuildGLXAttrib(attrib, stencil);
727         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
728         if (!visinfo)
729         {
730                 Con_Printf("Couldn't get an RGB, Double-buffered, Depth visual\n");
731                 return false;
732         }
733
734         if (vidmode_ext)
735         {
736                 int best_fit, best_dist, dist, x, y;
737
738                 // Are we going fullscreen?  If so, let's change video mode
739                 if (fullscreen)
740                 {
741                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
742                         best_dist = 9999999;
743                         best_fit = -1;
744
745                         for (i = 0; i < num_vidmodes; i++)
746                         {
747                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
748                                         continue;
749
750                                 x = width - vidmodes[i]->hdisplay;
751                                 y = height - vidmodes[i]->vdisplay;
752                                 dist = (x * x) + (y * y);
753                                 if (dist < best_dist)
754                                 {
755                                         best_dist = dist;
756                                         best_fit = i;
757                                 }
758                         }
759
760                         if (best_fit != -1)
761                         {
762                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
763                                 // to width/height =, so the window will take the full area of
764                                 // the mode chosen
765                                 width = vidmodes[best_fit]->hdisplay;
766                                 height = vidmodes[best_fit]->vdisplay;
767
768                                 // change to the mode
769                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
770                                 vidmode_active = true;
771
772                                 // Move the viewport to top left
773                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
774                         }
775                         else
776                                 fullscreen = 0;
777                 }
778         }
779
780         // LordHavoc: save the visual for use in gamma ramp settings later
781         vidx11_visual = visinfo->visual;
782
783         /* window attributes */
784         attr.background_pixel = 0;
785         attr.border_pixel = 0;
786         // LordHavoc: save the colormap for later, too
787         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
788         attr.event_mask = X_MASK;
789         if (vidmode_active)
790         {
791                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
792                 attr.override_redirect = True;
793                 attr.backing_store = NotUseful;
794                 attr.save_under = False;
795         }
796         else
797                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
798
799         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
800         XStoreName(vidx11_display, win, gamename);
801         XMapWindow(vidx11_display, win);
802
803         // LordHavoc: making the close button on a window do the right thing
804         // seems to involve this mess, sigh...
805         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
806         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
807
808         if (vidmode_active)
809         {
810                 XMoveWindow(vidx11_display, win, 0, 0);
811                 XRaiseWindow(vidx11_display, win);
812                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
813                 XFlush(vidx11_display);
814                 // Move the viewport to top left
815                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
816         }
817
818         //XSync(vidx11_display, False);
819
820         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
821         if (!ctx)
822                 Sys_Error ("glXCreateContext failed\n");
823
824         if (!qglXMakeCurrent(vidx11_display, win, ctx))
825                 Sys_Error ("glXMakeCurrent failed\n");
826
827         XSync(vidx11_display, False);
828
829         scr_width = width;
830         scr_height = height;
831
832         if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
833                 Sys_Error("glGetString not found in %s", gl_driver);
834
835         gl_renderer = qglGetString(GL_RENDERER);
836         gl_vendor = qglGetString(GL_VENDOR);
837         gl_version = qglGetString(GL_VERSION);
838         gl_extensions = qglGetString(GL_EXTENSIONS);
839         gl_platform = "GLX";
840         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
841
842         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
843         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_video_sync", videosyncfuncs, "-novideosync", false);
844
845         usingmouse = false;
846         vid_hidden = false;
847         vid_allowhwgamma = true;
848         GL_Init();
849         return true;
850 }
851
852 void Sys_SendKeyEvents(void)
853 {
854         HandleEvents();
855 }
856
857 /*
858 ===========
859 IN_Commands
860 ===========
861 */
862 void IN_Commands (void)
863 {
864 }
865
866 void IN_Move (usercmd_t *cmd)
867 {
868         if (mouse_avail)
869                 IN_Mouse(cmd, mouse_x, mouse_y);
870         mouse_x = 0;
871         mouse_y = 0;
872 }
873
874 static void *prjobj = NULL;
875
876 int GL_OpenLibrary(const char *name)
877 {
878         Con_Printf("Loading OpenGL driver %s\n", name);
879         GL_CloseLibrary();
880         if (!(prjobj = dlopen(name, RTLD_LAZY)))
881         {
882                 Con_Printf("Unable to open symbol list for %s\n", name);
883                 return false;
884         }
885         strcpy(gl_driver, name);
886         return true;
887 }
888
889 void GL_CloseLibrary(void)
890 {
891         if (prjobj)
892                 dlclose(prjobj);
893         prjobj = NULL;
894         gl_driver[0] = 0;
895         qglXGetProcAddressARB = NULL;
896         gl_extensions = "";
897         gl_platform = "";
898         gl_platformextensions = "";
899 }
900
901 void *GL_GetProcAddress(const char *name)
902 {
903         void *p = NULL;
904         if (qglXGetProcAddressARB != NULL)
905                 p = (void *) qglXGetProcAddressARB(name);
906         if (p == NULL)
907                 p = (void *) dlsym(prjobj, name);
908         return p;
909 }
910