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