more clean up of IN_Activate, added cl_ignoremousemove to merge some code
[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__)
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 //GLX prototypes
49 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
50 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
51 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
52 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
53 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
54 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
55
56 //GLX_ARB_get_proc_address
57 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
58
59 static dllfunction_t getprocaddressfuncs[] =
60 {
61         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
62         {NULL, NULL}
63 };
64
65 //GLX_SGI_swap_control
66 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
67
68 static dllfunction_t swapcontrolfuncs[] =
69 {
70         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
71         {NULL, NULL}
72 };
73
74 static Display *vidx11_display = NULL;
75 static int vidx11_screen;
76 static Window win;
77 static GLXContext ctx = NULL;
78
79 Atom wm_delete_window_atom;
80
81 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
82 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
83                     PointerMotionMask | ButtonMotionMask)
84 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
85                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
86                 LeaveWindowMask)
87
88
89 static qboolean mouse_avail = true;
90 static qboolean vid_usingmouse = false;
91 static qboolean vid_usemouse = false;
92 static qboolean vid_usingvsync = false;
93 static qboolean vid_usevsync = false;
94 static float    mouse_x, mouse_y;
95 static int p_mouse_x, p_mouse_y;
96
97 #ifndef __APPLE__
98 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
99 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
100 #endif
101
102 qboolean vidmode_ext = false;
103
104 static int win_x, win_y;
105
106 static int scr_width, scr_height;
107
108 static XF86VidModeModeInfo **vidmodes;
109 static int num_vidmodes;
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                 default:
214                         if (keysym < 32 && keysym > 126)
215                                 break;
216
217                         if (keysym >= 'A' && keysym <= 'Z')
218                                 key = keysym - 'A' + 'a';
219                         else
220                                 key = keysym;
221
222                         break;
223         }
224
225         return key;
226 }
227
228 static Cursor CreateNullCursor(Display *display, Window root)
229 {
230         Pixmap cursormask;
231         XGCValues xgc;
232         GC gc;
233         XColor dummycolour;
234         Cursor cursor;
235
236         cursormask = XCreatePixmap(display, root, 1, 1, 1);
237         xgc.function = GXclear;
238         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
239         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
240         dummycolour.pixel = 0;
241         dummycolour.red = 0;
242         dummycolour.flags = 04;
243         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
244         XFreePixmap(display,cursormask);
245         XFreeGC(display,gc);
246         return cursor;
247 }
248
249 static void IN_Activate (qboolean grab)
250 {
251         if (!vidx11_display)
252                 return;
253         if (grab)
254         {
255                 if (!vid_usingmouse && mouse_avail && win)
256                 {
257                         XWindowAttributes attribs_1;
258                         XSetWindowAttributes attribs_2;
259
260                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
261                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
262                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
263
264                 // inviso cursor
265                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
266
267                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
268
269 #ifndef __APPLE__
270                         if (vid_dga.integer)
271                         {
272                                 int MajorVersion, MinorVersion;
273
274                                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
275                                 {
276                                         // unable to query, probably not supported
277                                         Con_Print( "Failed to detect XF86DGA Mouse\n" );
278                                         Cvar_SetValueQuick(&vid_dga, 0);
279                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
280                                 }
281                                 else
282                                 {
283                                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
284                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
285                                 }
286                         }
287                         else
288 #endif
289                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
290
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 #ifndef __APPLE__
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 void HandleEvents(void)
321 {
322         XEvent event;
323         int key;
324         char ascii;
325         qboolean dowarp = false;
326
327         if (!vidx11_display)
328                 return;
329
330         while (XPending(vidx11_display))
331         {
332                 XNextEvent(vidx11_display, &event);
333
334                 switch (event.type)
335                 {
336                 case KeyPress:
337                         // key pressed
338                         key = XLateKey (&event.xkey, &ascii);
339                         Key_Event(key, ascii, true);
340                         break;
341
342                 case KeyRelease:
343                         // key released
344                         key = XLateKey (&event.xkey, &ascii);
345                         Key_Event(key, ascii, false);
346                         break;
347
348                 case MotionNotify:
349                         // mouse moved
350                         if (vid_usingmouse)
351                         {
352 #ifndef __APPLE__
353                                 if (vid_dga.integer == 1)
354                                 {
355                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
356                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
357                                 }
358                                 else
359 #endif
360                                 {
361
362                                         if (!event.xmotion.send_event)
363                                         {
364                                                 mouse_x += event.xmotion.x - p_mouse_x;
365                                                 mouse_y += event.xmotion.y - p_mouse_y;
366                                                 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
367                                                         dowarp = true;
368                                         }
369                                         p_mouse_x = event.xmotion.x;
370                                         p_mouse_y = event.xmotion.y;
371                                 }
372                         }
373                         //else
374                         //      ui_mouseupdate(event.xmotion.x, event.xmotion.y);
375                         break;
376
377                 case ButtonPress:
378                         // mouse button pressed
379                         switch(event.xbutton.button)
380                         {
381                         case 1:
382                                 Key_Event(K_MOUSE1, 0, true);
383                                 break;
384                         case 2:
385                                 Key_Event(K_MOUSE3, 0, true);
386                                 break;
387                         case 3:
388                                 Key_Event(K_MOUSE2, 0, true);
389                                 break;
390                         case 4:
391                                 Key_Event(K_MWHEELUP, 0, true);
392                                 break;
393                         case 5:
394                                 Key_Event(K_MWHEELDOWN, 0, true);
395                                 break;
396                         case 6:
397                                 Key_Event(K_MOUSE4, 0, true);
398                                 break;
399                         case 7:
400                                 Key_Event(K_MOUSE5, 0, true);
401                                 break;
402                         case 8:
403                                 Key_Event(K_MOUSE6, 0, true);
404                                 break;
405                         case 9:
406                                 Key_Event(K_MOUSE7, 0, true);
407                                 break;
408                         case 10:
409                                 Key_Event(K_MOUSE8, 0, true);
410                                 break;
411                         case 11:
412                                 Key_Event(K_MOUSE9, 0, true);
413                                 break;
414                         case 12:
415                                 Key_Event(K_MOUSE10, 0, true);
416                                 break;
417                         default:
418                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-12 expected\n", event.xbutton.button);
419                                 break;
420                         }
421                         break;
422
423                 case ButtonRelease:
424                         // mouse button released
425                         switch(event.xbutton.button)
426                         {
427                         case 1:
428                                 Key_Event(K_MOUSE1, 0, false);
429                                 break;
430                         case 2:
431                                 Key_Event(K_MOUSE3, 0, false);
432                                 break;
433                         case 3:
434                                 Key_Event(K_MOUSE2, 0, false);
435                                 break;
436                         case 4:
437                                 Key_Event(K_MWHEELUP, 0, false);
438                                 break;
439                         case 5:
440                                 Key_Event(K_MWHEELDOWN, 0, false);
441                                 break;
442                         case 6:
443                                 Key_Event(K_MOUSE4, 0, false);
444                                 break;
445                         case 7:
446                                 Key_Event(K_MOUSE5, 0, false);
447                                 break;
448                         case 8:
449                                 Key_Event(K_MOUSE6, 0, false);
450                                 break;
451                         case 9:
452                                 Key_Event(K_MOUSE7, 0, false);
453                                 break;
454                         case 10:
455                                 Key_Event(K_MOUSE8, 0, false);
456                                 break;
457                         case 11:
458                                 Key_Event(K_MOUSE9, 0, false);
459                                 break;
460                         case 12:
461                                 Key_Event(K_MOUSE10, 0, false);
462                                 break;
463                         default:
464                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-12 expected\n", event.xbutton.button);
465                                 break;
466                         }
467                         break;
468
469                 case CreateNotify:
470                         // window created
471                         win_x = event.xcreatewindow.x;
472                         win_y = event.xcreatewindow.y;
473                         break;
474
475                 case ConfigureNotify:
476                         // window changed size/location
477                         win_x = event.xconfigure.x;
478                         win_y = event.xconfigure.y;
479                         break;
480                 case DestroyNotify:
481                         // window has been destroyed
482                         Sys_Quit();
483                         break;
484                 case ClientMessage:
485                         // window manager messages
486                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
487                                 Sys_Quit();
488                         break;
489                 case MapNotify:
490                         // window restored
491                         vid_hidden = false;
492                         vid_activewindow = false;
493                         VID_RestoreSystemGamma();
494                         break;
495                 case UnmapNotify:
496                         // window iconified/rolledup/whatever
497                         vid_hidden = true;
498                         vid_activewindow = false;
499                         VID_RestoreSystemGamma();
500                         break;
501                 case FocusIn:
502                         // window is now the input focus
503                         vid_activewindow = true;
504                         break;
505                 case FocusOut:
506                         // window is no longer the input focus
507                         vid_activewindow = false;
508                         VID_RestoreSystemGamma();
509                         break;
510                 case EnterNotify:
511                         // mouse entered window
512                         break;
513                 case LeaveNotify:
514                         // mouse left window
515                         break;
516                 }
517         }
518
519         if (dowarp)
520         {
521                 /* move the mouse to the window center again */
522                 p_mouse_x = scr_width / 2;
523                 p_mouse_y = scr_height / 2;
524                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
525         }
526 }
527
528 static void *prjobj = NULL;
529
530 static void GL_CloseLibrary(void)
531 {
532         if (prjobj)
533                 dlclose(prjobj);
534         prjobj = NULL;
535         gl_driver[0] = 0;
536         qglXGetProcAddressARB = NULL;
537         gl_extensions = "";
538         gl_platform = "";
539         gl_platformextensions = "";
540 }
541
542 static int GL_OpenLibrary(const char *name)
543 {
544         Con_Printf("Loading OpenGL driver %s\n", name);
545         GL_CloseLibrary();
546         if (!(prjobj = dlopen(name, RTLD_LAZY)))
547         {
548                 Con_Printf("Unable to open symbol list for %s\n", name);
549                 return false;
550         }
551         strcpy(gl_driver, name);
552         return true;
553 }
554
555 void *GL_GetProcAddress(const char *name)
556 {
557         void *p = NULL;
558         if (qglXGetProcAddressARB != NULL)
559                 p = (void *) qglXGetProcAddressARB(name);
560         if (p == NULL)
561                 p = (void *) dlsym(prjobj, name);
562         return p;
563 }
564
565 void VID_Shutdown(void)
566 {
567         if (!ctx || !vidx11_display)
568                 return;
569
570         if (vidx11_display)
571         {
572                 IN_Activate(false);
573                 VID_RestoreSystemGamma();
574
575                 // FIXME: glXDestroyContext here?
576                 if (vid_isfullscreen)
577                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[0]);
578                 if (win)
579                         XDestroyWindow(vidx11_display, win);
580                 XCloseDisplay(vidx11_display);
581         }
582         vid_hidden = true;
583         vid_isfullscreen = false;
584         vidx11_display = NULL;
585         win = 0;
586         ctx = NULL;
587
588         GL_CloseLibrary();
589         Key_ClearStates ();
590 }
591
592 void signal_handler(int sig)
593 {
594         Con_Printf("Received signal %d, exiting...\n", sig);
595         VID_RestoreSystemGamma();
596         Sys_Quit();
597         exit(0);
598 }
599
600 void InitSig(void)
601 {
602         signal(SIGHUP, signal_handler);
603         signal(SIGINT, signal_handler);
604         signal(SIGQUIT, signal_handler);
605         signal(SIGILL, signal_handler);
606         signal(SIGTRAP, signal_handler);
607         signal(SIGIOT, signal_handler);
608         signal(SIGBUS, signal_handler);
609         signal(SIGFPE, signal_handler);
610         signal(SIGSEGV, signal_handler);
611         signal(SIGTERM, signal_handler);
612 }
613
614 /*
615 =================
616 VID_GetWindowSize
617 =================
618 */
619 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
620 {
621         *x = *y = 0;
622         *width = scr_width;
623         *height = scr_height;
624 }
625
626 void VID_Finish (void)
627 {
628         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
629         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
630         {
631                 vid_usingvsync = vid_usevsync;
632                 if (qglXSwapIntervalSGI (vid_usevsync))
633                         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");
634         }
635
636 // handle the mouse state when windowed if that's changed
637         vid_usemouse = false;
638         if (vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
639                 vid_usemouse = true;
640         if (!vid_activewindow)
641                 vid_usemouse = false;
642         if (vid_isfullscreen)
643                 vid_usemouse = true;
644         IN_Activate(vid_usemouse);
645
646         if (r_render.integer)
647         {
648                 if (r_speeds.integer || gl_finish.integer)
649                         qglFinish();
650                 qglXSwapBuffers(vidx11_display, win);
651         }
652 }
653
654 int VID_SetGamma(unsigned short *ramps)
655 {
656         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
657 }
658
659 int VID_GetGamma(unsigned short *ramps)
660 {
661         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
662 }
663
664 void VID_Init(void)
665 {
666 #ifndef __APPLE__
667         Cvar_RegisterVariable (&vid_dga);
668         Cvar_RegisterVariable (&vid_dga_mouseaccel);
669 #endif
670         InitSig(); // trap evil signals
671 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
672         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
673                 mouse_avail = false;
674 }
675
676 void VID_BuildGLXAttrib(int *attrib, int stencil)
677 {
678         *attrib++ = GLX_RGBA;
679         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
680         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
681         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
682         *attrib++ = GLX_DOUBLEBUFFER;
683         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
684         // if stencil is enabled, ask for alpha too
685         if (stencil)
686         {
687                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
688                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
689         }
690         *attrib++ = None;
691 }
692
693 int VID_InitMode(int fullscreen, int width, int height, int bpp)
694 {
695         int i;
696         int attrib[32];
697         XSetWindowAttributes attr;
698         unsigned long mask;
699         Window root;
700         XVisualInfo *visinfo;
701         int MajorVersion, MinorVersion;
702         const char *drivername;
703
704 #if defined(__APPLE__) && defined(__MACH__)
705         drivername = "/usr/X11R6/lib/libGL.1.dylib";
706 #else
707         drivername = "libGL.so.1";
708 #endif
709 // 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
710 // 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
711 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
712         i = COM_CheckParm("-gl_driver");
713         if (i && i < com_argc - 1)
714                 drivername = com_argv[i + 1];
715         if (!GL_OpenLibrary(drivername))
716         {
717                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
718                 return false;
719         }
720
721         if (!(vidx11_display = XOpenDisplay(NULL)))
722         {
723                 Con_Print("Couldn't open the X display\n");
724                 return false;
725         }
726
727         vidx11_screen = DefaultScreen(vidx11_display);
728         root = RootWindow(vidx11_display, vidx11_screen);
729
730         // Get video mode list
731         MajorVersion = MinorVersion = 0;
732         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
733                 vidmode_ext = false;
734         else
735         {
736                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
737                 vidmode_ext = true;
738         }
739
740         if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
741          || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
742          || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
743          || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
744          || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
745         {
746                 Con_Printf("glX functions not found in %s\n", gl_driver);
747                 return false;
748         }
749
750         VID_BuildGLXAttrib(attrib, bpp == 32);
751         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
752         if (!visinfo)
753         {
754                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
755                 return false;
756         }
757
758         if (vidmode_ext)
759         {
760                 int best_fit, best_dist, dist, x, y;
761
762                 // Are we going fullscreen?  If so, let's change video mode
763                 if (fullscreen)
764                 {
765                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
766                         best_dist = 9999999;
767                         best_fit = -1;
768
769                         for (i = 0; i < num_vidmodes; i++)
770                         {
771                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
772                                         continue;
773
774                                 x = width - vidmodes[i]->hdisplay;
775                                 y = height - vidmodes[i]->vdisplay;
776                                 dist = (x * x) + (y * y);
777                                 if (dist < best_dist)
778                                 {
779                                         best_dist = dist;
780                                         best_fit = i;
781                                 }
782                         }
783
784                         if (best_fit != -1)
785                         {
786                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
787                                 // to width/height =, so the window will take the full area of
788                                 // the mode chosen
789                                 width = vidmodes[best_fit]->hdisplay;
790                                 height = vidmodes[best_fit]->vdisplay;
791
792                                 // change to the mode
793                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
794                                 vid_isfullscreen = true;
795
796                                 // Move the viewport to top left
797                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
798                         }
799                         else
800                                 fullscreen = 0;
801                 }
802         }
803
804         // LordHavoc: save the visual for use in gamma ramp settings later
805         vidx11_visual = visinfo->visual;
806
807         /* window attributes */
808         attr.background_pixel = 0;
809         attr.border_pixel = 0;
810         // LordHavoc: save the colormap for later, too
811         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
812         attr.event_mask = X_MASK;
813         if (vid_isfullscreen)
814         {
815                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
816                 attr.override_redirect = True;
817                 attr.backing_store = NotUseful;
818                 attr.save_under = False;
819         }
820         else
821                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
822
823         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
824         XStoreName(vidx11_display, win, gamename);
825         XMapWindow(vidx11_display, win);
826
827         // LordHavoc: making the close button on a window do the right thing
828         // seems to involve this mess, sigh...
829         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
830         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
831
832         if (vid_isfullscreen)
833         {
834                 XMoveWindow(vidx11_display, win, 0, 0);
835                 XRaiseWindow(vidx11_display, win);
836                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
837                 XFlush(vidx11_display);
838                 // Move the viewport to top left
839                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
840         }
841
842         //XSync(vidx11_display, False);
843
844         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
845         if (!ctx)
846                 Sys_Error ("glXCreateContext failed\n");
847
848         if (!qglXMakeCurrent(vidx11_display, win, ctx))
849                 Sys_Error ("glXMakeCurrent failed\n");
850
851         XSync(vidx11_display, False);
852
853         scr_width = width;
854         scr_height = height;
855
856         if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
857                 Sys_Error("glGetString not found in %s", gl_driver);
858
859         gl_renderer = qglGetString(GL_RENDERER);
860         gl_vendor = qglGetString(GL_VENDOR);
861         gl_version = qglGetString(GL_VERSION);
862         gl_extensions = qglGetString(GL_EXTENSIONS);
863         gl_platform = "GLX";
864         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
865
866         gl_videosyncavailable = false;
867
868 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
869 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
870 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
871         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
872 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
873 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
874 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
875         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
876
877         vid_usingmouse = false;
878         vid_usingvsync = false;
879         vid_hidden = false;
880         vid_activewindow = true;
881         GL_Init();
882         return true;
883 }
884
885 void Sys_SendKeyEvents(void)
886 {
887         HandleEvents();
888 }
889
890 void IN_Move (void)
891 {
892         if (mouse_avail)
893         {
894                 in_mouse_x = mouse_x;
895                 in_mouse_y = mouse_y;
896         }
897         mouse_x = 0;
898         mouse_y = 0;
899 }