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