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