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