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