]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_glx.c
XShm and pthreads support for vid_glx dpsoftrast
[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 #include "dpsoftrast.h"
32
33 #include <X11/keysym.h>
34 #include <X11/cursorfont.h>
35 #include <X11/xpm.h>
36
37 #include <X11/extensions/XShm.h>
38 #if !defined(__APPLE__) && !defined(__MACH__) && !defined(SUNOS)
39 #include <X11/extensions/xf86dga.h>
40 #endif
41 #include <X11/extensions/xf86vmode.h>
42
43 #include <sys/ipc.h>
44 #include <sys/shm.h>
45 #include <X11/extensions/XShm.h>
46
47 // get the Uchar type
48 #include "utf8lib.h"
49 #include "image.h"
50
51 #include "nexuiz.xpm"
52 #include "darkplaces.xpm"
53
54 // Tell startup code that we have a client
55 int cl_available = true;
56
57 // note: if we used the XRandR extension we could support refresh rates
58 qboolean vid_supportrefreshrate = false;
59
60 //GLX prototypes
61 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
62 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
63 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
64 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
65 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
66 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
67
68 //GLX_ARB_get_proc_address
69 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
70
71 static dllfunction_t getprocaddressfuncs[] =
72 {
73         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
74         {NULL, NULL}
75 };
76
77 //GLX_SGI_swap_control
78 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
79
80 static dllfunction_t swapcontrolfuncs[] =
81 {
82         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
83         {NULL, NULL}
84 };
85
86 static Display *vidx11_display = NULL;
87 static int vidx11_screen;
88 static Window win, root;
89 static GLXContext ctx = NULL;
90 static GC vidx11_gc = NULL;
91 static XImage *vidx11_ximage[2] = { NULL, NULL };
92 static int vidx11_ximage_pos;
93 static XShmSegmentInfo vidx11_shminfo[2];
94 static int vidx11_shmevent = -1;
95 static int vidx11_shmwait = 0; // number of frames outstanding
96
97 Atom wm_delete_window_atom;
98 Atom net_wm_state_atom;
99 Atom net_wm_state_hidden_atom;
100 Atom net_wm_state_fullscreen_atom;
101 Atom net_wm_icon;
102 Atom cardinal;
103
104 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
105 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
106                     PointerMotionMask | ButtonMotionMask)
107 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
108                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
109                 LeaveWindowMask)
110
111
112 static qboolean mouse_avail = true;
113 static qboolean vid_usingmousegrab = false;
114 static qboolean vid_usingmouse = false;
115 static qboolean vid_usinghidecursor = false;
116 static qboolean vid_usingvsync = false;
117 static qboolean vid_usevsync = false;
118 static qboolean vid_x11_hardwaregammasupported = false;
119 static qboolean vid_x11_dgasupported = false;
120 static int vid_x11_gammarampsize = 0;
121
122 #if !defined(__APPLE__) && !defined(SUNOS)
123 cvar_t vid_dgamouse = {CVAR_SAVE, "vid_dgamouse", "0", "make use of DGA mouse input"};
124 static qboolean vid_usingdgamouse = false;
125 #endif
126 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"};
127
128 qboolean vidmode_ext = false;
129
130 static int win_x, win_y;
131
132 static XF86VidModeModeInfo init_vidmode, game_vidmode;
133 static qboolean vid_isfullscreen = false;
134 static qboolean vid_isvidmodefullscreen = false;
135 static qboolean vid_isnetwmfullscreen = false;
136 static qboolean vid_isoverrideredirect = false;
137
138 static Visual *vidx11_visual;
139 static Colormap vidx11_colormap;
140
141 /*-----------------------------------------------------------------------*/
142 //
143
144 long keysym2ucs(KeySym keysym);
145 void DP_Xutf8LookupString(XKeyEvent * ev,
146                          Uchar *uch,
147                          KeySym * keysym_return,
148                          Status * status_return)
149 {
150         int rc;
151         KeySym keysym;
152         int codepoint;
153         char buffer[64];
154         int nbytes = sizeof(buffer);
155
156         rc = XLookupString(ev, buffer, nbytes, &keysym, NULL);
157
158         if (rc > 0) {
159                 codepoint = buffer[0] & 0xFF;
160         } else {
161                 codepoint = keysym2ucs(keysym);
162         }
163
164         if (codepoint < 0) {
165                 if (keysym == None) {
166                         *status_return = XLookupNone;
167                 } else {
168                         *status_return = XLookupKeySym;
169                         *keysym_return = keysym;
170                 }
171                 *uch = 0;
172                 return;
173         }
174
175         *uch = codepoint;
176
177         if (keysym != None) {
178                 *keysym_return = keysym;
179                 *status_return = XLookupBoth;
180         } else {
181                 *status_return = XLookupChars;
182         }
183 }
184 static int XLateKey(XKeyEvent *ev, Uchar *ascii)
185 {
186         int key = 0;
187         //char buf[64];
188         KeySym keysym, shifted;
189         Status status;
190
191         keysym = XLookupKeysym (ev, 0);
192         DP_Xutf8LookupString(ev, ascii, &shifted, &status);
193
194         switch(keysym)
195         {
196                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
197                 case XK_Page_Up:         key = K_PGUP; break;
198
199                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
200                 case XK_Page_Down:       key = K_PGDN; break;
201
202                 case XK_KP_Home: key = K_KP_HOME; break;
203                 case XK_Home:    key = K_HOME; break;
204
205                 case XK_KP_End:  key = K_KP_END; break;
206                 case XK_End:     key = K_END; break;
207
208                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
209                 case XK_Left:    key = K_LEFTARROW; break;
210
211                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
212                 case XK_Right:  key = K_RIGHTARROW;             break;
213
214                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
215                 case XK_Down:    key = K_DOWNARROW; break;
216
217                 case XK_KP_Up:   key = K_KP_UPARROW; break;
218                 case XK_Up:              key = K_UPARROW;        break;
219
220                 case XK_Escape: key = K_ESCAPE;         break;
221
222                 case XK_KP_Enter: key = K_KP_ENTER;     break;
223                 case XK_Return: key = K_ENTER;           break;
224
225                 case XK_Tab:            key = K_TAB;                     break;
226
227                 case XK_F1:              key = K_F1;                            break;
228
229                 case XK_F2:              key = K_F2;                            break;
230
231                 case XK_F3:              key = K_F3;                            break;
232
233                 case XK_F4:              key = K_F4;                            break;
234
235                 case XK_F5:              key = K_F5;                            break;
236
237                 case XK_F6:              key = K_F6;                            break;
238
239                 case XK_F7:              key = K_F7;                            break;
240
241                 case XK_F8:              key = K_F8;                            break;
242
243                 case XK_F9:              key = K_F9;                            break;
244
245                 case XK_F10:            key = K_F10;                     break;
246
247                 case XK_F11:            key = K_F11;                     break;
248
249                 case XK_F12:            key = K_F12;                     break;
250
251                 case XK_BackSpace: key = K_BACKSPACE; break;
252
253                 case XK_KP_Delete: key = K_KP_DEL; break;
254                 case XK_Delete: key = K_DEL; break;
255
256                 case XK_Pause:  key = K_PAUSE;           break;
257
258                 case XK_Shift_L:
259                 case XK_Shift_R:        key = K_SHIFT;          break;
260
261                 case XK_Execute:
262                 case XK_Control_L:
263                 case XK_Control_R:      key = K_CTRL;            break;
264
265                 case XK_Alt_L:
266                 case XK_Meta_L:
267                 case XK_ISO_Level3_Shift:
268                 case XK_Alt_R:
269                 case XK_Meta_R: key = K_ALT;                    break;
270
271                 case XK_KP_Begin: key = K_KP_5; break;
272
273                 case XK_Insert:key = K_INS; break;
274                 case XK_KP_Insert: key = K_KP_INS; break;
275
276                 case XK_KP_Multiply: key = K_KP_MULTIPLY; break;
277                 case XK_KP_Add:  key = K_KP_PLUS; break;
278                 case XK_KP_Subtract: key = K_KP_MINUS; break;
279                 case XK_KP_Divide: key = K_KP_SLASH; break;
280
281                 case XK_section:        key = '~'; break;
282
283                 default:
284                         if (keysym < 32)
285                                 break;
286
287                         if (keysym >= 'A' && keysym <= 'Z')
288                                 key = keysym - 'A' + 'a';
289                         else
290                                 key = keysym;
291
292                         break;
293         }
294
295         return key;
296 }
297
298 static Cursor CreateNullCursor(Display *display, Window root)
299 {
300         Pixmap cursormask;
301         XGCValues xgc;
302         GC gc;
303         XColor dummycolour;
304         Cursor cursor;
305
306         cursormask = XCreatePixmap(display, root, 1, 1, 1);
307         xgc.function = GXclear;
308         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
309         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
310         dummycolour.pixel = 0;
311         dummycolour.red = 0;
312         dummycolour.flags = 04;
313         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
314         XFreePixmap(display,cursormask);
315         XFreeGC(display,gc);
316         return cursor;
317 }
318
319 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
320 {
321         static int originalmouseparms_num;
322         static int originalmouseparms_denom;
323         static int originalmouseparms_threshold;
324         static qboolean restore_spi;
325
326 #if !defined(__APPLE__) && !defined(SUNOS)
327         qboolean usedgamouse;
328 #endif
329
330         if (!vidx11_display || !win)
331                 return;
332
333         if (relative)
334                 fullscreengrab = true;
335
336         if (!mouse_avail)
337                 fullscreengrab = relative = hidecursor = false;
338
339 #if !defined(__APPLE__) && !defined(SUNOS)
340         usedgamouse = relative && vid_dgamouse.integer;
341         if (!vid_x11_dgasupported)
342                 usedgamouse = false;
343         if (fullscreengrab && vid_usingmouse && (vid_usingdgamouse != usedgamouse))
344                 VID_SetMouse(false, false, false); // ungrab first!
345 #endif
346
347         if (vid_usingmousegrab != fullscreengrab)
348         {
349                 vid_usingmousegrab = fullscreengrab;
350                 cl_ignoremousemoves = 2;
351                 if (fullscreengrab)
352                 {
353                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
354                         if (vid_grabkeyboard.integer || vid_isoverrideredirect)
355                                 XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
356                 }
357                 else
358                 {
359                         XUngrabPointer(vidx11_display, CurrentTime);
360                         XUngrabKeyboard(vidx11_display, CurrentTime);
361                 }
362         }
363
364         if (relative)
365         {
366                 if (!vid_usingmouse)
367                 {
368                         XWindowAttributes attribs_1;
369                         XSetWindowAttributes attribs_2;
370
371                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
372                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
373                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
374
375 #if !defined(__APPLE__) && !defined(SUNOS)
376                         vid_usingdgamouse = usedgamouse;
377                         if (usedgamouse)
378                         {
379                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
380                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
381                         }
382                         else
383 #endif
384                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
385
386 // COMMANDLINEOPTION: X11 Input: -noforcemparms disables setting of mouse parameters (not used with DGA, windows only)
387 #if !defined(__APPLE__) && !defined(SUNOS)
388                         if (!COM_CheckParm ("-noforcemparms") && !usedgamouse)
389 #else
390                         if (!COM_CheckParm ("-noforcemparms"))
391 #endif
392                         {
393                                 XGetPointerControl(vidx11_display, &originalmouseparms_num, &originalmouseparms_denom, &originalmouseparms_threshold);
394                                 XChangePointerControl (vidx11_display, true, false, 1, 1, -1); // TODO maybe change threshold here, or remove this comment
395                                 restore_spi = true;
396                         }
397                         else
398                                 restore_spi = false;
399
400                         cl_ignoremousemoves = 2;
401                         vid_usingmouse = true;
402                 }
403         }
404         else
405         {
406                 if (vid_usingmouse)
407                 {
408 #if !defined(__APPLE__) && !defined(SUNOS)
409                         if (vid_usingdgamouse)
410                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
411                         vid_usingdgamouse = false;
412 #endif
413                         cl_ignoremousemoves = 2;
414
415                         if (restore_spi)
416                                 XChangePointerControl (vidx11_display, true, true, originalmouseparms_num, originalmouseparms_denom, originalmouseparms_threshold);
417                         restore_spi = false;
418
419                         vid_usingmouse = false;
420                 }
421         }
422
423         if (vid_usinghidecursor != hidecursor)
424         {
425                 vid_usinghidecursor = hidecursor;
426                 if (hidecursor)
427                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
428                 else
429                         XUndefineCursor(vidx11_display, win);
430         }
431 }
432
433 static keynum_t buttonremap[18] =
434 {
435         K_MOUSE1,
436         K_MOUSE3,
437         K_MOUSE2,
438         K_MWHEELUP,
439         K_MWHEELDOWN,
440         K_MOUSE4,
441         K_MOUSE5,
442         K_MOUSE6,
443         K_MOUSE7,
444         K_MOUSE8,
445         K_MOUSE9,
446         K_MOUSE10,
447         K_MOUSE11,
448         K_MOUSE12,
449         K_MOUSE13,
450         K_MOUSE14,
451         K_MOUSE15,
452         K_MOUSE16,
453 };
454
455 static qboolean BuildXImages(int w, int h)
456 {
457         int i;
458         if(vidx11_shmevent >= 0)
459         {
460                 for(i = 0; i < 2; ++i)
461                 {
462                         vidx11_shminfo[i].shmid = -1;
463                         vidx11_ximage[i] = XShmCreateImage(vidx11_display, vidx11_visual, DefaultDepth(vidx11_display, vidx11_screen), ZPixmap, NULL, &vidx11_shminfo[i], w, h);
464                         if(!vidx11_ximage[i])
465                         {
466                                 Con_Printf("Failed to get an XImage segment\n");
467                                 VID_Shutdown();
468                                 return false;
469                         }
470                         vidx11_shminfo[i].shmid = shmget(IPC_PRIVATE, vidx11_ximage[i]->bytes_per_line * vidx11_ximage[i]->height, IPC_CREAT|0777);
471                         if(vidx11_shminfo[i].shmid < 0)
472                         {
473                                 Con_Printf("Failed to get a shm segment\n");
474                                 VID_Shutdown();
475                                 return false;
476                         }
477                         vidx11_shminfo[i].shmaddr = vidx11_ximage[i]->data = shmat(vidx11_shminfo[i].shmid, NULL, 0);
478                         if(!vidx11_shminfo[i].shmaddr)
479                         {
480                                 Con_Printf("Failed to get a shm segment addresst\n");
481                                 VID_Shutdown();
482                                 return false;
483                         }
484                         vidx11_shminfo[i].readOnly = True;
485                         XShmAttach(vidx11_display, &vidx11_shminfo[i]);
486                 }
487         }
488         else
489         {
490                 for(i = 0; i < 2; ++i)
491                 {
492                         char *p = calloc(4, w * h);
493                         vidx11_shminfo[i].shmid = -1;
494                         vidx11_ximage[i] = XCreateImage(vidx11_display, vidx11_visual, DefaultDepth(vidx11_display, vidx11_screen), ZPixmap, 0, (char*)p, w, h, 8, 0);
495                         if(!vidx11_ximage[i])
496                         {
497                                 Con_Printf("Failed to get an XImage segment\n");
498                                 VID_Shutdown();
499                                 return false;
500                         }
501                 }
502         }
503         return true;
504 }
505 static void DestroyXImages(void)
506 {
507         int i;
508         for(i = 0; i < 2; ++i)
509         {
510                 if(vidx11_shminfo[i].shmid >= 0)
511                 {
512                         XShmDetach(vidx11_display, &vidx11_shminfo[i]);
513                         XDestroyImage(vidx11_ximage[i]);
514                         vidx11_ximage[i] = NULL;
515                         shmdt(vidx11_shminfo[i].shmaddr);
516                         shmctl(vidx11_shminfo[i].shmid, IPC_RMID, 0);
517                         vidx11_shminfo[i].shmid = -1;
518                 }
519                 if(vidx11_ximage[i])
520                         XDestroyImage(vidx11_ximage[i]);
521                 vidx11_ximage[i] = 0;
522         }
523 }
524
525 static int in_mouse_x_save = 0, in_mouse_y_save = 0;
526 static void HandleEvents(void)
527 {
528         XEvent event;
529         int key;
530         Uchar unicode;
531         qboolean dowarp = false;
532
533         if (!vidx11_display)
534                 return;
535
536         in_mouse_x += in_mouse_x_save;
537         in_mouse_y += in_mouse_y_save;
538         in_mouse_x_save = 0;
539         in_mouse_y_save = 0;
540
541         while (XPending(vidx11_display))
542         {
543                 XNextEvent(vidx11_display, &event);
544
545                 switch (event.type)
546                 {
547                 case KeyPress:
548                         // key pressed
549                         key = XLateKey (&event.xkey, &unicode);
550                         Key_Event(key, unicode, true);
551                         break;
552
553                 case KeyRelease:
554                         // key released
555                         key = XLateKey (&event.xkey, &unicode);
556                         Key_Event(key, unicode, false);
557                         break;
558
559                 case MotionNotify:
560                         // mouse moved
561                         if (vid_usingmouse)
562                         {
563 #if !defined(__APPLE__) && !defined(SUNOS)
564                                 if (vid_usingdgamouse)
565                                 {
566                                         in_mouse_x += event.xmotion.x_root;
567                                         in_mouse_y += event.xmotion.y_root;
568                                 }
569                                 else
570 #endif
571                                 {
572                                         if (!event.xmotion.send_event)
573                                         {
574                                                 in_mouse_x += event.xmotion.x - in_windowmouse_x;
575                                                 in_mouse_y += event.xmotion.y - in_windowmouse_y;
576                                                 //if (abs(vid.width/2 - event.xmotion.x) + abs(vid.height/2 - event.xmotion.y))
577                                                 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)
578                                                         dowarp = true;
579                                         }
580                                 }
581                         }
582                         in_windowmouse_x = event.xmotion.x;
583                         in_windowmouse_y = event.xmotion.y;
584                         break;
585
586                 case ButtonPress:
587                         // mouse button pressed
588                         if (event.xbutton.button <= 18)
589                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, true);
590                         else
591                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-18 expected\n", event.xbutton.button);
592                         break;
593
594                 case ButtonRelease:
595                         // mouse button released
596                         if (event.xbutton.button <= 18)
597                                 Key_Event(buttonremap[event.xbutton.button - 1], 0, false);
598                         else
599                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-18 expected\n", event.xbutton.button);
600                         break;
601
602                 case CreateNotify:
603                         // window created
604                         win_x = event.xcreatewindow.x;
605                         win_y = event.xcreatewindow.y;
606                         break;
607
608                 case ConfigureNotify:
609                         // window changed size/location
610                         win_x = event.xconfigure.x;
611                         win_y = event.xconfigure.y;
612                         if((vid_resizable.integer < 2 || vid_isnetwmfullscreen) && (vid.width != event.xconfigure.width || vid.height != event.xconfigure.height))
613                         {
614                                 vid.width = event.xconfigure.width;
615                                 vid.height = event.xconfigure.height;
616                                 if(vid_isnetwmfullscreen)
617                                         Con_Printf("NetWM fullscreen: actually using resolution %dx%d\n", vid.width, vid.height);
618                                 else
619                                         Con_DPrintf("Updating to ConfigureNotify resolution %dx%d\n", vid.width, vid.height);
620
621                                 DPSOFTRAST_Flush();
622
623                                 if(vid.softdepthpixels)
624                                         free(vid.softdepthpixels);
625
626                                 DestroyXImages();
627                                 XSync(vidx11_display, False);
628                                 if(!BuildXImages(vid.width, vid.height))
629                                         return;
630                                 XSync(vidx11_display, False);
631
632                                 vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
633                                 vid.softdepthpixels = (unsigned int *)calloc(4, vid.width * vid.height);
634                         }
635                         break;
636                 case DestroyNotify:
637                         // window has been destroyed
638                         Sys_Quit(0);
639                         break;
640                 case ClientMessage:
641                         // window manager messages
642                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
643                                 Sys_Quit(0);
644                         break;
645                 case MapNotify:
646                         if (vid_isoverrideredirect)
647                                 break;
648                         // window restored
649                         vid_hidden = false;
650                         VID_RestoreSystemGamma();
651
652                         if(vid_isvidmodefullscreen)
653                         {
654                                 // set our video mode
655                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &game_vidmode);
656
657                                 // Move the viewport to top left
658                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
659                         }
660
661                         if(vid_isnetwmfullscreen)
662                         {
663                                 // make sure it's fullscreen
664                                 XEvent event;
665                                 event.type = ClientMessage;
666                                 event.xclient.serial = 0;
667                                 event.xclient.send_event = True;
668                                 event.xclient.message_type = net_wm_state_atom;
669                                 event.xclient.window = win;
670                                 event.xclient.format = 32;
671                                 event.xclient.data.l[0] = 1;
672                                 event.xclient.data.l[1] = net_wm_state_fullscreen_atom;
673                                 event.xclient.data.l[2] = 0;
674                                 event.xclient.data.l[3] = 1;
675                                 event.xclient.data.l[4] = 0;
676                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
677                         }
678
679                         dowarp = true;
680
681                         break;
682                 case UnmapNotify:
683                         if (vid_isoverrideredirect)
684                                 break;
685                         // window iconified/rolledup/whatever
686                         vid_hidden = true;
687                         VID_RestoreSystemGamma();
688
689                         if(vid_isvidmodefullscreen)
690                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
691
692                         break;
693                 case FocusIn:
694                         if (vid_isoverrideredirect)
695                                 break;
696                         // window is now the input focus
697                         vid_activewindow = true;
698                         break;
699                 case FocusOut:
700                         if (vid_isoverrideredirect)
701                                 break;
702
703                         if(vid_isnetwmfullscreen && event.xfocus.mode == NotifyNormal)
704                         {
705                                 // iconify netwm fullscreen window when it loses focus
706                                 // when the user selects it in the taskbar, the window manager will map it again and send MapNotify
707                                 XEvent event;
708                                 event.type = ClientMessage;
709                                 event.xclient.serial = 0;
710                                 event.xclient.send_event = True;
711                                 event.xclient.message_type = net_wm_state_atom;
712                                 event.xclient.window = win;
713                                 event.xclient.format = 32;
714                                 event.xclient.data.l[0] = 1;
715                                 event.xclient.data.l[1] = net_wm_state_hidden_atom;
716                                 event.xclient.data.l[2] = 0;
717                                 event.xclient.data.l[3] = 1;
718                                 event.xclient.data.l[4] = 0;
719                                 XSendEvent(vidx11_display, root, False, SubstructureRedirectMask | SubstructureNotifyMask, &event);
720                         }
721
722                         // window is no longer the input focus
723                         vid_activewindow = false;
724                         VID_RestoreSystemGamma();
725
726                         break;
727                 case EnterNotify:
728                         // mouse entered window
729                         break;
730                 case LeaveNotify:
731                         // mouse left window
732                         break;
733                 default:
734                         if(vidx11_shmevent >= 0 && event.type == vidx11_shmevent)
735                                 --vidx11_shmwait;
736                         break;
737                 }
738         }
739
740         if (dowarp)
741         {
742                 /* move the mouse to the window center again */
743                 // we'll catch the warp motion by its send_event flag, updating the
744                 // stored mouse position without adding any delta motion
745                 XEvent event;
746                 event.type = MotionNotify;
747                 event.xmotion.display = vidx11_display;
748                 event.xmotion.window = win;
749                 event.xmotion.x = vid.width / 2;
750                 event.xmotion.y = vid.height / 2;
751                 XSendEvent(vidx11_display, win, False, PointerMotionMask, &event);
752                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, vid.width / 2, vid.height / 2);
753         }
754 }
755
756 static void *prjobj = NULL;
757
758 static void GL_CloseLibrary(void)
759 {
760         if (prjobj)
761                 dlclose(prjobj);
762         prjobj = NULL;
763         gl_driver[0] = 0;
764         qglXGetProcAddressARB = NULL;
765         gl_extensions = "";
766         gl_platform = "";
767         gl_platformextensions = "";
768 }
769
770 static int GL_OpenLibrary(const char *name)
771 {
772         Con_Printf("Loading OpenGL driver %s\n", name);
773         GL_CloseLibrary();
774         if (!(prjobj = dlopen(name, RTLD_LAZY | RTLD_GLOBAL)))
775         {
776                 Con_Printf("Unable to open symbol list for %s\n", name);
777                 return false;
778         }
779         strlcpy(gl_driver, name, sizeof(gl_driver));
780         return true;
781 }
782
783 void *GL_GetProcAddress(const char *name)
784 {
785         void *p = NULL;
786         if (qglXGetProcAddressARB != NULL)
787                 p = (void *) qglXGetProcAddressARB((GLubyte *)name);
788         if (p == NULL)
789                 p = (void *) dlsym(prjobj, name);
790         return p;
791 }
792
793 void VID_Shutdown(void)
794 {
795         if (!ctx || !vidx11_display)
796                 return;
797
798         VID_SetMouse(false, false, false);
799         VID_RestoreSystemGamma();
800
801         // FIXME: glXDestroyContext here?
802         if (vid_isvidmodefullscreen)
803                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, &init_vidmode);
804
805         if(vidx11_gc)
806                 XFreeGC(vidx11_display, vidx11_gc);
807         vidx11_gc = NULL;
808
809         DestroyXImages();
810         vidx11_shmevent = -1;
811         vid.softpixels = NULL;
812
813         if (vid.softdepthpixels)
814                 free(vid.softdepthpixels);
815
816         if (win)
817                 XDestroyWindow(vidx11_display, win);
818         XCloseDisplay(vidx11_display);
819
820         vid_hidden = true;
821         vid_isfullscreen = false;
822         vid_isnetwmfullscreen = false;
823         vid_isvidmodefullscreen = false;
824         vid_isoverrideredirect = false;
825         vidx11_display = NULL;
826         win = 0;
827         ctx = NULL;
828
829         GL_CloseLibrary();
830         Key_ClearStates ();
831 }
832
833 void signal_handler(int sig)
834 {
835         Con_Printf("Received signal %d, exiting...\n", sig);
836         VID_RestoreSystemGamma();
837         Sys_Quit(1);
838 }
839
840 void InitSig(void)
841 {
842         signal(SIGHUP, signal_handler);
843         signal(SIGINT, signal_handler);
844         signal(SIGQUIT, signal_handler);
845         signal(SIGILL, signal_handler);
846         signal(SIGTRAP, signal_handler);
847         signal(SIGIOT, signal_handler);
848         signal(SIGBUS, signal_handler);
849         signal(SIGFPE, signal_handler);
850         signal(SIGSEGV, signal_handler);
851         signal(SIGTERM, signal_handler);
852 }
853
854 void VID_Finish (void)
855 {
856         vid_usevsync = vid_vsync.integer && !cls.timedemo && qglXSwapIntervalSGI;
857         switch(vid.renderpath)
858         {
859                 case RENDERPATH_SOFT:
860                         vidx11_ximage_pos = !vidx11_ximage_pos;
861                         vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
862                         DPSOFTRAST_SetRenderTargets(vid.width, vid.height, vid.softdepthpixels, vid.softpixels, NULL, NULL, NULL);
863
864                         if(vidx11_shmevent >= 0) {
865                                 // save mouse motion so we can deal with it later
866                                 in_mouse_x = 0;
867                                 in_mouse_y = 0;
868                                 while(vidx11_shmwait)
869                                         HandleEvents();
870                                 in_mouse_x_save += in_mouse_x;
871                                 in_mouse_y_save += in_mouse_y;
872                                 in_mouse_x = 0;
873                                 in_mouse_y = 0;
874
875                                 ++vidx11_shmwait;
876                                 XShmPutImage(vidx11_display, win, vidx11_gc, vidx11_ximage[!vidx11_ximage_pos], 0, 0, 0, 0, vid.width, vid.height, True);
877                         } else {
878                                 XPutImage(vidx11_display, win, vidx11_gc, vidx11_ximage[!vidx11_ximage_pos], 0, 0, 0, 0, vid.width, vid.height);
879                         }
880                         break;
881
882                 case RENDERPATH_GL11:
883                 case RENDERPATH_GL13:
884                 case RENDERPATH_GL20:
885                 case RENDERPATH_GLES2:
886                         if (vid_usingvsync != vid_usevsync)
887                         {
888                                 vid_usingvsync = vid_usevsync;
889                                 if (qglXSwapIntervalSGI (vid_usevsync))
890                                         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");
891                         }
892
893                         if (!vid_hidden)
894                         {
895                                 CHECKGLERROR
896                                 if (r_speeds.integer == 2 || gl_finish.integer)
897                                         GL_Finish();
898                                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
899                         }
900                         break;
901
902                 case RENDERPATH_D3D9:
903                 case RENDERPATH_D3D10:
904                 case RENDERPATH_D3D11:
905                         break;
906         }
907
908         if (vid_x11_hardwaregammasupported)
909                 VID_UpdateGamma(false, vid_x11_gammarampsize);
910 }
911
912 int VID_SetGamma(unsigned short *ramps, int rampsize)
913 {
914         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
915 }
916
917 int VID_GetGamma(unsigned short *ramps, int rampsize)
918 {
919         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
920 }
921
922 void VID_Init(void)
923 {
924 #if !defined(__APPLE__) && !defined(SUNOS)
925         Cvar_RegisterVariable (&vid_dgamouse);
926 #endif
927         Cvar_RegisterVariable (&vid_netwmfullscreen);
928         InitSig(); // trap evil signals
929 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
930         if (COM_CheckParm ("-nomouse"))
931                 mouse_avail = false;
932         vidx11_shminfo[0].shmid = -1;
933         vidx11_shminfo[1].shmid = -1;
934 }
935
936 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
937 {
938         *attrib++ = GLX_RGBA;
939         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
940         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
941         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
942         *attrib++ = GLX_DOUBLEBUFFER;
943         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
944         // if stencil is enabled, ask for alpha too
945         if (stencil)
946         {
947                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
948                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
949         }
950         if (stereobuffer)
951                 *attrib++ = GLX_STEREO;
952         if (samples > 1)
953         {
954                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
955                 *attrib++ = 1;
956                 *attrib++ = GLX_SAMPLES_ARB;
957                 *attrib++ = samples;
958         }
959         *attrib++ = None;
960 }
961
962 qboolean VID_InitModeSoft(viddef_mode_t *mode)
963 {
964         int i, j;
965         XSetWindowAttributes attr;
966         XClassHint *clshints;
967         XWMHints *wmhints;
968         XSizeHints *szhints;
969         unsigned long mask;
970         int MajorVersion, MinorVersion;
971         char *xpm;
972         char **idata;
973         unsigned char *data;
974         XGCValues gcval;
975         const char *dpyname;
976
977         vid_isfullscreen = false;
978         vid_isnetwmfullscreen = false;
979         vid_isvidmodefullscreen = false;
980         vid_isoverrideredirect = false;
981
982         if (!(vidx11_display = XOpenDisplay(NULL)))
983         {
984                 Con_Print("Couldn't open the X display\n");
985                 return false;
986         }
987         dpyname = XDisplayName(NULL);
988
989         // LordHavoc: making the close button on a window do the right thing
990         // seems to involve this mess, sigh...
991         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
992         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
993         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
994         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
995         net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
996         cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
997
998         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
999         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
1000
1001         vidx11_screen = DefaultScreen(vidx11_display);
1002         root = RootWindow(vidx11_display, vidx11_screen);
1003
1004         // Get video mode list
1005         MajorVersion = MinorVersion = 0;
1006         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
1007                 vidmode_ext = false;
1008         else
1009         {
1010                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
1011                 vidmode_ext = true;
1012         }
1013
1014         if (mode->fullscreen)
1015         {
1016                 if(vid_netwmfullscreen.integer)
1017                 {
1018                         // TODO detect WM support
1019                         vid_isnetwmfullscreen = true;
1020                         vid_isfullscreen = true;
1021                         // width and height will be filled in later
1022                         Con_DPrintf("Using NetWM fullscreen mode\n");
1023                 }
1024
1025                 if(!vid_isfullscreen && vidmode_ext)
1026                 {
1027                         int best_fit, best_dist, dist, x, y;
1028
1029                         // Are we going fullscreen?  If so, let's change video mode
1030                         XF86VidModeModeLine *current_vidmode;
1031                         XF86VidModeModeInfo **vidmodes;
1032                         int num_vidmodes;
1033
1034                         // This nice hack comes from the SDL source code
1035                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
1036                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
1037
1038                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1039                         best_dist = 0;
1040                         best_fit = -1;
1041
1042                         for (i = 0; i < num_vidmodes; i++)
1043                         {
1044                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
1045                                         continue;
1046
1047                                 x = mode->width - vidmodes[i]->hdisplay;
1048                                 y = mode->height - vidmodes[i]->vdisplay;
1049                                 dist = (x * x) + (y * y);
1050                                 if (best_fit == -1 || dist < best_dist)
1051                                 {
1052                                         best_dist = dist;
1053                                         best_fit = i;
1054                                 }
1055                         }
1056
1057                         if (best_fit != -1)
1058                         {
1059                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
1060                                 // to width/height =, so the window will take the full area of
1061                                 // the mode chosen
1062                                 mode->width = vidmodes[best_fit]->hdisplay;
1063                                 mode->height = vidmodes[best_fit]->vdisplay;
1064
1065                                 // change to the mode
1066                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
1067                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
1068                                 vid_isvidmodefullscreen = true;
1069                                 vid_isfullscreen = true;
1070
1071                                 // Move the viewport to top left
1072                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1073                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
1074                         }
1075
1076                         free(vidmodes);
1077                 }
1078
1079                 if(!vid_isfullscreen)
1080                 {
1081                         // sorry, no FS available
1082                         // use the full desktop resolution
1083                         vid_isfullscreen = true;
1084                         // width and height will be filled in later
1085                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
1086                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
1087                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
1088                 }
1089         }
1090
1091         // LordHavoc: save the visual for use in gamma ramp settings later
1092         vidx11_visual = DefaultVisual(vidx11_display, vidx11_screen);
1093
1094         /* window attributes */
1095         attr.background_pixel = 0;
1096         attr.border_pixel = 0;
1097         // LordHavoc: save the colormap for later, too
1098         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, vidx11_visual, AllocNone);
1099         attr.event_mask = X_MASK;
1100
1101         if (mode->fullscreen)
1102         {
1103                 if(vid_isnetwmfullscreen)
1104                 {
1105                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
1106                         attr.backing_store = NotUseful;
1107                         attr.save_under = False;
1108                 }
1109                 else
1110                 {
1111                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
1112                         attr.override_redirect = True;
1113                         attr.backing_store = NotUseful;
1114                         attr.save_under = False;
1115                         vid_isoverrideredirect = true; // so it knows to grab
1116                 }
1117         }
1118         else
1119         {
1120                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1121         }
1122
1123         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, CopyFromParent, InputOutput, vidx11_visual, mask, &attr);
1124
1125         data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1126         if(data)
1127         {
1128                 // use _NET_WM_ICON too
1129                 static long netwm_icon[MAX_NETWM_ICON];
1130                 int pos = 0;
1131                 int i = 1;
1132
1133                 while(data)
1134                 {
1135                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1136                         {
1137                                 netwm_icon[pos++] = image_width;
1138                                 netwm_icon[pos++] = image_height;
1139                                 for(i = 0; i < image_height; ++i)
1140                                         for(j = 0; j < image_width; ++j)
1141                                                 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1142                         }
1143                         else
1144                         {
1145                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1146                         }
1147                         ++i;
1148                         Mem_Free(data);
1149                         data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1150                 }
1151                 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1152         }
1153
1154         // fallthrough for old window managers
1155         xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1156         idata = NULL;
1157         if(xpm)
1158                 idata = XPM_DecodeString(xpm);
1159         if(!idata)
1160                 idata = ENGINE_ICON;
1161
1162         wmhints = XAllocWMHints();
1163         if(XpmCreatePixmapFromData(vidx11_display, win,
1164                 idata,
1165                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1166                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1167
1168         if(xpm)
1169                 Mem_Free(xpm);
1170
1171         clshints = XAllocClassHint();
1172         clshints->res_name = strdup(gamename);
1173         clshints->res_class = strdup("DarkPlaces");
1174
1175         szhints = XAllocSizeHints();
1176         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1177         {
1178                 szhints->min_width = szhints->max_width = mode->width;
1179                 szhints->min_height = szhints->max_height = mode->height;
1180                 szhints->flags |= PMinSize | PMaxSize;
1181         }
1182
1183         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1184         // strdup() allocates using malloc(), should be freed with free()
1185         free(clshints->res_name);
1186         free(clshints->res_class);
1187         XFree(clshints);
1188         XFree(wmhints);
1189         XFree(szhints);
1190
1191         //XStoreName(vidx11_display, win, gamename);
1192         XMapWindow(vidx11_display, win);
1193
1194         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1195
1196         if (vid_isoverrideredirect)
1197         {
1198                 XMoveWindow(vidx11_display, win, 0, 0);
1199                 XRaiseWindow(vidx11_display, win);
1200                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1201                 XFlush(vidx11_display);
1202         }
1203
1204         if(vid_isvidmodefullscreen)
1205         {
1206                 // Move the viewport to top left
1207                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1208         }
1209
1210         //XSync(vidx11_display, False);
1211
1212         // COMMANDLINEOPTION: Unix GLX: -noshm disables XShm extensioon
1213         if(dpyname && dpyname[0] == ':' && dpyname[1] && (dpyname[2] < '0' || dpyname[2] > '9') && !COM_CheckParm("-noshm") && XShmQueryExtension(vidx11_display))
1214         {
1215                 Con_Printf("Using XShm\n");
1216                 vidx11_shmevent = XShmGetEventBase(vidx11_display) + ShmCompletion;
1217         }
1218         else
1219         {
1220                 Con_Printf("Not using XShm\n");
1221                 vidx11_shmevent = -1;
1222         }
1223         BuildXImages(mode->width, mode->height);
1224
1225         vidx11_ximage_pos = 0;
1226         vid.softpixels = (unsigned int *) vidx11_ximage[vidx11_ximage_pos]->data;
1227         vidx11_shmwait = 0;
1228         vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1229
1230         memset(&gcval, 0, sizeof(gcval));
1231         vidx11_gc = XCreateGC(vidx11_display, win, 0, &gcval);
1232
1233         if (DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, vid_soft_interlace.integer, (unsigned int *)vid.softpixels, (unsigned int *)vid.softdepthpixels) < 0)
1234         {
1235                 Con_Printf("Failed to initialize software rasterizer\n");
1236                 VID_Shutdown();
1237                 return false;
1238         }
1239
1240         XSync(vidx11_display, False);
1241
1242         vid_usingmousegrab = false;
1243         vid_usingmouse = false;
1244         vid_usinghidecursor = false;
1245         vid_usingvsync = false;
1246         vid_hidden = false;
1247         vid_activewindow = true;
1248         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1249 #if !defined(__APPLE__) && !defined(SUNOS)
1250         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1251         if (!vid_x11_dgasupported)
1252                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1253 #endif
1254
1255         VID_Soft_SharedSetup();
1256
1257         return true;
1258 }
1259 qboolean VID_InitModeGL(viddef_mode_t *mode)
1260 {
1261         int i, j;
1262         int attrib[32];
1263         XSetWindowAttributes attr;
1264         XClassHint *clshints;
1265         XWMHints *wmhints;
1266         XSizeHints *szhints;
1267         unsigned long mask;
1268         XVisualInfo *visinfo;
1269         int MajorVersion, MinorVersion;
1270         const char *drivername;
1271         char *xpm;
1272         char **idata;
1273         unsigned char *data;
1274
1275         vid_isfullscreen = false;
1276         vid_isnetwmfullscreen = false;
1277         vid_isvidmodefullscreen = false;
1278         vid_isoverrideredirect = false;
1279
1280 #if defined(__APPLE__) && defined(__MACH__)
1281         drivername = "/usr/X11R6/lib/libGL.1.dylib";
1282 #else
1283         drivername = "libGL.so.1";
1284 #endif
1285 // 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
1286 // 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
1287 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
1288         i = COM_CheckParm("-gl_driver");
1289         if (i && i < com_argc - 1)
1290                 drivername = com_argv[i + 1];
1291         if (!GL_OpenLibrary(drivername))
1292         {
1293                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
1294                 return false;
1295         }
1296
1297         if (!(vidx11_display = XOpenDisplay(NULL)))
1298         {
1299                 Con_Print("Couldn't open the X display\n");
1300                 return false;
1301         }
1302
1303         // LordHavoc: making the close button on a window do the right thing
1304         // seems to involve this mess, sigh...
1305         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
1306         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
1307         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
1308         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
1309         net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
1310         cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
1311
1312         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
1313         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
1314
1315         vidx11_screen = DefaultScreen(vidx11_display);
1316         root = RootWindow(vidx11_display, vidx11_screen);
1317
1318         // Get video mode list
1319         MajorVersion = MinorVersion = 0;
1320         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
1321                 vidmode_ext = false;
1322         else
1323         {
1324                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
1325                 vidmode_ext = true;
1326         }
1327
1328         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
1329          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
1330          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
1331          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
1332          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
1333          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
1334         {
1335                 Con_Printf("glX functions not found in %s\n", gl_driver);
1336                 return false;
1337         }
1338
1339         VID_BuildGLXAttrib(attrib, mode->bitsperpixel == 32, mode->stereobuffer, mode->samples);
1340         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
1341         if (!visinfo)
1342         {
1343                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
1344                 return false;
1345         }
1346
1347         if (mode->fullscreen)
1348         {
1349                 if(vid_netwmfullscreen.integer)
1350                 {
1351                         // TODO detect WM support
1352                         vid_isnetwmfullscreen = true;
1353                         vid_isfullscreen = true;
1354                         // width and height will be filled in later
1355                         Con_DPrintf("Using NetWM fullscreen mode\n");
1356                 }
1357
1358                 if(!vid_isfullscreen && vidmode_ext)
1359                 {
1360                         int best_fit, best_dist, dist, x, y;
1361
1362                         // Are we going fullscreen?  If so, let's change video mode
1363                         XF86VidModeModeLine *current_vidmode;
1364                         XF86VidModeModeInfo **vidmodes;
1365                         int num_vidmodes;
1366
1367                         // This nice hack comes from the SDL source code
1368                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
1369                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
1370
1371                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1372                         best_dist = 0;
1373                         best_fit = -1;
1374
1375                         for (i = 0; i < num_vidmodes; i++)
1376                         {
1377                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
1378                                         continue;
1379
1380                                 x = mode->width - vidmodes[i]->hdisplay;
1381                                 y = mode->height - vidmodes[i]->vdisplay;
1382                                 dist = (x * x) + (y * y);
1383                                 if (best_fit == -1 || dist < best_dist)
1384                                 {
1385                                         best_dist = dist;
1386                                         best_fit = i;
1387                                 }
1388                         }
1389
1390                         if (best_fit != -1)
1391                         {
1392                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
1393                                 // to width/height =, so the window will take the full area of
1394                                 // the mode chosen
1395                                 mode->width = vidmodes[best_fit]->hdisplay;
1396                                 mode->height = vidmodes[best_fit]->vdisplay;
1397
1398                                 // change to the mode
1399                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
1400                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
1401                                 vid_isvidmodefullscreen = true;
1402                                 vid_isfullscreen = true;
1403
1404                                 // Move the viewport to top left
1405                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1406                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
1407                         }
1408
1409                         free(vidmodes);
1410                 }
1411
1412                 if(!vid_isfullscreen)
1413                 {
1414                         // sorry, no FS available
1415                         // use the full desktop resolution
1416                         vid_isfullscreen = true;
1417                         // width and height will be filled in later
1418                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
1419                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
1420                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
1421                 }
1422         }
1423
1424         // LordHavoc: save the visual for use in gamma ramp settings later
1425         vidx11_visual = visinfo->visual;
1426
1427         /* window attributes */
1428         attr.background_pixel = 0;
1429         attr.border_pixel = 0;
1430         // LordHavoc: save the colormap for later, too
1431         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
1432         attr.event_mask = X_MASK;
1433
1434         if (mode->fullscreen)
1435         {
1436                 if(vid_isnetwmfullscreen)
1437                 {
1438                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
1439                         attr.backing_store = NotUseful;
1440                         attr.save_under = False;
1441                 }
1442                 else
1443                 {
1444                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
1445                         attr.override_redirect = True;
1446                         attr.backing_store = NotUseful;
1447                         attr.save_under = False;
1448                         vid_isoverrideredirect = true; // so it knows to grab
1449                 }
1450         }
1451         else
1452         {
1453                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1454         }
1455
1456         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
1457
1458         data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1459         if(data)
1460         {
1461                 // use _NET_WM_ICON too
1462                 static long netwm_icon[MAX_NETWM_ICON];
1463                 int pos = 0;
1464                 int i = 1;
1465
1466                 while(data)
1467                 {
1468                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1469                         {
1470                                 netwm_icon[pos++] = image_width;
1471                                 netwm_icon[pos++] = image_height;
1472                                 for(i = 0; i < image_height; ++i)
1473                                         for(j = 0; j < image_width; ++j)
1474                                                 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1475                         }
1476                         else
1477                         {
1478                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1479                         }
1480                         ++i;
1481                         Mem_Free(data);
1482                         data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1483                 }
1484                 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1485         }
1486
1487         // fallthrough for old window managers
1488         xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1489         idata = NULL;
1490         if(xpm)
1491                 idata = XPM_DecodeString(xpm);
1492         if(!idata)
1493                 idata = ENGINE_ICON;
1494
1495         wmhints = XAllocWMHints();
1496         if(XpmCreatePixmapFromData(vidx11_display, win,
1497                 idata,
1498                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1499                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1500
1501         if(xpm)
1502                 Mem_Free(xpm);
1503
1504         clshints = XAllocClassHint();
1505         clshints->res_name = strdup(gamename);
1506         clshints->res_class = strdup("DarkPlaces");
1507
1508         szhints = XAllocSizeHints();
1509         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1510         {
1511                 szhints->min_width = szhints->max_width = mode->width;
1512                 szhints->min_height = szhints->max_height = mode->height;
1513                 szhints->flags |= PMinSize | PMaxSize;
1514         }
1515
1516         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1517         // strdup() allocates using malloc(), should be freed with free()
1518         free(clshints->res_name);
1519         free(clshints->res_class);
1520         XFree(clshints);
1521         XFree(wmhints);
1522         XFree(szhints);
1523
1524         //XStoreName(vidx11_display, win, gamename);
1525         XMapWindow(vidx11_display, win);
1526
1527         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1528
1529         if (vid_isoverrideredirect)
1530         {
1531                 XMoveWindow(vidx11_display, win, 0, 0);
1532                 XRaiseWindow(vidx11_display, win);
1533                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1534                 XFlush(vidx11_display);
1535         }
1536
1537         if(vid_isvidmodefullscreen)
1538         {
1539                 // Move the viewport to top left
1540                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1541         }
1542
1543         //XSync(vidx11_display, False);
1544
1545         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
1546         XFree(visinfo); // glXChooseVisual man page says to use XFree to free visinfo
1547         if (!ctx)
1548         {
1549                 Con_Printf ("glXCreateContext failed\n");
1550                 return false;
1551         }
1552
1553         if (!qglXMakeCurrent(vidx11_display, win, ctx))
1554         {
1555                 Con_Printf ("glXMakeCurrent failed\n");
1556                 return false;
1557         }
1558
1559         XSync(vidx11_display, False);
1560
1561         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1562         {
1563                 Con_Printf ("glGetString not found in %s\n", gl_driver);
1564                 return false;
1565         }
1566
1567         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1568         gl_platform = "GLX";
1569         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
1570
1571 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1572 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1573 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1574         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
1575 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
1576 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
1577 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
1578         GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
1579
1580         vid_usingmousegrab = false;
1581         vid_usingmouse = false;
1582         vid_usinghidecursor = false;
1583         vid_usingvsync = false;
1584         vid_hidden = false;
1585         vid_activewindow = true;
1586         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1587 #if !defined(__APPLE__) && !defined(SUNOS)
1588         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1589         if (!vid_x11_dgasupported)
1590                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1591 #endif
1592
1593         GL_Init();
1594         return true;
1595 }
1596
1597 qboolean VID_InitMode(viddef_mode_t *mode)
1598 {
1599 #ifdef SSE_POSSIBLE
1600         if (vid_soft.integer)
1601                 return VID_InitModeSoft(mode);
1602         else
1603 #endif
1604                 return VID_InitModeGL(mode);
1605 }
1606
1607 void Sys_SendKeyEvents(void)
1608 {
1609         static qboolean sound_active = true;
1610
1611         // enable/disable sound on focus gain/loss
1612         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1613         {
1614                 if (!sound_active)
1615                 {
1616                         S_UnblockSound ();
1617                         sound_active = true;
1618                 }
1619         }
1620         else
1621         {
1622                 if (sound_active)
1623                 {
1624                         S_BlockSound ();
1625                         sound_active = false;
1626                 }
1627         }
1628
1629         HandleEvents();
1630 }
1631
1632 void IN_Move (void)
1633 {
1634 }
1635
1636 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1637 {
1638         if(vidmode_ext)
1639         {
1640                 int i, bpp;
1641                 size_t k;
1642                 XF86VidModeModeInfo **vidmodes;
1643                 int num_vidmodes;
1644
1645                 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1646                 k = 0;
1647                 for (i = 0; i < num_vidmodes; i++)
1648                 {
1649                         if(k >= maxcount)
1650                                 break;
1651                         // we don't get bpp info, so let's just assume all of 8, 15, 16, 24, 32 work
1652                         for(bpp = 8; bpp <= 32; bpp = ((bpp == 8) ? 15 : (bpp & 0xF8) + 8))
1653                         {
1654                                 if(k >= maxcount)
1655                                         break;
1656                                 modes[k].width = vidmodes[i]->hdisplay;
1657                                 modes[k].height = vidmodes[i]->vdisplay;
1658                                 modes[k].bpp = 8;
1659                                 if(vidmodes[i]->dotclock && vidmodes[i]->htotal && vidmodes[i]->vtotal)
1660                                         modes[k].refreshrate = vidmodes[i]->dotclock / vidmodes[i]->htotal / vidmodes[i]->vtotal;
1661                                 else
1662                                         modes[k].refreshrate = 60;
1663                                 modes[k].pixelheight_num = 1;
1664                                 modes[k].pixelheight_denom = 1; // xvidmode does not provide this
1665                                 ++k;
1666                         }
1667                 }
1668                 // manpage of XF86VidModeGetAllModeLines says it should be freed by the caller
1669                 XFree(vidmodes);
1670                 return k;
1671         }
1672         return 0; // FIXME implement this
1673 }