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