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