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