]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_glx.c
added GL_Finish function in backend, to centralize all the qglFinish
[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                         GL_Finish();
752                 qglXSwapBuffers(vidx11_display, win);CHECKGLERROR
753         }
754
755         if (vid_x11_hardwaregammasupported)
756                 VID_UpdateGamma(false, vid_x11_gammarampsize);
757 }
758
759 int VID_SetGamma(unsigned short *ramps, int rampsize)
760 {
761         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
762 }
763
764 int VID_GetGamma(unsigned short *ramps, int rampsize)
765 {
766         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, rampsize, ramps, ramps + rampsize, ramps + rampsize*2);
767 }
768
769 void VID_Init(void)
770 {
771 #if !defined(__APPLE__) && !defined(SUNOS)
772         Cvar_RegisterVariable (&vid_dgamouse);
773 #endif
774         Cvar_RegisterVariable (&vid_netwmfullscreen);
775         InitSig(); // trap evil signals
776 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
777         if (COM_CheckParm ("-nomouse"))
778                 mouse_avail = false;
779 }
780
781 void VID_BuildGLXAttrib(int *attrib, qboolean stencil, qboolean stereobuffer, int samples)
782 {
783         *attrib++ = GLX_RGBA;
784         *attrib++ = GLX_RED_SIZE;*attrib++ = stencil ? 8 : 5;
785         *attrib++ = GLX_GREEN_SIZE;*attrib++ = stencil ? 8 : 5;
786         *attrib++ = GLX_BLUE_SIZE;*attrib++ = stencil ? 8 : 5;
787         *attrib++ = GLX_DOUBLEBUFFER;
788         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = stencil ? 24 : 16;
789         // if stencil is enabled, ask for alpha too
790         if (stencil)
791         {
792                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
793                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 8;
794         }
795         if (stereobuffer)
796                 *attrib++ = GLX_STEREO;
797         if (samples > 1)
798         {
799                 *attrib++ = GLX_SAMPLE_BUFFERS_ARB;
800                 *attrib++ = 1;
801                 *attrib++ = GLX_SAMPLES_ARB;
802                 *attrib++ = samples;
803         }
804         *attrib++ = None;
805 }
806
807 qboolean VID_InitMode(viddef_mode_t *mode)
808 {
809         int i, j;
810         int attrib[32];
811         XSetWindowAttributes attr;
812         XClassHint *clshints;
813         XWMHints *wmhints;
814         XSizeHints *szhints;
815         unsigned long mask;
816         XVisualInfo *visinfo;
817         int MajorVersion, MinorVersion;
818         const char *drivername;
819         char *xpm;
820         char **idata;
821         unsigned char *data;
822
823         vid_isfullscreen = false;
824         vid_isnetwmfullscreen = false;
825         vid_isvidmodefullscreen = false;
826         vid_isoverrideredirect = false;
827
828 #if defined(__APPLE__) && defined(__MACH__)
829         drivername = "/usr/X11R6/lib/libGL.1.dylib";
830 #else
831         drivername = "libGL.so.1";
832 #endif
833 // 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
834 // 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
835 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
836         i = COM_CheckParm("-gl_driver");
837         if (i && i < com_argc - 1)
838                 drivername = com_argv[i + 1];
839         if (!GL_OpenLibrary(drivername))
840         {
841                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
842                 return false;
843         }
844
845         if (!(vidx11_display = XOpenDisplay(NULL)))
846         {
847                 Con_Print("Couldn't open the X display\n");
848                 return false;
849         }
850
851         // LordHavoc: making the close button on a window do the right thing
852         // seems to involve this mess, sigh...
853         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
854         net_wm_state_atom = XInternAtom(vidx11_display, "_NET_WM_STATE", false);
855         net_wm_state_fullscreen_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_FULLSCREEN", false);
856         net_wm_state_hidden_atom = XInternAtom(vidx11_display, "_NET_WM_STATE_HIDDEN", false);
857         net_wm_icon = XInternAtom(vidx11_display, "_NET_WM_ICON", false);
858         cardinal = XInternAtom(vidx11_display, "CARDINAL", false);
859
860         // make autorepeat send keypress/keypress/.../keyrelease instead of intervening keyrelease
861         XkbSetDetectableAutoRepeat(vidx11_display, true, NULL);
862
863         vidx11_screen = DefaultScreen(vidx11_display);
864         root = RootWindow(vidx11_display, vidx11_screen);
865
866         // Get video mode list
867         MajorVersion = MinorVersion = 0;
868         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
869                 vidmode_ext = false;
870         else
871         {
872                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
873                 vidmode_ext = true;
874         }
875
876         if ((qglXChooseVisual = (XVisualInfo *(GLAPIENTRY *)(Display *dpy, int screen, int *attribList))GL_GetProcAddress("glXChooseVisual")) == NULL
877          || (qglXCreateContext = (GLXContext (GLAPIENTRY *)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct))GL_GetProcAddress("glXCreateContext")) == NULL
878          || (qglXDestroyContext = (void (GLAPIENTRY *)(Display *dpy, GLXContext ctx))GL_GetProcAddress("glXDestroyContext")) == NULL
879          || (qglXMakeCurrent = (Bool (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable, GLXContext ctx))GL_GetProcAddress("glXMakeCurrent")) == NULL
880          || (qglXSwapBuffers = (void (GLAPIENTRY *)(Display *dpy, GLXDrawable drawable))GL_GetProcAddress("glXSwapBuffers")) == NULL
881          || (qglXQueryExtensionsString = (const char *(GLAPIENTRY *)(Display *dpy, int screen))GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
882         {
883                 Con_Printf("glX functions not found in %s\n", gl_driver);
884                 return false;
885         }
886
887         VID_BuildGLXAttrib(attrib, mode->bitsperpixel == 32, mode->stereobuffer, mode->samples);
888         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
889         if (!visinfo)
890         {
891                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
892                 return false;
893         }
894
895         if (mode->fullscreen)
896         {
897                 if(vid_netwmfullscreen.integer)
898                 {
899                         // TODO detect WM support
900                         vid_isnetwmfullscreen = true;
901                         vid_isfullscreen = true;
902                         // width and height will be filled in later
903                         Con_DPrintf("Using NetWM fullscreen mode\n");
904                 }
905
906                 if(!vid_isfullscreen && vidmode_ext)
907                 {
908                         int best_fit, best_dist, dist, x, y;
909
910                         // Are we going fullscreen?  If so, let's change video mode
911                         XF86VidModeModeLine *current_vidmode;
912                         XF86VidModeModeInfo **vidmodes;
913                         int num_vidmodes;
914
915                         // This nice hack comes from the SDL source code
916                         current_vidmode = (XF86VidModeModeLine*)((char*)&init_vidmode + sizeof(init_vidmode.dotclock));
917                         XF86VidModeGetModeLine(vidx11_display, vidx11_screen, (int*)&init_vidmode.dotclock, current_vidmode);
918
919                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
920                         best_dist = 0;
921                         best_fit = -1;
922
923                         for (i = 0; i < num_vidmodes; i++)
924                         {
925                                 if (mode->width > vidmodes[i]->hdisplay || mode->height > vidmodes[i]->vdisplay)
926                                         continue;
927
928                                 x = mode->width - vidmodes[i]->hdisplay;
929                                 y = mode->height - vidmodes[i]->vdisplay;
930                                 dist = (x * x) + (y * y);
931                                 if (best_fit == -1 || dist < best_dist)
932                                 {
933                                         best_dist = dist;
934                                         best_fit = i;
935                                 }
936                         }
937
938                         if (best_fit != -1)
939                         {
940                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
941                                 // to width/height =, so the window will take the full area of
942                                 // the mode chosen
943                                 mode->width = vidmodes[best_fit]->hdisplay;
944                                 mode->height = vidmodes[best_fit]->vdisplay;
945
946                                 // change to the mode
947                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
948                                 memcpy(&game_vidmode, vidmodes[best_fit], sizeof(game_vidmode));
949                                 vid_isvidmodefullscreen = true;
950                                 vid_isfullscreen = true;
951
952                                 // Move the viewport to top left
953                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
954                                 Con_DPrintf("Using XVidMode fullscreen mode at %dx%d\n", mode->width, mode->height);
955                         }
956
957                         free(vidmodes);
958                 }
959
960                 if(!vid_isfullscreen)
961                 {
962                         // sorry, no FS available
963                         // use the full desktop resolution
964                         vid_isfullscreen = true;
965                         // width and height will be filled in later
966                         mode->width = DisplayWidth(vidx11_display, vidx11_screen);
967                         mode->height = DisplayHeight(vidx11_display, vidx11_screen);
968                         Con_DPrintf("Using X11 fullscreen mode at %dx%d\n", mode->width, mode->height);
969                 }
970         }
971
972         // LordHavoc: save the visual for use in gamma ramp settings later
973         vidx11_visual = visinfo->visual;
974
975         /* window attributes */
976         attr.background_pixel = 0;
977         attr.border_pixel = 0;
978         // LordHavoc: save the colormap for later, too
979         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
980         attr.event_mask = X_MASK;
981
982         if (mode->fullscreen)
983         {
984                 if(vid_isnetwmfullscreen)
985                 {
986                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask;
987                         attr.backing_store = NotUseful;
988                         attr.save_under = False;
989                 }
990                 else
991                 {
992                         mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
993                         attr.override_redirect = True;
994                         attr.backing_store = NotUseful;
995                         attr.save_under = False;
996                         vid_isoverrideredirect = true; // so it knows to grab
997                 }
998         }
999         else
1000         {
1001                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1002         }
1003
1004         win = XCreateWindow(vidx11_display, root, 0, 0, mode->width, mode->height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
1005
1006         data = loadimagepixelsbgra("darkplaces-icon", false, false, false, NULL);
1007         if(data)
1008         {
1009                 // use _NET_WM_ICON too
1010                 static long netwm_icon[MAX_NETWM_ICON];
1011                 int pos = 0;
1012                 int i = 1;
1013
1014                 while(data)
1015                 {
1016                         if(pos + 2 * image_width * image_height < MAX_NETWM_ICON)
1017                         {
1018                                 netwm_icon[pos++] = image_width;
1019                                 netwm_icon[pos++] = image_height;
1020                                 for(i = 0; i < image_height; ++i)
1021                                         for(j = 0; j < image_width; ++j)
1022                                                 netwm_icon[pos++] = BuffLittleLong(&data[(i*image_width+j)*4]);
1023                         }
1024                         else
1025                         {
1026                                 Con_Printf("Skipping NETWM icon #%d because there is no space left\n", i);
1027                         }
1028                         ++i;
1029                         Mem_Free(data);
1030                         data = loadimagepixelsbgra(va("darkplaces-icon%d", i), false, false, false, NULL);
1031                 }
1032                 XChangeProperty(vidx11_display, win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *) netwm_icon, pos);
1033         }
1034
1035         // fallthrough for old window managers
1036         xpm = (char *) FS_LoadFile("darkplaces-icon.xpm", tempmempool, false, NULL);
1037         idata = NULL;
1038         if(xpm)
1039                 idata = XPM_DecodeString(xpm);
1040         if(!idata)
1041                 idata = ENGINE_ICON;
1042
1043         wmhints = XAllocWMHints();
1044         if(XpmCreatePixmapFromData(vidx11_display, win,
1045                 idata,
1046                 &wmhints->icon_pixmap, &wmhints->icon_mask, NULL) == XpmSuccess)
1047                 wmhints->flags |= IconPixmapHint | IconMaskHint;
1048
1049         if(xpm)
1050                 Mem_Free(xpm);
1051
1052         clshints = XAllocClassHint();
1053         clshints->res_name = strdup(gamename);
1054         clshints->res_class = strdup("DarkPlaces");
1055
1056         szhints = XAllocSizeHints();
1057         if(vid_resizable.integer == 0 && !vid_isnetwmfullscreen)
1058         {
1059                 szhints->min_width = szhints->max_width = mode->width;
1060                 szhints->min_height = szhints->max_height = mode->height;
1061                 szhints->flags |= PMinSize | PMaxSize;
1062         }
1063
1064         XmbSetWMProperties(vidx11_display, win, gamename, gamename, (char **) com_argv, com_argc, szhints, wmhints, clshints);
1065         // strdup() allocates using malloc(), should be freed with free()
1066         free(clshints->res_name);
1067         free(clshints->res_class);
1068         XFree(clshints);
1069         XFree(wmhints);
1070         XFree(szhints);
1071
1072         //XStoreName(vidx11_display, win, gamename);
1073         XMapWindow(vidx11_display, win);
1074
1075         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
1076
1077         if (vid_isoverrideredirect)
1078         {
1079                 XMoveWindow(vidx11_display, win, 0, 0);
1080                 XRaiseWindow(vidx11_display, win);
1081                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
1082                 XFlush(vidx11_display);
1083         }
1084
1085         if(vid_isvidmodefullscreen)
1086         {
1087                 // Move the viewport to top left
1088                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
1089         }
1090
1091         //XSync(vidx11_display, False);
1092
1093         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
1094         XFree(visinfo); // glXChooseVisual man page says to use XFree to free visinfo
1095         if (!ctx)
1096         {
1097                 Con_Printf ("glXCreateContext failed\n");
1098                 return false;
1099         }
1100
1101         if (!qglXMakeCurrent(vidx11_display, win, ctx))
1102         {
1103                 Con_Printf ("glXMakeCurrent failed\n");
1104                 return false;
1105         }
1106
1107         XSync(vidx11_display, False);
1108
1109         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1110         {
1111                 Con_Printf ("glGetString not found in %s\n", gl_driver);
1112                 return false;
1113         }
1114
1115         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1116         gl_platform = "GLX";
1117         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
1118
1119 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1120 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1121 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
1122         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
1123 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
1124 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
1125 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
1126         GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
1127
1128         vid_usingmousegrab = false;
1129         vid_usingmouse = false;
1130         vid_usinghidecursor = false;
1131         vid_usingvsync = false;
1132         vid_hidden = false;
1133         vid_activewindow = true;
1134         vid_x11_hardwaregammasupported = XF86VidModeGetGammaRampSize(vidx11_display, vidx11_screen, &vid_x11_gammarampsize) != 0;
1135 #if !defined(__APPLE__) && !defined(SUNOS)
1136         vid_x11_dgasupported = XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion);
1137         if (!vid_x11_dgasupported)
1138                 Con_Print( "Failed to detect XF86DGA Mouse extension\n" );
1139 #endif
1140
1141         GL_Init();
1142         return true;
1143 }
1144
1145 void Sys_SendKeyEvents(void)
1146 {
1147         static qboolean sound_active = true;
1148
1149         // enable/disable sound on focus gain/loss
1150         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1151         {
1152                 if (!sound_active)
1153                 {
1154                         S_UnblockSound ();
1155                         sound_active = true;
1156                 }
1157         }
1158         else
1159         {
1160                 if (sound_active)
1161                 {
1162                         S_BlockSound ();
1163                         sound_active = false;
1164                 }
1165         }
1166
1167         HandleEvents();
1168 }
1169
1170 void IN_Move (void)
1171 {
1172 }
1173
1174 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1175 {
1176         if(vidmode_ext)
1177         {
1178                 int i, bpp;
1179                 size_t k;
1180                 XF86VidModeModeInfo **vidmodes;
1181                 int num_vidmodes;
1182
1183                 XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
1184                 k = 0;
1185                 for (i = 0; i < num_vidmodes; i++)
1186                 {
1187                         if(k >= maxcount)
1188                                 break;
1189                         // we don't get bpp info, so let's just assume all of 8, 15, 16, 24, 32 work
1190                         for(bpp = 8; bpp <= 32; bpp = ((bpp == 8) ? 15 : (bpp & 0xF8) + 8))
1191                         {
1192                                 if(k >= maxcount)
1193                                         break;
1194                                 modes[k].width = vidmodes[i]->hdisplay;
1195                                 modes[k].height = vidmodes[i]->vdisplay;
1196                                 modes[k].bpp = 8;
1197                                 if(vidmodes[i]->dotclock && vidmodes[i]->htotal && vidmodes[i]->vtotal)
1198                                         modes[k].refreshrate = vidmodes[i]->dotclock / vidmodes[i]->htotal / vidmodes[i]->vtotal;
1199                                 else
1200                                         modes[k].refreshrate = 60;
1201                                 modes[k].pixelheight_num = 1;
1202                                 modes[k].pixelheight_denom = 1; // xvidmode does not provide this
1203                                 ++k;
1204                         }
1205                 }
1206                 // manpage of XF86VidModeGetAllModeLines says it should be freed by the caller
1207                 XFree(vidmodes);
1208                 return k;
1209         }
1210         return 0; // FIXME implement this
1211 }