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