]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_glx.c
fix bug with rtlights on vertex texture blend surfaces (such as 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 static void IN_Activate (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                         IN_Activate(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         if (vidx11_display)
519         {
520                 IN_Activate(false);
521                 VID_RestoreSystemGamma();
522
523                 // FIXME: glXDestroyContext here?
524                 if (vid_isfullscreen)
525                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
526                 if (win)
527                         XDestroyWindow(vidx11_display, win);
528                 XCloseDisplay(vidx11_display);
529         }
530         vid_hidden = true;
531         vid_isfullscreen = false;
532         vidx11_display = NULL;
533         win = 0;
534         ctx = NULL;
535
536         GL_CloseLibrary();
537         Key_ClearStates ();
538 }
539
540 void signal_handler(int sig)
541 {
542         Con_Printf("Received signal %d, exiting...\n", sig);
543         VID_RestoreSystemGamma();
544         Sys_Quit(1);
545 }
546
547 void InitSig(void)
548 {
549         signal(SIGHUP, signal_handler);
550         signal(SIGINT, signal_handler);
551         signal(SIGQUIT, signal_handler);
552         signal(SIGILL, signal_handler);
553         signal(SIGTRAP, signal_handler);
554         signal(SIGIOT, signal_handler);
555         signal(SIGBUS, signal_handler);
556         signal(SIGFPE, signal_handler);
557         signal(SIGSEGV, signal_handler);
558         signal(SIGTERM, signal_handler);
559 }
560
561 void VID_Finish (qboolean allowmousegrab)
562 {
563         qboolean vid_usemouse;
564
565         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
566         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
567         {
568                 vid_usingvsync = vid_usevsync;
569                 if (qglXSwapIntervalSGI (vid_usevsync))
570                         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");
571         }
572
573         // handle the mouse state when windowed if that's changed
574         vid_usemouse = false;
575         if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
576                 vid_usemouse = true;
577         if (!vid_activewindow)
578                 vid_usemouse = false;
579         if (vid_isfullscreen)
580                 vid_usemouse = true;
581         IN_Activate(vid_usemouse);
582
583         if (r_render.integer)
584         {
585                 CHECKGLERROR
586                 if (r_speeds.integer || gl_finish.integer)
587                 {
588                         qglFinish();CHECKGLERROR
589                 }
590                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
591         }
592
593         if (vid_x11_hardwaregammasupported)
594                 VID_UpdateGamma(false, vid_x11_gammarampsize);
595 }
596
597 int VID_SetGamma(unsigned short *ramps, int rampsize)
598 {
599         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
600 }
601
602 int VID_GetGamma(unsigned short *ramps, int rampsize)
603 {
604         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
605 }
606
607 void VID_Init(void)
608 {
609 #if !defined(__APPLE__) && !defined(SUNOS)
610         Cvar_RegisterVariable (&vid_dgamouse);
611 #endif
612         InitSig(); // trap evil signals
613 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
614         if (COM_CheckParm ("-nomouse"))
615                 mouse_avail = false;
616 }
617
618 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
619 {
620         *attrib++ = GLX_RGBA;
621         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
622         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
623         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
624         *attrib++ = GLX_DOUBLEBUFFER;
625         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
626         // if stencil is enabled, ask for alpha too
627         if (stencil)
628         {
629                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
630                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
631         }
632         if (stereobuffer)
633                 *attrib++ = GLX_STEREO;
634         if (samples > 1)
635         {
636                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
637                 *attrib++ = 1;
638                 *attrib++ = GLX_SAMPLES_ARB;
639                 *attrib++ = samples;
640         }
641         *attrib++ = None;
642 }
643
644 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
645 {
646         int i;
647         int attrib[32];
648         XSetWindowAttributes attr;
649         XClassHint *clshints;
650         XWMHints *wmhints;
651         XSizeHints *szhints;
652         unsigned long mask;
653         Window root;
654         XVisualInfo *visinfo;
655         int MajorVersion, MinorVersion;
656         const char *drivername;
657
658 #if defined(__APPLE__) && defined(__MACH__)
659         drivername = "/usr/X11R6/lib/libGL.1.dylib";
660 #else
661         drivername = "libGL.so.1";
662 #endif
663 // 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
664 // 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
665 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
666         i = COM_CheckParm("-gl_driver");
667         if (i && i < com_argc - 1)
668                 drivername = com_argv[i + 1];
669         if (!GL_OpenLibrary(drivername))
670         {
671                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
672                 return false;
673         }
674
675         if (!(vidx11_display = XOpenDisplay(NULL)))
676         {
677                 Con_Print("Couldn't open the X display\n");
678                 return false;
679         }
680
681         vidx11_screen = DefaultScreen(vidx11_display);
682         root = RootWindow(vidx11_display, vidx11_screen);
683
684         // Get video mode list
685         MajorVersion = MinorVersion = 0;
686         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
687                 vidmode_ext = false;
688         else
689         {
690                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
691                 vidmode_ext = true;
692         }
693
694         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
695          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
696          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
697          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
698          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
699          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
700         {
701                 Con_Printf("glX functions not found in %s\n", gl_driver);
702                 return false;
703         }
704
705         VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, samples);
706         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
707         if (!visinfo && (samples == 1))
708         {
709                 /* Some Mesa drivers reject sample buffers with 1 sample, so try
710                  * entirely without one */
711                 VID_BuildGLXAttrib(attrib, bpp == 32, stereobuffer, 0);
712                 visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
713         }
714         if (!visinfo)
715         {
716                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
717                 return false;
718         }
719
720         if (vidmode_ext)
721         {
722                 int best_fit, best_dist, dist, x, y;
723
724                 // Are we going fullscreen?  If so, let's change video mode
725                 if (fullscreen)
726                 {
727                         XF86VidModeModeLine *current_vidmode;
728                         XF86VidModeModeInfo **vidmodes;
729                         int num_vidmodes;
730
731                         // This nice hack comes from the SDL source code
732                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
733                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
734
735                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
736                         best_dist = 9999999;
737                         best_fit = -1;
738
739                         for (i = 0; i < num_vidmodes; i++)
740                         {
741                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
742                                         continue;
743
744                                 x = width - vidmodes[i]->hdisplay;
745                                 y = height - vidmodes[i]->vdisplay;
746                                 dist = (x * x) + (y * y);
747                                 if (dist < best_dist)
748                                 {
749                                         best_dist = dist;
750                                         best_fit = i;
751                                 }
752                         }
753
754                         if (best_fit != -1)
755                         {
756                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
757                                 // to width/height =, so the window will take the full area of
758                                 // the mode chosen
759                                 width = vidmodes[best_fit]->hdisplay;
760                                 height = vidmodes[best_fit]->vdisplay;
761
762                                 // change to the mode
763                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
764                                 vid_isfullscreen = true;
765
766                                 // Move the viewport to top left
767                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
768                         }
769                         else
770                                 fullscreen = 0;
771
772                         free(vidmodes);
773                 }
774         }
775
776         // LordHavoc: save the visual for use in gamma ramp settings later
777         vidx11_visual = visinfo->visual;
778
779         /* window attributes */
780         attr.background_pixel = 0;
781         attr.border_pixel = 0;
782         // LordHavoc: save the colormap for later, too
783         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
784         attr.event_mask = X_MASK;
785         if (vid_isfullscreen)
786         {
787                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
788                 attr.override_redirect = True;
789                 attr.backing_store = NotUseful;
790                 attr.save_under = False;
791         }
792         else
793                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
794
795         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
796
797         wmhints = XAllocWMHints();
798         if(XpmCreatePixmapFromData(vidx11_display, win,
799                 (gamemode == GAME_NEXUIZ) ? nexuiz_xpm : darkplaces_xpm,
800                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
801                 wmhints->flags |= IconPixmapHint | IconMaskHint;
802
803         clshints = XAllocClassHint();
804         clshints->res_name = strdup(gamename);
805         clshints->res_class = strdup("DarkPlaces");
806
807         szhints = XAllocSizeHints();
808         if(vid_resizable.integer == 0)
809         {
810                 szhints->min_width = szhints->max_width = width;
811                 szhints->min_height = szhints->max_height = height;
812                 szhints->flags |= PMinSize | PMaxSize;
813         }
814
815         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
816         XFree(clshints);
817         XFree(wmhints);
818         XFree(szhints);
819         //XStoreName(vidx11_display, win, gamename);
820         XMapWindow(vidx11_display, win);
821
822         // LordHavoc: making the close button on a window do the right thing
823         // seems to involve this mess, sigh...
824         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
825         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
826
827         if (vid_isfullscreen)
828         {
829                 XMoveWindow(vidx11_display, win, 0, 0);
830                 XRaiseWindow(vidx11_display, win);
831                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
832                 XFlush(vidx11_display);
833                 // Move the viewport to top left
834                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
835         }
836
837         //XSync(vidx11_display, False);
838
839         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
840         if (!ctx)
841         {
842                 Con_Printf ("glXCreateContext failed\n");
843                 return false;
844         }
845
846         if (!qglXMakeCurrent(vidx11_display, win, ctx))
847         {
848                 Con_Printf ("glXMakeCurrent failed\n");
849                 return false;
850         }
851
852         XSync(vidx11_display, False);
853
854         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
855         {
856                 Con_Printf ("glGetString not found in %s\n", gl_driver);
857                 return false;
858         }
859
860         gl_renderer = (const char *)qglGetString(GL_RENDERER);
861         gl_vendor = (const char *)qglGetString(GL_VENDOR);
862         gl_version = (const char *)qglGetString(GL_VERSION);
863         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
864         gl_platform = "GLX";
865         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
866
867         if (!gl_extensions)
868                 gl_extensions = "";
869         if (!gl_platformextensions)
870                 gl_platformextensions = "";
871
872         Con_DPrintf("GL_VENDOR: %s\n", gl_vendor);
873         Con_DPrintf("GL_RENDERER: %s\n", gl_renderer);
874         Con_DPrintf("GL_VERSION: %s\n", gl_version);
875         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
876         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
877
878         gl_videosyncavailable = false;
879
880 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
881 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
882 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
883         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
884 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
885 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
886 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
887         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
888
889         vid_usingmouse = false;
890         vid_usingvsync = false;
891         vid_hidden = false;
892         vid_activewindow = true;
893         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
894 #if !defined(__APPLE__) && !defined(SUNOS)
895         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
896         if (!vid_x11_dgasupported)
897                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
898 #endif
899         GL_Init();
900         return true;
901 }
902
903 void Sys_SendKeyEvents(void)
904 {
905         static qboolean sound_active = true;
906
907         // enable/disable sound on focus gain/loss
908         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
909         {
910                 if (!sound_active)
911                 {
912                         S_UnblockSound ();
913                         sound_active = true;
914                 }
915         }
916         else
917         {
918                 if (sound_active)
919                 {
920                         S_BlockSound ();
921                         sound_active = false;
922                 }
923         }
924
925         HandleEvents();
926 }
927
928 void IN_Move (void)
929 {
930         if (mouse_avail)
931         {
932                 in_mouse_x = mouse_x;
933                 in_mouse_y = mouse_y;
934         }
935         mouse_x = 0;
936         mouse_y = 0;
937 }