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