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