VID_Init now takes mode settings (fullscreen, width, height)
[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 #include <X11/extensions/xf86dga.h>
39 #include <X11/extensions/xf86vmode.h>
40
41 #include "quakedef.h"
42
43 //GLX prototypes
44 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
45 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
46 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
47 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
48 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
49 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
50
51 //GLX_ARB_get_proc_address
52 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
53
54 static gl_extensionfunctionlist_t getprocaddressfuncs[] =
55 {
56         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
57         {NULL, NULL}
58 };
59
60 //GLX_SGI_video_sync
61 GLint (GLAPIENTRY *qglXGetVideoSyncSGI)(GLuint *count);
62 GLint (GLAPIENTRY *qglXWaitVideoSyncSGI)(int divisor, int remainder, unsigned int *count);
63
64 static gl_extensionfunctionlist_t videosyncfuncs[] =
65 {
66         {"glXGetVideoSyncSGI", (void **) &qglXGetVideoSyncSGI},
67         {"glXWaitVideoSyncSGI", (void **) &qglXWaitVideoSyncSGI},
68         {NULL, NULL}
69 };
70
71 static Display *vidx11_display = NULL;
72 static int scrnum;
73 static Window win;
74 static GLXContext ctx = NULL;
75
76 Atom wm_delete_window_atom;
77
78 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
79 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
80                     PointerMotionMask | ButtonMotionMask )
81 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | StructureNotifyMask )
82
83
84 viddef_t        vid;                            // global video state
85
86 static qboolean         mouse_avail = true;
87 static qboolean         mouse_active = false, usingmouse = false;
88 static float    mouse_x, mouse_y;
89 static int p_mouse_x, p_mouse_y;
90
91 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
92 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
93
94 qboolean vidmode_ext = false;
95
96 static int win_x, win_y;
97
98 static int scr_width, scr_height;
99
100 static XF86VidModeModeInfo **vidmodes;
101 static int num_vidmodes;
102 static qboolean vidmode_active = false;
103
104 static Visual *vidx11_visual;
105 static Colormap vidx11_colormap;
106
107 /*-----------------------------------------------------------------------*/
108
109 static int
110 XLateKey(XKeyEvent *ev)
111 {
112         int key = 0;
113         KeySym keysym;
114
115         keysym = XLookupKeysym(ev, 0);
116
117         switch(keysym)
118         {
119                 case XK_KP_Page_Up:     key = KP_PGUP; break;
120                 case XK_Page_Up:        key = K_PGUP; break;
121
122                 case XK_KP_Page_Down:   key = KP_PGDN; break;
123                 case XK_Page_Down:      key = K_PGDN; break;
124
125                 case XK_KP_Home:        key = KP_HOME; break;
126                 case XK_Home:           key = K_HOME; break;
127
128                 case XK_KP_End:         key = KP_END; break;
129                 case XK_End:            key = K_END; break;
130
131                 case XK_KP_Left:        key = KP_LEFTARROW; break;
132                 case XK_Left:           key = K_LEFTARROW; break;
133
134                 case XK_KP_Right:       key = KP_RIGHTARROW; break;
135                 case XK_Right:          key = K_RIGHTARROW; break;
136
137                 case XK_KP_Down:        key = KP_DOWNARROW; break;
138                 case XK_Down:           key = K_DOWNARROW; break;
139
140                 case XK_KP_Up:          key = KP_UPARROW; break;
141                 case XK_Up:                     key = K_UPARROW; break;
142
143                 case XK_Escape:         key = K_ESCAPE; break;
144
145                 case XK_KP_Enter:       key = KP_ENTER; break;
146                 case XK_Return:         key = K_ENTER; break;
147
148                 case XK_Tab:            key = K_TAB; break;
149
150                 case XK_F1:                     key = K_F1; break;
151                 case XK_F2:                     key = K_F2; break;
152                 case XK_F3:                     key = K_F3; break;
153                 case XK_F4:                     key = K_F4; break;
154                 case XK_F5:                     key = K_F5; break;
155                 case XK_F6:                     key = K_F6; break;
156                 case XK_F7:                     key = K_F7; break;
157                 case XK_F8:                     key = K_F8; break;
158                 case XK_F9:                     key = K_F9; break;
159                 case XK_F10:            key = K_F10; break;
160                 case XK_F11:            key = K_F11; break;
161                 case XK_F12:            key = K_F12; break;
162
163                 case XK_BackSpace:      key = K_BACKSPACE; break;
164
165                 case XK_KP_Delete:      key = KP_DEL; break;
166                 case XK_Delete:         key = K_DEL; break;
167
168                 case XK_Pause:          key = K_PAUSE; break;
169
170                 case XK_Shift_L:
171                 case XK_Shift_R:        key = K_SHIFT; break;
172
173                 case XK_Execute:
174                 case XK_Control_L:
175                 case XK_Control_R:      key = K_CTRL; break;
176
177                 case XK_Mode_switch:
178                 case XK_Alt_L:
179                 case XK_Meta_L:
180                 case XK_Alt_R:
181                 case XK_Meta_R:         key = K_ALT; break;
182
183                 case XK_Caps_Lock:      key = K_CAPSLOCK; break;
184                 case XK_KP_Begin:       key = KP_5; break;
185
186                 case XK_Insert:         key = K_INS; break;
187                 case XK_KP_Insert:      key = KP_INS; break;
188
189                 case XK_KP_Multiply:    key = KP_MULTIPLY; break;
190                 case XK_KP_Add:         key = KP_PLUS; break;
191                 case XK_KP_Subtract:    key = KP_MINUS; break;
192                 case XK_KP_Divide:      key = KP_DIVIDE; break;
193
194                 /* For Sun keyboards */
195                 case XK_F27:            key = K_HOME; break;
196                 case XK_F29:            key = K_PGUP; break;
197                 case XK_F33:            key = K_END; break;
198                 case XK_F35:            key = K_PGDN; break;
199
200                 default:
201                         if (keysym < 128)
202                         {
203                                 /* ASCII keys */
204                                 key = keysym;
205                                 if ((key >= 'A') && (key <= 'Z'))
206                                         key = key + ('a' - 'A');
207                         }
208                         break;
209         }
210
211         return key;
212 }
213
214 static Cursor CreateNullCursor(Display *display, Window root)
215 {
216         Pixmap cursormask;
217         XGCValues xgc;
218         GC gc;
219         XColor dummycolour;
220         Cursor cursor;
221
222         cursormask = XCreatePixmap(display, root, 1, 1, 1);
223         xgc.function = GXclear;
224         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
225         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
226         dummycolour.pixel = 0;
227         dummycolour.red = 0;
228         dummycolour.flags = 04;
229         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
230         XFreePixmap(display,cursormask);
231         XFreeGC(display,gc);
232         return cursor;
233 }
234
235 static void install_grabs(void)
236 {
237         XWindowAttributes attribs_1;
238         XSetWindowAttributes attribs_2;
239
240         XGetWindowAttributes(vidx11_display, win, &attribs_1);
241         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
242         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
243
244 // inviso cursor
245         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
246
247         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
248
249         if (vid_dga.integer)
250         {
251                 int MajorVersion, MinorVersion;
252
253                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
254                 {
255                         // unable to query, probalby not supported
256                         Con_Printf( "Failed to detect XF86DGA Mouse\n" );
257                         vid_dga.integer = 0;
258                 }
259                 else
260                 {
261                         vid_dga.integer = 1;
262                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
263                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
264                 }
265         }
266         else
267                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
268
269         XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
270
271         mouse_active = true;
272         mouse_x = mouse_y = 0;
273 }
274
275 static void uninstall_grabs(void)
276 {
277         if (!vidx11_display || !win)
278                 return;
279
280         if (vid_dga.integer == 1)
281                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
282
283         XUngrabPointer(vidx11_display, CurrentTime);
284         XUngrabKeyboard(vidx11_display, CurrentTime);
285
286 // inviso cursor
287         XUndefineCursor(vidx11_display, win);
288
289         mouse_active = false;
290 }
291
292 static void HandleEvents(void)
293 {
294         XEvent event;
295         qboolean dowarp = false;
296
297         if (!vidx11_display)
298                 return;
299
300         while (XPending(vidx11_display))
301         {
302                 XNextEvent(vidx11_display, &event);
303
304                 switch (event.type)
305                 {
306                 case KeyPress:
307                         // key pressed
308                         Key_Event(XLateKey(&event.xkey), true);
309                         break;
310
311                 case KeyRelease:
312                         // key released
313                         Key_Event(XLateKey(&event.xkey), false);
314                         break;
315
316                 case MotionNotify:
317                         // mouse moved
318                         if (usingmouse)
319                         {
320                                 if (vid_dga.integer == 1)
321                                 {
322                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
323                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
324                                 }
325                                 else
326                                 {
327
328                                         if (!event.xmotion.send_event)
329                                         {
330                                                 mouse_x += event.xmotion.x - p_mouse_x;
331                                                 mouse_y += event.xmotion.y - p_mouse_y;
332                                                 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
333                                                         dowarp = true;
334                                         }
335                                         p_mouse_x = event.xmotion.x;
336                                         p_mouse_y = event.xmotion.y;
337                                 }
338                         }
339                         else
340                                 ui_mouseupdate(event.xmotion.x, event.xmotion.y);
341                         break;
342
343                 case ButtonPress:
344                         // mouse button pressed
345                         switch(event.xbutton.button)
346                         {
347                         case 1:
348                                 Key_Event(K_MOUSE1, true);
349                                 break;
350                         case 2:
351                                 Key_Event(K_MOUSE3, true);
352                                 break;
353                         case 3:
354                                 Key_Event(K_MOUSE2, true);
355                                 break;
356                         case 4:
357                                 Key_Event(K_MWHEELUP, true);
358                                 break;
359                         case 5:
360                                 Key_Event(K_MWHEELDOWN, true);
361                                 break;
362                 default:
363                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-5 expected\n", event.xbutton.button);
364                                 break;
365                         }
366                         break;
367
368                 case ButtonRelease:
369                         // mouse button released
370                         switch(event.xbutton.button)
371                         {
372                         case 1:
373                                 Key_Event(K_MOUSE1, false);
374                                 break;
375                         case 2:
376                                 Key_Event(K_MOUSE3, false);
377                                 break;
378                         case 3:
379                                 Key_Event(K_MOUSE2, false);
380                                 break;
381                         case 4:
382                                 Key_Event(K_MWHEELUP, false);
383                                 break;
384                         case 5:
385                                 Key_Event(K_MWHEELDOWN, false);
386                                 break;
387                 default:
388                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-5 expected\n", event.xbutton.button);
389                                 break;
390                         }
391                         break;
392
393                 case CreateNotify:
394                         // window created
395                         win_x = event.xcreatewindow.x;
396                         win_y = event.xcreatewindow.y;
397                         break;
398
399                 case ConfigureNotify:
400                         // window changed size/location
401                         win_x = event.xconfigure.x;
402                         win_y = event.xconfigure.y;
403                         break;
404                 case DestroyNotify:
405                         // window has been destroyed
406                         Sys_Quit();
407                         break;
408                 case ClientMessage:
409                         // window manager messages
410                         if ((event.xclient.format == 32) && (event.xclient.data.l[0] == wm_delete_window_atom))
411                                 Sys_Quit();
412                         break;
413                 case MapNotify:
414                         // window restored
415                         vid_hidden = false;
416                         break;
417                 case UnmapNotify:
418                         // window iconified/rolledup/whatever
419                         vid_hidden = true;
420                         break;
421                 case FocusIn:
422                         // window is now the input focus
423                         break;
424                 case FocusOut:
425                         // window is no longer the input focus
426                         break;
427                 case EnterNotify:
428                         // mouse entered window
429                         break;
430                 case LeaveNotify:
431                         // mouse left window
432                         break;
433                 }
434         }
435
436         if (dowarp)
437         {
438                 /* move the mouse to the window center again */
439                 p_mouse_x = scr_width / 2;
440                 p_mouse_y = scr_height / 2;
441                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
442         }
443
444 }
445
446 static void IN_DeactivateMouse( void )
447 {
448         if (!mouse_avail || !vidx11_display || !win)
449                 return;
450
451         if (mouse_active)
452         {
453                 uninstall_grabs();
454                 mouse_active = false;
455         }
456 }
457
458 static void IN_ActivateMouse( void )
459 {
460         if (!mouse_avail || !vidx11_display || !win)
461                 return;
462
463         if (!mouse_active)
464         {
465                 mouse_x = mouse_y = 0; // don't spazz
466                 install_grabs();
467                 mouse_active = true;
468         }
469 }
470
471
472 void VID_Shutdown(void)
473 {
474         if (!ctx || !vidx11_display)
475                 return;
476
477         if (vidx11_display)
478         {
479                 uninstall_grabs();
480
481                 if (vidmode_active)
482                         XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[0]);
483                 if (win)
484                         XDestroyWindow(vidx11_display, win);
485                 XCloseDisplay(vidx11_display);
486         }
487         vidmode_active = false;
488         vidx11_display = NULL;
489         win = 0;
490         ctx = NULL;
491
492         GL_CloseLibrary();
493 }
494
495 void signal_handler(int sig)
496 {
497         printf("Received signal %d, exiting...\n", sig);
498         Sys_Quit();
499         exit(0);
500 }
501
502 void InitSig(void)
503 {
504         signal(SIGHUP, signal_handler);
505         signal(SIGINT, signal_handler);
506         signal(SIGQUIT, signal_handler);
507         signal(SIGILL, signal_handler);
508         signal(SIGTRAP, signal_handler);
509         signal(SIGIOT, signal_handler);
510         signal(SIGBUS, signal_handler);
511         signal(SIGFPE, signal_handler);
512         signal(SIGSEGV, signal_handler);
513         signal(SIGTERM, signal_handler);
514 }
515
516 /*
517 =================
518 VID_GetWindowSize
519 =================
520 */
521 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
522 {
523         *x = *y = 0;
524         *width = scr_width;
525         *height = scr_height;
526 }
527
528 void VID_Finish (void)
529 {
530         int usemouse;
531         if (r_render.integer)
532         {
533                 qglFinish();
534                 qglXSwapBuffers(vidx11_display, win);
535         }
536
537 // handle the mouse state when windowed if that's changed
538         usemouse = false;
539         if (vid_mouse.integer && !key_consoleactive)
540                 usemouse = true;
541         if (vidmode_active)
542                 usemouse = true;
543         if (usemouse)
544         {
545                 if (!usingmouse)
546                 {
547                         usingmouse = true;
548                         IN_ActivateMouse ();
549                 }
550         }
551         else
552         {
553                 if (usingmouse)
554                 {
555                         usingmouse = false;
556                         IN_DeactivateMouse ();
557                 }
558         }
559 }
560
561 // LordHavoc: ported from SDL 1.2.2, this was far more difficult to port from
562 // SDL than to simply use the XFree gamma ramp extension, but that affects the
563 // whole screen even when the game window is inactive, this only affects the
564 // screen while the window is active, very desirable behavior :)
565 int VID_SetGamma(float prescale, float gamma, float scale, float base)
566 {
567 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
568 #if 1
569         return FALSE;
570 #else
571         int i, ncolors, c;
572         unsigned int Rmask, Gmask, Bmask, Rloss, Gloss, Bloss, Rshift, Gshift, Bshift, mask;
573         XColor xcmap[256];
574         unsigned short ramp[256];
575
576         if (COM_CheckParm("-nogamma"))
577                 return FALSE;
578
579         if (vidx11_visual->class != DirectColor)
580         {
581                 Con_Printf("X11 Visual class is %d, can only do gamma on %d\n", vidx11_visual->class, DirectColor);
582                 return FALSE;
583         }
584
585         Rmask = vidx11_visual->red_mask;
586         Gmask = vidx11_visual->green_mask;
587         Bmask = vidx11_visual->blue_mask;
588
589         Rshift = 0;
590         Rloss = 8;
591         if ((mask = Rmask))
592         {
593                 for (;!(mask & 1);mask >>= 1)
594                         ++Rshift;
595                 for (;(mask & 1);mask >>= 1)
596                         --Rloss;
597         }
598         Gshift = 0;
599         Gloss = 8;
600         if ((mask = Gmask))
601         {
602                 for (;!(mask & 1);mask >>= 1)
603                         ++Gshift;
604                 for (;(mask & 1);mask >>= 1)
605                         --Gloss;
606         }
607         Bshift = 0;
608         Bloss = 8;
609         if ((mask = Bmask))
610         {
611                 for (;!(mask & 1);mask >>= 1)
612                         ++Bshift;
613                 for (;(mask & 1);mask >>= 1)
614                         --Bloss;
615         }
616
617         BuildGammaTable16(prescale, gamma, scale, base, ramp);
618
619         // convert gamma ramp to palette (yes this seems odd)
620         ncolors = vidx11_visual->map_entries;
621         for (i = 0;i < ncolors;i++)
622         {
623                 c = (256 * i / ncolors);
624                 xcmap[i].pixel = ((c >> Rloss) << Rshift) | ((c >> Gloss) << Gshift) | ((c >> Bloss) << Bshift);
625                 xcmap[i].red   = ramp[c];
626                 xcmap[i].green = ramp[c];
627                 xcmap[i].blue  = ramp[c];
628                 xcmap[i].flags = (DoRed|DoGreen|DoBlue);
629         }
630         XStoreColors(vidx11_display, vidx11_colormap, xcmap, ncolors);
631         XSync(vidx11_display, false);
632         // FIXME: should this check for BadAccess/BadColor/BadValue errors produced by XStoreColors before setting this true?
633         return TRUE;
634 #endif
635 }
636
637 void VID_Init(int fullscreen, int width, int height)
638 {
639         int i;
640 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
641 #if 0
642         int gammaattrib[] =
643         {
644                 GLX_RGBA,
645                 GLX_RED_SIZE, 1,
646                 GLX_GREEN_SIZE, 1,
647                 GLX_BLUE_SIZE, 1,
648                 GLX_DOUBLEBUFFER,
649                 GLX_DEPTH_SIZE, 1,
650                 GLX_X_VISUAL_TYPE, GLX_DIRECT_COLOR,
651                 None
652         };
653 #endif
654         int nogammaattrib[] =
655         {
656                 GLX_RGBA,
657                 GLX_RED_SIZE, 1,
658                 GLX_GREEN_SIZE, 1,
659                 GLX_BLUE_SIZE, 1,
660                 GLX_DOUBLEBUFFER,
661                 GLX_DEPTH_SIZE, 1,
662                 None
663         };
664         XSetWindowAttributes attr;
665         unsigned long mask;
666         Window root;
667         XVisualInfo *visinfo;
668         int MajorVersion, MinorVersion;
669
670         if (!GL_OpenLibrary("libGL.so.1"))
671                 Sys_Error("Unable to load GL driver\n");
672
673         Cvar_RegisterVariable (&vid_dga);
674         Cvar_RegisterVariable (&vid_dga_mouseaccel);
675
676         if (!(vidx11_display = XOpenDisplay(NULL)))
677         {
678                 fprintf(stderr, "Error couldn't open the X display\n");
679                 exit(1);
680         }
681
682         scrnum = DefaultScreen(vidx11_display);
683         root = RootWindow(vidx11_display, scrnum);
684
685         // Get video mode list
686         MajorVersion = MinorVersion = 0;
687         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
688                 vidmode_ext = false;
689         else
690         {
691                 Con_Printf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
692                 vidmode_ext = true;
693         }
694
695         if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
696          || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
697          || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
698          || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
699          || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
700                 Sys_Error("glX functions not found in %s\n", gl_driver);
701
702         visinfo = NULL;
703 // LordHavoc: FIXME: finish this code, we need to allocate colors before we can store them
704 #if 0
705         if (!COM_CheckParm("-nogamma"))
706                 visinfo = qglXChooseVisual(vidx11_display, scrnum, gammaattrib);
707 #endif
708         if (!visinfo)
709         {
710                 visinfo = qglXChooseVisual(vidx11_display, scrnum, nogammaattrib);
711                 if (!visinfo)
712                 {
713                         Sys_Error("couldn't get an RGB, Double-buffered, Depth visual\n");
714                         exit(1);
715                 }
716         }
717
718         if (vidmode_ext)
719         {
720                 int best_fit, best_dist, dist, x, y;
721
722                 XF86VidModeGetAllModeLines(vidx11_display, scrnum, &num_vidmodes, &vidmodes);
723
724                 // Are we going fullscreen?  If so, let's change video mode
725                 if (fullscreen)
726                 {
727                         best_dist = 9999999;
728                         best_fit = -1;
729
730                         for (i = 0; i < num_vidmodes; i++)
731                         {
732                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
733                                         continue;
734
735                                 x = width - vidmodes[i]->hdisplay;
736                                 y = height - vidmodes[i]->vdisplay;
737                                 dist = (x * x) + (y * y);
738                                 if (dist < best_dist)
739                                 {
740                                         best_dist = dist;
741                                         best_fit = i;
742                                 }
743                         }
744
745                         if (best_fit != -1)
746                         {
747                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
748                                 // to width/height =, so the window will take the full area of
749                                 // the mode chosen
750                                 width = vidmodes[best_fit]->hdisplay;
751                                 height = vidmodes[best_fit]->vdisplay;
752
753                                 // change to the mode
754                                 XF86VidModeSwitchToMode(vidx11_display, scrnum, vidmodes[best_fit]);
755                                 vidmode_active = true;
756
757                                 // Move the viewport to top left
758                                 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
759                         }
760                         else
761                                 fullscreen = 0;
762                 }
763         }
764
765         // LordHavoc: save the visual for use in gamma ramp settings later
766         vidx11_visual = visinfo->visual;
767
768         /* window attributes */
769         attr.background_pixel = 0;
770         attr.border_pixel = 0;
771         // LordHavoc: save the colormap for later, too
772         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
773         attr.event_mask = X_MASK;
774         if (vidmode_active)
775         {
776                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
777                 attr.override_redirect = True;
778                 attr.backing_store = NotUseful;
779                 attr.save_under = False;
780         }
781         else
782                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
783
784         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
785         XStoreName(vidx11_display, win, gamename);
786         XMapWindow(vidx11_display, win);
787
788         // LordHavoc: making the close button on a window do the right thing
789         // seems to involve this mess, sigh...
790         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
791         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
792
793         if (vidmode_active)
794         {
795                 XMoveWindow(vidx11_display, win, 0, 0);
796                 XRaiseWindow(vidx11_display, win);
797                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
798                 XFlush(vidx11_display);
799                 // Move the viewport to top left
800                 XF86VidModeSetViewPort(vidx11_display, scrnum, 0, 0);
801         }
802
803         XFlush(vidx11_display);
804
805         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
806
807         qglXMakeCurrent(vidx11_display, win, ctx);
808
809         scr_width = width;
810         scr_height = height;
811
812         if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
813                 Sys_Error("glGetString not found in %s", gl_driver);
814
815         gl_renderer = qglGetString(GL_RENDERER);
816         gl_vendor = qglGetString(GL_VENDOR);
817         gl_version = qglGetString(GL_VERSION);
818         gl_extensions = qglGetString(GL_EXTENSIONS);
819         gl_platform = "GLX";
820         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, scrnum);
821
822         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
823         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_video_sync", videosyncfuncs, "-novideosync", false);
824
825         InitSig(); // trap evil signals
826
827         vid_hidden = false;
828
829         GL_Init();
830
831         Con_SafePrintf ("Video mode %dx%d initialized.\n", width, height);
832 }
833
834 void Sys_SendKeyEvents(void)
835 {
836         HandleEvents();
837 }
838
839 void IN_Init(void)
840 {
841         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
842                 mouse_avail = false;
843 }
844
845 void IN_Shutdown(void)
846 {
847 }
848
849 /*
850 ===========
851 IN_Commands
852 ===========
853 */
854 void IN_Commands (void)
855 {
856 }
857
858 void IN_Move (usercmd_t *cmd)
859 {
860         if (mouse_avail)
861                 IN_Mouse(cmd, mouse_x, mouse_y);
862         mouse_x = 0;
863         mouse_y = 0;
864 }
865
866 static void *prjobj = NULL;
867
868 int GL_OpenLibrary(const char *name)
869 {
870         Con_Printf("Loading GL driver %s\n", name);
871         GL_CloseLibrary();
872         if (!(prjobj = dlopen(name, RTLD_LAZY)))
873         {
874                 Con_Printf("Unable to open symbol list for %s\n", name);
875                 return false;
876         }
877         strcpy(gl_driver, name);
878         return true;
879 }
880
881 void GL_CloseLibrary(void)
882 {
883         if (prjobj)
884                 dlclose(prjobj);
885         prjobj = NULL;
886         gl_driver[0] = 0;
887         qglXGetProcAddressARB = NULL;
888         gl_extensions = "";
889         gl_platform = "";
890         gl_platformextensions = "";
891 }
892
893 void *GL_GetProcAddress(const char *name)
894 {
895         void *p = NULL;
896         if (qglXGetProcAddressARB != NULL)
897                 p = (void *) qglXGetProcAddressARB(name);
898         if (p == NULL)
899                 p = (void *) dlsym(prjobj, name);
900         return p;
901 }