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