4050a1c8f531ca5b90cf4bf2d05ecb2371ef628d
[xonotic/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 <X11/XKBlib.h> // TODO possibly ifdef this out on non-supporting systems... Solaris (as always)?
27 #include <GL/glx.h>
28
29 #include "quakedef.h"
30
31 #include <X11/keysym.h>
32 #include <X11/cursorfont.h>
33 #include <X11/xpm.h>
34
35 #include <X11/extensions/XShm.h>
36 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
37 #include <X11/extensions/xf86dga.h>
38 #endif
39 #include <X11/extensions/xf86vmode.h>
40
41 #include "nexuiz.xpm"
42 #include "darkplaces.xpm"
43
44 // Tell startup code that we have a client
45 int cl_available = true;
46
47 // note: if we used the XRandR extension we could support refresh rates
48 qboolean vid_supportrefreshrate = false;
49
50 //GLX prototypes
51 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
52 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
53 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
54 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
55 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
56 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
57
58 //GLX_ARB_get_proc_address
59 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
60
61 static dllfunction_t getprocaddressfuncs[] =
62 {
63         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
64         {NULL, NULL}
65 };
66
67 //GLX_SGI_swap_control
68 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
69
70 static dllfunction_t swapcontrolfuncs[] =
71 {
72         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
73         {NULL, NULL}
74 };
75
76 static Display *vidx11_display = NULL;
77 static int vidx11_screen;
78 static Window win;
79 static GLXContext ctx = NULL;
80
81 Atom wm_delete_window_atom;
82
83 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
84 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
85                     PointerMotionMask | ButtonMotionMask)
86 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
87                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
88                 LeaveWindowMask)
89
90
91 static qboolean mouse_avail = true;
92 static qboolean vid_usingmousegrab = false;
93 static qboolean vid_usingmouse = false;
94 static qboolean vid_usinghidecursor = false;
95 static qboolean vid_usingvsync = false;
96 static qboolean vid_usevsync = false;
97 static qboolean vid_x11_hardwaregammasupported = false;
98 static qboolean vid_x11_dgasupported = false;
99 static int vid_x11_gammarampsize = 0;
100
101 #if !defined(__APPLE__) && !defined(SUNOS)
102 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "1", "make use of DGA mouse input"};
103 static qboolean vid_usingdgamouse = false;
104 #endif
105
106 qboolean vidmode_ext = false;
107
108 static int win_x, win_y;
109
110 static XF86VidModeModeInfo init_vidmode;
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_ISO_Level3_Shift:
202                 case XK_Alt_R:
203                 case XK_Meta_R: key = K_ALT;                    break;
204
205                 case XK_KP_Begin: key = K_KP_5; break;
206
207                 case XK_Insert:key = K_INS; break;
208                 case XK_KP_Insert: key = K_KP_INS; break;
209
210                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
211                 case XK_KP_Add:  key = K_KP_PLUS; break;
212                 case XK_KP_Subtract: key = K_KP_MINUS; break;
213                 case XK_KP_Divide: key = K_KP_SLASH; break;
214
215                 case XK_section:        key = '~'; break;
216
217                 default:
218                         if (keysym < 32)
219                                 break;
220
221                         if (keysym >= 'A' && keysym <= 'Z')
222                                 key = keysym - 'A' + 'a';
223                         else
224                                 key = keysym;
225
226                         break;
227         }
228
229         return key;
230 }
231
232 static Cursor CreateNullCursor(Display *display, Window root)
233 {
234         Pixmap cursormask;
235         XGCValues xgc;
236         GC gc;
237         XColor dummycolour;
238         Cursor cursor;
239
240         cursormask = XCreatePixmap(display, root, 1, 1, 1);
241         xgc.function = GXclear;
242         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
243         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
244         dummycolour.pixel = 0;
245         dummycolour.red = 0;
246         dummycolour.flags = 04;
247         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
248         XFreePixmap(display,cursormask);
249         XFreeGC(display,gc);
250         return cursor;
251 }
252
253 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
254 {
255         qboolean usedgamouse;
256
257         if (!vidx11_display || !win)
258                 return;
259
260         if (relative)
261                 fullscreengrab = true;
262
263         if (!mouse_avail)
264                 fullscreengrab = relative = hidecursor = false;
265
266         usedgamouse = relative && vid_dgamouse.integer;
267 #if !defined(__APPLE__) && !defined(SUNOS)
268         if (!vid_x11_dgasupported)
269                 usedgamouse = false;
270         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
271                 VID_SetMouse(false, false, false); // ungrab first!
272 #endif
273
274         if (vid_usingmousegrab != fullscreengrab)
275         {
276                 vid_usingmousegrab = fullscreengrab;
277                 cl_ignoremousemoves = 2;
278                 if (fullscreengrab)
279                 {
280                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
281                         if (vid_grabkeyboard.integer || vid_isfullscreen)
282                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
283                 }
284                 else
285                 {
286                         XUngrabPointer(vidx11_display, CurrentTime);
287                         XUngrabKeyboard(vidx11_display, CurrentTime);
288                 }
289         }
290
291         if (relative)
292         {
293                 if (!vid_usingmouse)
294                 {
295                         XWindowAttributes attribs_1;
296                         XSetWindowAttributes attribs_2;
297
298                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
299                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
300                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
301
302 #if !defined(__APPLE__) && !defined(SUNOS)
303                         vid_usingdgamouse = usedgamouse;
304                         if (usedgamouse)
305                         {
306                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
307                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
308                         }
309                         else
310 #endif
311                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
312
313                         cl_ignoremousemoves = 2;
314                         vid_usingmouse = true;
315                 }
316         }
317         else
318         {
319                 if (vid_usingmouse)
320                 {
321 #if !defined(__APPLE__) && !defined(SUNOS)
322                         if (vid_usingdgamouse)
323                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
324                         vid_usingdgamouse = false;
325 #endif
326                         cl_ignoremousemoves = 2;
327                         vid_usingmouse = false;
328                 }
329         }
330
331         if (vid_usinghidecursor != hidecursor)
332         {
333                 vid_usinghidecursor = hidecursor;
334                 if (hidecursor)
335                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
336                 else
337                         XUndefineCursor(vidx11_display, win);
338         }
339 }
340
341 static keynum_t buttonremap[18] =
342 {
343         K_MOUSE1,
344         K_MOUSE3,
345         K_MOUSE2,
346         K_MWHEELUP,
347         K_MWHEELDOWN,
348         K_MOUSE4,
349         K_MOUSE5,
350         K_MOUSE6,
351         K_MOUSE7,
352         K_MOUSE8,
353         K_MOUSE9,
354         K_MOUSE10,
355         K_MOUSE11,
356         K_MOUSE12,
357         K_MOUSE13,
358         K_MOUSE14,
359         K_MOUSE15,
360         K_MOUSE16,
361 };
362
363 static void HandleEvents(void)
364 {
365         XEvent event;
366         int key;
367         char ascii;
368         qboolean dowarp = false;
369
370         if (!vidx11_display)
371                 return;
372
373         while (XPending(vidx11_display))
374         {
375                 XNextEvent(vidx11_display, &event);
376
377                 switch (event.type)
378                 {
379                 case KeyPress:
380                         // key pressed
381                         key = XLateKey (&event.xkey, &ascii);
382                         Key_Event(key, ascii, true);
383                         break;
384
385                 case KeyRelease:
386                         // key released
387                         key = XLateKey (&event.xkey, &ascii);
388                         Key_Event(key, ascii, false);
389                         break;
390
391                 case MotionNotify:
392                         // mouse moved
393                         if (vid_usingmouse)
394                         {
395 #if !defined(__APPLE__) && !defined(SUNOS)
396                                 if (vid_usingdgamouse)
397                                 {
398                                         in_mouse_x += event.xmotion.x_root;
399                                         in_mouse_y += event.xmotion.y_root;
400                                 }
401                                 else
402 #endif
403                                 {
404                                         if (!event.xmotion.send_event)
405                                         {
406                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
407                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
408                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
409                                                 if (abs(vid.width/2 - event.xmotion.x) > vid.width / 4 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4)
410                                                         dowarp = true;
411                                         }
412                                 }
413                         }
414                         in_windowmouse_x = event.xmotion.x;
415                         in_windowmouse_y = event.xmotion.y;
416                         break;
417
418                 case ButtonPress:
419                         // mouse button pressed
420                         if (event.xbutton.button <= 18)
421                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
422                         else
423                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
424                         break;
425
426                 case ButtonRelease:
427                         // mouse button released
428                         if (event.xbutton.button <= 18)
429                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
430                         else
431                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
432                         break;
433
434                 case CreateNotify:
435                         // window created
436                         win_x = event.xcreatewindow.x;
437                         win_y = event.xcreatewindow.y;
438                         break;
439
440                 case ConfigureNotify:
441                         // window changed size/location
442                         win_x = event.xconfigure.x;
443                         win_y = event.xconfigure.y;
444                         if(vid_resizable.integer < 2)
445                         {
446                                 vid.width = event.xconfigure.width;
447                                 vid.height = event.xconfigure.height;
448                         }
449                         break;
450                 case DestroyNotify:
451                         // window has been destroyed
452                         Sys_Quit(0);
453                         break;
454                 case ClientMessage:
455                         // window manager messages
456                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
457                                 Sys_Quit(0);
458                         break;
459                 case MapNotify:
460                         if (vid.fullscreen)
461                                 break;
462                         // window restored
463                         vid_hidden = false;
464                         VID_RestoreSystemGamma();
465                         break;
466                 case UnmapNotify:
467                         if (vid.fullscreen)
468                                 break;
469                         // window iconified/rolledup/whatever
470                         vid_hidden = true;
471                         VID_RestoreSystemGamma();
472                         break;
473                 case FocusIn:
474                         if (vid.fullscreen)
475                                 break;
476                         // window is now the input focus
477                         vid_activewindow = true;
478                         break;
479                 case FocusOut:
480                         if (vid.fullscreen)
481                                 break;
482                         // window is no longer the input focus
483                         vid_activewindow = false;
484                         VID_RestoreSystemGamma();
485                         break;
486                 case EnterNotify:
487                         // mouse entered window
488                         break;
489                 case LeaveNotify:
490                         // mouse left window
491                         break;
492                 }
493         }
494
495         if (dowarp)
496         {
497                 /* move the mouse to the window center again */
498                 // we'll catch the warp motion by its send_event flag, updating the
499                 // stored mouse position without adding any delta motion
500                 XEvent event;
501                 event.type = MotionNotify;
502                 event.xmotion.display = vidx11_display;
503                 event.xmotion.window = win;
504                 event.xmotion.x = vid.width / 2;
505                 event.xmotion.y = vid.height / 2;
506                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
507                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
508         }
509 }
510
511 static void *prjobj = NULL;
512
513 static void GL_CloseLibrary(void)
514 {
515         if (prjobj)
516                 dlclose(prjobj);
517         prjobj = NULL;
518         gl_driver[0] = 0;
519         qglXGetProcAddressARB = NULL;
520         gl_extensions = "";
521         gl_platform = "";
522         gl_platformextensions = "";
523 }
524
525 static int GL_OpenLibrary(const char *name)
526 {
527         Con_Printf("Loading OpenGL driver %s\n", name);
528         GL_CloseLibrary();
529         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
530         {
531                 Con_Printf("Unable to open symbol list for %s\n", name);
532                 return false;
533         }
534         strlcpy(gl_driver, name, sizeof(gl_driver));
535         return true;
536 }
537
538 void *GL_GetProcAddress(const char *name)
539 {
540         void *p = NULL;
541         if (qglXGetProcAddressARB != NULL)
542                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
543         if (p == NULL)
544                 p = (void *) dlsym(prjobj, name);
545         return p;
546 }
547
548 void VID_Shutdown(void)
549 {
550         if (!ctx || !vidx11_display)
551                 return;
552
553         VID_SetMouse(false, false, false);
554         VID_RestoreSystemGamma();
555
556         // FIXME: glXDestroyContext here?
557         if (vid_isfullscreen)
558                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
559         if (win)
560                 XDestroyWindow(vidx11_display, win);
561         XCloseDisplay(vidx11_display);
562
563         vid_hidden = true;
564         vid_isfullscreen = false;
565         vidx11_display = NULL;
566         win = 0;
567         ctx = NULL;
568
569         GL_CloseLibrary();
570         Key_ClearStates ();
571 }
572
573 void signal_handler(int sig)
574 {
575         Con_Printf("Received signal %d, exiting...\n", sig);
576         VID_RestoreSystemGamma();
577         Sys_Quit(1);
578 }
579
580 void InitSig(void)
581 {
582         signal(SIGHUP, signal_handler);
583         signal(SIGINT, signal_handler);
584         signal(SIGQUIT, signal_handler);
585         signal(SIGILL, signal_handler);
586         signal(SIGTRAP, signal_handler);
587         signal(SIGIOT, signal_handler);
588         signal(SIGBUS, signal_handler);
589         signal(SIGFPE, signal_handler);
590         signal(SIGSEGV, signal_handler);
591         signal(SIGTERM, signal_handler);
592 }
593
594 void VID_Finish (void)
595 {
596         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
597         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
598         {
599                 vid_usingvsync = vid_usevsync;
600                 if (qglXSwapIntervalSGI (vid_usevsync))
601                         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");
602         }
603
604         if (r_render.integer)
605         {
606                 CHECKGLERROR
607                 if (r_speeds.integer || gl_finish.integer)
608                 {
609                         qglFinish();CHECKGLERROR
610                 }
611                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
612         }
613
614         if (vid_x11_hardwaregammasupported)
615                 VID_UpdateGamma(false, vid_x11_gammarampsize);
616 }
617
618 int VID_SetGamma(unsigned short *ramps, int rampsize)
619 {
620         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
621 }
622
623 int VID_GetGamma(unsigned short *ramps, int rampsize)
624 {
625         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
626 }
627
628 void VID_Init(void)
629 {
630 #if !defined(__APPLE__) && !defined(SUNOS)
631         Cvar_RegisterVariable (&vid_dgamouse);
632 #endif
633         InitSig(); // trap evil signals
634 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
635         if (COM_CheckParm ("-nomouse"))
636                 mouse_avail = false;
637 }
638
639 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
640 {
641         *attrib++ = GLX_RGBA;
642         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
643         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
644         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
645         *attrib++ = GLX_DOUBLEBUFFER;
646         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
647         // if stencil is enabled, ask for alpha too
648         if (stencil)
649         {
650                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
651                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
652         }
653         if (stereobuffer)
654                 *attrib++ = GLX_STEREO;
655         if (samples > 1)
656         {
657                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
658                 *attrib++ = 1;
659                 *attrib++ = GLX_SAMPLES_ARB;
660                 *attrib++ = samples;
661         }
662         *attrib++ = None;
663 }
664
665 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
666 {
667         int i;
668         int attrib[32];
669         XSetWindowAttributes attr;
670         XClassHint *clshints;
671         XWMHints *wmhints;
672         XSizeHints *szhints;
673         unsigned long mask;
674         Window root;
675         XVisualInfo *visinfo;
676         int MajorVersion, MinorVersion;
677         const char *drivername;
678
679 #if defined(__APPLE__) && defined(__MACH__)
680         drivername = "/usr/X11R6/lib/libGL.1.dylib";
681 #else
682         drivername = "libGL.so.1";
683 #endif
684 // 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
685 // 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
686 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
687         i = COM_CheckParm("-gl_driver");
688         if (i && i < com_argc - 1)
689                 drivername = com_argv[i + 1];
690         if (!GL_OpenLibrary(drivername))
691         {
692                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
693                 return false;
694         }
695
696         if (!(vidx11_display = XOpenDisplay(NULL)))
697         {
698                 Con_Print("Couldn't open the X display\n");
699                 return false;
700         }
701
702         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
703         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
704
705         vidx11_screen = DefaultScreen(vidx11_display);
706         root = RootWindow(vidx11_display, vidx11_screen);
707
708         // Get video mode list
709         MajorVersion = MinorVersion = 0;
710         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
711                 vidmode_ext = false;
712         else
713         {
714                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
715                 vidmode_ext = true;
716         }
717
718         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
719          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
720          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
721          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
722          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
723          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
724         {
725                 Con_Printf("glX functions not found in %s\n", gl_driver);
726                 return false;
727         }
728
729         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, samples);
730         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
731         if (!visinfo && (samples == 1))
732         {
733                 /* Some Mesa drivers reject sample buffers with 1 sample, so try
734                  * entirely without one */
735                 VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, 0);
736                 visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
737         }
738         if (!visinfo)
739         {
740                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
741                 return false;
742         }
743
744         if (vidmode_ext)
745         {
746                 int best_fit, best_dist, dist, x, y;
747
748                 // Are we going fullscreen?  If so, let's change video mode
749                 if (fullscreen)
750                 {
751                         XF86VidModeModeLine *current_vidmode;
752                         XF86VidModeModeInfo **vidmodes;
753                         int num_vidmodes;
754
755                         // This nice hack comes from the SDL source code
756                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
757                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
758
759                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
760                         best_dist = 9999999;
761                         best_fit = -1;
762
763                         for (i = 0; i < num_vidmodes; i++)
764                         {
765                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
766                                         continue;
767
768                                 x = width - vidmodes[i]->hdisplay;
769                                 y = height - vidmodes[i]->vdisplay;
770                                 dist = (x * x) + (y * y);
771                                 if (dist < best_dist)
772                                 {
773                                         best_dist = dist;
774                                         best_fit = i;
775                                 }
776                         }
777
778                         if (best_fit != -1)
779                         {
780                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
781                                 // to width/height =, so the window will take the full area of
782                                 // the mode chosen
783                                 width = vidmodes[best_fit]->hdisplay;
784                                 height = vidmodes[best_fit]->vdisplay;
785
786                                 // change to the mode
787                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
788                                 vid_isfullscreen = true;
789
790                                 // Move the viewport to top left
791                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
792                         }
793                         else
794                                 fullscreen = 0;
795
796                         free(vidmodes);
797                 }
798         }
799
800         // LordHavoc: save the visual for use in gamma ramp settings later
801         vidx11_visual = visinfo->visual;
802
803         /* window attributes */
804         attr.background_pixel = 0;
805         attr.border_pixel = 0;
806         // LordHavoc: save the colormap for later, too
807         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
808         attr.event_mask = X_MASK;
809         if (vid_isfullscreen)
810         {
811                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
812                 attr.override_redirect = True;
813                 attr.backing_store = NotUseful;
814                 attr.save_under = False;
815         }
816         else
817                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
818
819         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
820
821         wmhints = XAllocWMHints();
822         if(XpmCreatePixmapFromData(vidx11_display, win,
823                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
824                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
825                 wmhints->flags |= IconPixmapHint | IconMaskHint;
826
827         clshints = XAllocClassHint();
828         clshints->res_name = strdup(gamename);
829         clshints->res_class = strdup("DarkPlaces");
830
831         szhints = XAllocSizeHints();
832         if(vid_resizable.integer == 0)
833         {
834                 szhints->min_width = szhints->max_width = width;
835                 szhints->min_height = szhints->max_height = height;
836                 szhints->flags |= PMinSize | PMaxSize;
837         }
838
839         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
840         XFree(clshints);
841         XFree(wmhints);
842         XFree(szhints);
843         //XStoreName(vidx11_display, win, gamename);
844         XMapWindow(vidx11_display, win);
845
846         // LordHavoc: making the close button on a window do the right thing
847         // seems to involve this mess, sigh...
848         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
849         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
850
851         if (vid_isfullscreen)
852         {
853                 XMoveWindow(vidx11_display, win, 0, 0);
854                 XRaiseWindow(vidx11_display, win);
855                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
856                 XFlush(vidx11_display);
857                 // Move the viewport to top left
858                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
859         }
860
861         //XSync(vidx11_display, False);
862
863         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
864         if (!ctx)
865         {
866                 Con_Printf ("glXCreateContext failed\n");
867                 return false;
868         }
869
870         if (!qglXMakeCurrent(vidx11_display, win, ctx))
871         {
872                 Con_Printf ("glXMakeCurrent failed\n");
873                 return false;
874         }
875
876         XSync(vidx11_display, False);
877
878         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
879         {
880                 Con_Printf ("glGetString not found in %s\n", gl_driver);
881                 return false;
882         }
883
884         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
885         gl_platform = "GLX";
886         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
887
888         gl_videosyncavailable = false;
889
890 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
891 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
892 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
893         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
894 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
895 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
896 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
897         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
898
899         vid_usingmousegrab = false;
900         vid_usingmouse = false;
901         vid_usinghidecursor = false;
902         vid_usingvsync = false;
903         vid_hidden = false;
904         vid_activewindow = true;
905         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
906 #if !defined(__APPLE__) && !defined(SUNOS)
907         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
908         if (!vid_x11_dgasupported)
909                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
910 #endif
911         GL_Init();
912         return true;
913 }
914
915 void Sys_SendKeyEvents(void)
916 {
917         static qboolean sound_active = true;
918
919         // enable/disable sound on focus gain/loss
920         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
921         {
922                 if (!sound_active)
923                 {
924                         S_UnblockSound ();
925                         sound_active = true;
926                 }
927         }
928         else
929         {
930                 if (sound_active)
931                 {
932                         S_BlockSound ();
933                         sound_active = false;
934                 }
935         }
936
937         HandleEvents();
938 }
939
940 void IN_Move (void)
941 {
942 }