]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_glx.c
391 (-2)
[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 <termios.h>
21 //#include <sys/ioctl.h>
22 //#include <sys/stat.h>
23 //#include <sys/vt.h>
24 //#include <stdarg.h>
25 //#include <stdio.h>
26 #include <signal.h>
27
28 #include <dlfcn.h>
29
30 #include <X11/Xlib.h>
31 #include <X11/Xutil.h>
32 #include <GL/glx.h>
33
34 #include <X11/keysym.h>
35 #include <X11/cursorfont.h>
36
37 #include <X11/extensions/XShm.h>
38 #if !defined(__APPLE__) && !defined(__MACH__)
39 #include <X11/extensions/xf86dga.h>
40 #endif
41 #include <X11/extensions/xf86vmode.h>
42
43 #include "quakedef.h"
44
45 // Tell startup code that we have a client
46 int cl_available = true;
47
48 //GLX prototypes
49 XVisualInfo *(GLAPIENTRY *qglXChooseVisual)(Display *dpy, int screen, int *attribList);
50 GLXContext (GLAPIENTRY *qglXCreateContext)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
51 void (GLAPIENTRY *qglXDestroyContext)(Display *dpy, GLXContext ctx);
52 Bool (GLAPIENTRY *qglXMakeCurrent)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
53 void (GLAPIENTRY *qglXSwapBuffers)(Display *dpy, GLXDrawable drawable);
54 const char *(GLAPIENTRY *qglXQueryExtensionsString)(Display *dpy, int screen);
55
56 //GLX_ARB_get_proc_address
57 void *(GLAPIENTRY *qglXGetProcAddressARB)(const GLubyte *procName);
58
59 static dllfunction_t getprocaddressfuncs[] =
60 {
61         {"glXGetProcAddressARB", (void **) &qglXGetProcAddressARB},
62         {NULL, NULL}
63 };
64
65 //GLX_SGI_swap_control
66 GLint (GLAPIENTRY *qglXSwapIntervalSGI)(GLint interval);
67
68 static dllfunction_t swapcontrolfuncs[] =
69 {
70         {"glXSwapIntervalSGI", (void **) &qglXSwapIntervalSGI},
71         {NULL, NULL}
72 };
73
74 static Display *vidx11_display = NULL;
75 static int vidx11_screen;
76 static Window win;
77 static GLXContext ctx = NULL;
78
79 Atom wm_delete_window_atom;
80
81 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
82 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
83                     PointerMotionMask | ButtonMotionMask)
84 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | \
85                 StructureNotifyMask | FocusChangeMask | EnterWindowMask | \
86                 LeaveWindowMask)
87
88
89 static qboolean mouse_avail = true;
90 static qboolean vid_usingmouse = false;
91 static qboolean vid_usemouse = false;
92 static qboolean vid_usingvsync = false;
93 static qboolean vid_usevsync = false;
94 static qboolean ignoremousemove = false;
95 static float    mouse_x, mouse_y;
96 static int p_mouse_x, p_mouse_y;
97
98 #ifndef __APPLE__
99 cvar_t vid_dga = {CVAR_SAVE, "vid_dga", "1"};
100 cvar_t vid_dga_mouseaccel = {0, "vid_dga_mouseaccel", "1"};
101 #endif
102
103 qboolean vidmode_ext = false;
104
105 static int win_x, win_y;
106
107 static int scr_width, scr_height;
108
109 static XF86VidModeModeInfo **vidmodes;
110 static int num_vidmodes;
111 static qboolean vid_isfullscreen = false;
112
113 static Visual *vidx11_visual;
114 static Colormap vidx11_colormap;
115
116 /*-----------------------------------------------------------------------*/
117
118 static int XLateKey(XKeyEvent *ev, char *ascii)
119 {
120         int key = 0;
121         char buf[64];
122         KeySym keysym, shifted;
123
124         keysym = XLookupKeysym (ev, 0);
125         XLookupString(ev, buf, sizeof buf, &shifted, 0);
126         *ascii = buf[0];
127
128         switch(keysym)
129         {
130                 case XK_KP_Page_Up:      key = K_KP_PGUP; break;
131                 case XK_Page_Up:         key = K_PGUP; break;
132
133                 case XK_KP_Page_Down: key = K_KP_PGDN; break;
134                 case XK_Page_Down:       key = K_PGDN; break;
135
136                 case XK_KP_Home: key = K_KP_HOME; break;
137                 case XK_Home:    key = K_HOME; break;
138
139                 case XK_KP_End:  key = K_KP_END; break;
140                 case XK_End:     key = K_END; break;
141
142                 case XK_KP_Left: key = K_KP_LEFTARROW; break;
143                 case XK_Left:    key = K_LEFTARROW; break;
144
145                 case XK_KP_Right: key = K_KP_RIGHTARROW; break;
146                 case XK_Right:  key = K_RIGHTARROW;             break;
147
148                 case XK_KP_Down: key = K_KP_DOWNARROW; break;
149                 case XK_Down:    key = K_DOWNARROW; break;
150
151                 case XK_KP_Up:   key = K_KP_UPARROW; break;
152                 case XK_Up:              key = K_UPARROW;        break;
153
154                 case XK_Escape: key = K_ESCAPE;         break;
155
156                 case XK_KP_Enter: key = K_KP_ENTER;     break;
157                 case XK_Return: key = K_ENTER;           break;
158
159                 case XK_Tab:            key = K_TAB;                     break;
160
161                 case XK_F1:              key = K_F1;                            break;
162
163                 case XK_F2:              key = K_F2;                            break;
164
165                 case XK_F3:              key = K_F3;                            break;
166
167                 case XK_F4:              key = K_F4;                            break;
168
169                 case XK_F5:              key = K_F5;                            break;
170
171                 case XK_F6:              key = K_F6;                            break;
172
173                 case XK_F7:              key = K_F7;                            break;
174
175                 case XK_F8:              key = K_F8;                            break;
176
177                 case XK_F9:              key = K_F9;                            break;
178
179                 case XK_F10:            key = K_F10;                     break;
180
181                 case XK_F11:            key = K_F11;                     break;
182
183                 case XK_F12:            key = K_F12;                     break;
184
185                 case XK_BackSpace: key = K_BACKSPACE; break;
186
187                 case XK_KP_Delete: key = K_KP_DEL; break;
188                 case XK_Delete: key = K_DEL; break;
189
190                 case XK_Pause:  key = K_PAUSE;           break;
191
192                 case XK_Shift_L:
193                 case XK_Shift_R:        key = K_SHIFT;          break;
194
195                 case XK_Execute:
196                 case XK_Control_L:
197                 case XK_Control_R:      key = K_CTRL;            break;
198
199                 case XK_Alt_L:
200                 case XK_Meta_L:
201                 case XK_Alt_R:
202                 case XK_Meta_R: key = K_ALT;                    break;
203
204                 case XK_KP_Begin: key = K_KP_5; break;
205
206                 case XK_Insert:key = K_INS; break;
207                 case XK_KP_Insert: key = K_KP_INS; break;
208
209                 case XK_KP_Multiply: key = '*'; break;
210                 case XK_KP_Add:  key = K_KP_PLUS; break;
211                 case XK_KP_Subtract: key = K_KP_MINUS; break;
212                 case XK_KP_Divide: key = K_KP_SLASH; break;
213
214                 default:
215                         if (keysym < 32 && keysym > 126)
216                                 break;
217
218                         if (keysym >= 'A' && keysym <= 'Z')
219                                 key = keysym - 'A' + 'a';
220                         else
221                                 key = keysym;
222
223                         break;
224         }
225
226         return key;
227 }
228
229 static Cursor CreateNullCursor(Display *display, Window root)
230 {
231         Pixmap cursormask;
232         XGCValues xgc;
233         GC gc;
234         XColor dummycolour;
235         Cursor cursor;
236
237         cursormask = XCreatePixmap(display, root, 1, 1, 1);
238         xgc.function = GXclear;
239         gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
240         XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
241         dummycolour.pixel = 0;
242         dummycolour.red = 0;
243         dummycolour.flags = 04;
244         cursor = XCreatePixmapCursor(display, cursormask, cursormask, &dummycolour,&dummycolour, 0,0);
245         XFreePixmap(display,cursormask);
246         XFreeGC(display,gc);
247         return cursor;
248 }
249
250 static void IN_Activate (qboolean grab)
251 {
252         if (!mouse_avail || !vidx11_display || !win)
253                 return;
254
255         if (grab)
256         {
257                 if (!vid_usingmouse)
258                 {
259                         XWindowAttributes attribs_1;
260                         XSetWindowAttributes attribs_2;
261
262                         XGetWindowAttributes(vidx11_display, win, &attribs_1);
263                         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
264                         XChangeWindowAttributes(vidx11_display, win, CWEventMask, &attribs_2);
265
266                 // inviso cursor
267                         XDefineCursor(vidx11_display, win, CreateNullCursor(vidx11_display, win));
268
269                         XGrabPointer(vidx11_display, win,  True, 0, GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
270
271 #ifndef __APPLE__
272                         if (vid_dga.integer)
273                         {
274                                 int MajorVersion, MinorVersion;
275
276                                 if (!XF86DGAQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
277                                 {
278                                         // unable to query, probably not supported
279                                         Con_Print( "Failed to detect XF86DGA Mouse\n" );
280                                         Cvar_SetValueQuick(&vid_dga, 0);
281                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
282                                 }
283                                 else
284                                 {
285                                         XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), XF86DGADirectMouse);
286                                         XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
287                                 }
288                         }
289                         else
290 #endif
291                                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, scr_width / 2, scr_height / 2);
292
293                         XGrabKeyboard(vidx11_display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
294
295                         mouse_x = mouse_y = 0;
296                         ignoremousemove = true;
297                         vid_usingmouse = true;
298                 }
299         }
300         else
301         {
302                 if (vid_usingmouse)
303                 {
304 #ifndef __APPLE__
305                         if (vid_dga.integer == 1)
306                                 XF86DGADirectVideo(vidx11_display, DefaultScreen(vidx11_display), 0);
307 #endif
308
309                         XUngrabPointer(vidx11_display, CurrentTime);
310                         XUngrabKeyboard(vidx11_display, CurrentTime);
311
312                 // inviso cursor
313                         XUndefineCursor(vidx11_display, win);
314
315                         ignoremousemove = true;
316                         vid_usingmouse = false;
317                 }
318         }
319 }
320
321 static void HandleEvents(void)
322 {
323         XEvent event;
324         int key;
325         char ascii;
326         qboolean dowarp = false;
327
328         if (!vidx11_display)
329                 return;
330
331         while (XPending(vidx11_display))
332         {
333                 XNextEvent(vidx11_display, &event);
334
335                 switch (event.type)
336                 {
337                 case KeyPress:
338                         // key pressed
339                         key = XLateKey (&event.xkey, &ascii);
340                         Key_Event(key, ascii, true);
341                         break;
342
343                 case KeyRelease:
344                         // key released
345                         key = XLateKey (&event.xkey, &ascii);
346                         Key_Event(key, ascii, false);
347                         break;
348
349                 case MotionNotify:
350                         // mouse moved
351                         if (vid_usingmouse)
352                         {
353 #ifndef __APPLE__
354                                 if (vid_dga.integer == 1)
355                                 {
356                                         mouse_x += event.xmotion.x_root * vid_dga_mouseaccel.value;
357                                         mouse_y += event.xmotion.y_root * vid_dga_mouseaccel.value;
358                                 }
359                                 else
360 #endif
361                                 {
362
363                                         if (!event.xmotion.send_event)
364                                         {
365                                                 mouse_x += event.xmotion.x - p_mouse_x;
366                                                 mouse_y += event.xmotion.y - p_mouse_y;
367                                                 if (abs(scr_width/2 - event.xmotion.x) > scr_width / 4 || abs(scr_height/2 - event.xmotion.y) > scr_height / 4)
368                                                         dowarp = true;
369                                         }
370                                         p_mouse_x = event.xmotion.x;
371                                         p_mouse_y = event.xmotion.y;
372                                 }
373                         }
374                         //else
375                         //      ui_mouseupdate(event.xmotion.x, event.xmotion.y);
376                         break;
377
378                 case ButtonPress:
379                         // mouse button pressed
380                         switch(event.xbutton.button)
381                         {
382                         case 1:
383                                 Key_Event(K_MOUSE1, 0, true);
384                                 break;
385                         case 2:
386                                 Key_Event(K_MOUSE3, 0, true);
387                                 break;
388                         case 3:
389                                 Key_Event(K_MOUSE2, 0, true);
390                                 break;
391                         case 4:
392                                 Key_Event(K_MWHEELUP, 0, true);
393                                 break;
394                         case 5:
395                                 Key_Event(K_MWHEELDOWN, 0, true);
396                                 break;
397                         case 6:
398                                 Key_Event(K_MOUSE4, 0, true);
399                                 break;
400                         case 7:
401                                 Key_Event(K_MOUSE5, 0, true);
402                                 break;
403                         case 8:
404                                 Key_Event(K_MOUSE6, 0, true);
405                                 break;
406                         case 9:
407                                 Key_Event(K_MOUSE7, 0, true);
408                                 break;
409                         case 10:
410                                 Key_Event(K_MOUSE8, 0, true);
411                                 break;
412                         case 11:
413                                 Key_Event(K_MOUSE9, 0, true);
414                                 break;
415                         case 12:
416                                 Key_Event(K_MOUSE10, 0, true);
417                                 break;
418                         default:
419                                 Con_Printf("HandleEvents: ButtonPress gave value %d, 1-12 expected\n", event.xbutton.button);
420                                 break;
421                         }
422                         break;
423
424                 case ButtonRelease:
425                         // mouse button released
426                         switch(event.xbutton.button)
427                         {
428                         case 1:
429                                 Key_Event(K_MOUSE1, 0, false);
430                                 break;
431                         case 2:
432                                 Key_Event(K_MOUSE3, 0, false);
433                                 break;
434                         case 3:
435                                 Key_Event(K_MOUSE2, 0, false);
436                                 break;
437                         case 4:
438                                 Key_Event(K_MWHEELUP, 0, false);
439                                 break;
440                         case 5:
441                                 Key_Event(K_MWHEELDOWN, 0, false);
442                                 break;
443                         case 6:
444                                 Key_Event(K_MOUSE4, 0, false);
445                                 break;
446                         case 7:
447                                 Key_Event(K_MOUSE5, 0, false);
448                                 break;
449                         case 8:
450                                 Key_Event(K_MOUSE6, 0, false);
451                                 break;
452                         case 9:
453                                 Key_Event(K_MOUSE7, 0, false);
454                                 break;
455                         case 10:
456                                 Key_Event(K_MOUSE8, 0, false);
457                                 break;
458                         case 11:
459                                 Key_Event(K_MOUSE9, 0, false);
460                                 break;
461                         case 12:
462                                 Key_Event(K_MOUSE10, 0, false);
463                                 break;
464                         default:
465                                 Con_Printf("HandleEvents: ButtonRelease gave value %d, 1-12 expected\n", event.xbutton.button);
466                                 break;
467                         }
468                         break;
469
470                 case CreateNotify:
471                         // window created
472                         win_x = event.xcreatewindow.x;
473                         win_y = event.xcreatewindow.y;
474                         break;
475
476                 case ConfigureNotify:
477                         // window changed size/location
478                         win_x = event.xconfigure.x;
479                         win_y = event.xconfigure.y;
480                         break;
481                 case DestroyNotify:
482                         // window has been destroyed
483                         Sys_Quit();
484                         break;
485                 case ClientMessage:
486                         // window manager messages
487                         if ((event.xclient.format == 32) && ((unsigned int)event.xclient.data.l[0] == wm_delete_window_atom))
488                                 Sys_Quit();
489                         break;
490                 case MapNotify:
491                         // window restored
492                         vid_hidden = false;
493                         vid_activewindow = false;
494                         VID_RestoreSystemGamma();
495                         break;
496                 case UnmapNotify:
497                         // window iconified/rolledup/whatever
498                         vid_hidden = true;
499                         vid_activewindow = false;
500                         VID_RestoreSystemGamma();
501                         break;
502                 case FocusIn:
503                         // window is now the input focus
504                         vid_activewindow = true;
505                         break;
506                 case FocusOut:
507                         // window is no longer the input focus
508                         vid_activewindow = false;
509                         VID_RestoreSystemGamma();
510                         break;
511                 case EnterNotify:
512                         // mouse entered window
513                         break;
514                 case LeaveNotify:
515                         // mouse left window
516                         break;
517                 }
518         }
519
520         if (dowarp)
521         {
522                 /* move the mouse to the window center again */
523                 p_mouse_x = scr_width / 2;
524                 p_mouse_y = scr_height / 2;
525                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
526         }
527
528         // if told to ignore one mouse move, do so
529         if (ignoremousemove)
530         {
531                 ignoremousemove = false;
532                 mouse_x = 0;
533                 mouse_y = 0;
534         }
535 }
536
537 static void *prjobj = NULL;
538
539 static void GL_CloseLibrary(void)
540 {
541         if (prjobj)
542                 dlclose(prjobj);
543         prjobj = NULL;
544         gl_driver[0] = 0;
545         qglXGetProcAddressARB = NULL;
546         gl_extensions = "";
547         gl_platform = "";
548         gl_platformextensions = "";
549 }
550
551 static int GL_OpenLibrary(const char *name)
552 {
553         Con_Printf("Loading OpenGL driver %s\n", name);
554         GL_CloseLibrary();
555         if (!(prjobj = dlopen(name, RTLD_LAZY)))
556         {
557                 Con_Printf("Unable to open symbol list for %s\n", name);
558                 return false;
559         }
560         strcpy(gl_driver, name);
561         return true;
562 }
563
564 void *GL_GetProcAddress(const char *name)
565 {
566         void *p = NULL;
567         if (qglXGetProcAddressARB != NULL)
568                 p = (void *) qglXGetProcAddressARB(name);
569         if (p == NULL)
570                 p = (void *) dlsym(prjobj, name);
571         return p;
572 }
573
574 void VID_Shutdown(void)
575 {
576         if (!ctx || !vidx11_display)
577                 return;
578
579         vid_hidden = true;
580         vid_usingmouse = false;
581         if (vidx11_display)
582         {
583                 VID_RestoreSystemGamma();
584                 IN_Activate(false);
585
586                 // FIXME: glXDestroyContext here?
587                 if (vid_isfullscreen)
588                         XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[0]);
589                 if (win)
590                         XDestroyWindow(vidx11_display, win);
591                 XCloseDisplay(vidx11_display);
592         }
593         vid_isfullscreen = false;
594         vidx11_display = NULL;
595         win = 0;
596         ctx = NULL;
597
598         GL_CloseLibrary();
599         Key_ClearStates ();
600 }
601
602 void signal_handler(int sig)
603 {
604         Con_Printf("Received signal %d, exiting...\n", sig);
605         VID_RestoreSystemGamma();
606         Sys_Quit();
607         exit(0);
608 }
609
610 void InitSig(void)
611 {
612         signal(SIGHUP, signal_handler);
613         signal(SIGINT, signal_handler);
614         signal(SIGQUIT, signal_handler);
615         signal(SIGILL, signal_handler);
616         signal(SIGTRAP, signal_handler);
617         signal(SIGIOT, signal_handler);
618         signal(SIGBUS, signal_handler);
619         signal(SIGFPE, signal_handler);
620         signal(SIGSEGV, signal_handler);
621         signal(SIGTERM, signal_handler);
622 }
623
624 /*
625 =================
626 VID_GetWindowSize
627 =================
628 */
629 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
630 {
631         *x = *y = 0;
632         *width = scr_width;
633         *height = scr_height;
634 }
635
636 void VID_Finish (void)
637 {
638         vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
639         if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
640         {
641                 vid_usingvsync = vid_usevsync;
642                 if (qglXSwapIntervalSGI (vid_usevsync))
643                         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");
644         }
645
646 // handle the mouse state when windowed if that's changed
647         vid_usemouse = false;
648         if (vid_mouse.integer && !key_consoleactive && !cls.demoplayback)
649                 vid_usemouse = true;
650         if (!vid_activewindow)
651                 vid_usemouse = false;
652         if (vid_isfullscreen)
653                 vid_usemouse = true;
654         IN_Activate(vid_usemouse);
655
656         if (r_render.integer)
657         {
658                 if (r_speeds.integer || gl_finish.integer)
659                         qglFinish();
660                 qglXSwapBuffers(vidx11_display, win);
661         }
662 }
663
664 int VID_SetGamma(unsigned short *ramps)
665 {
666         return XF86VidModeSetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
667 }
668
669 int VID_GetGamma(unsigned short *ramps)
670 {
671         return XF86VidModeGetGammaRamp(vidx11_display, vidx11_screen, 256, ramps, ramps + 256, ramps + 512);
672 }
673
674 void VID_Init(void)
675 {
676 #ifndef __APPLE__
677         Cvar_RegisterVariable (&vid_dga);
678         Cvar_RegisterVariable (&vid_dga_mouseaccel);
679 #endif
680         InitSig(); // trap evil signals
681 // COMMANDLINEOPTION: Input: -nomouse disables mouse support (see also vid_mouse cvar)
682         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe"))
683                 mouse_avail = false;
684 }
685
686 void VID_BuildGLXAttrib(int *attrib, int stencil)
687 {
688         *attrib++ = GLX_RGBA;
689         *attrib++ = GLX_RED_SIZE;*attrib++ = 1;
690         *attrib++ = GLX_GREEN_SIZE;*attrib++ = 1;
691         *attrib++ = GLX_BLUE_SIZE;*attrib++ = 1;
692         *attrib++ = GLX_DOUBLEBUFFER;
693         *attrib++ = GLX_DEPTH_SIZE;*attrib++ = 1;
694         // if stencil is enabled, ask for alpha too
695         if (stencil)
696         {
697                 *attrib++ = GLX_STENCIL_SIZE;*attrib++ = 8;
698                 *attrib++ = GLX_ALPHA_SIZE;*attrib++ = 1;
699         }
700         *attrib++ = None;
701 }
702
703 int VID_InitMode(int fullscreen, int width, int height, int bpp)
704 {
705         int i;
706         int attrib[32];
707         XSetWindowAttributes attr;
708         unsigned long mask;
709         Window root;
710         XVisualInfo *visinfo;
711         int MajorVersion, MinorVersion;
712         const char *drivername;
713
714 #if defined(__APPLE__) && defined(__MACH__)
715         drivername = "/usr/X11R6/lib/libGL.1.dylib";
716 #else
717         drivername = "libGL.so.1";
718 #endif
719 // 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
720 // 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
721 // LordHavoc: although this works on MacOSX, it's useless there (as there is only one system libGL)
722         i = COM_CheckParm("-gl_driver");
723         if (i && i < com_argc - 1)
724                 drivername = com_argv[i + 1];
725         if (!GL_OpenLibrary(drivername))
726         {
727                 Con_Printf("Unable to load GL driver \"%s\"\n", drivername);
728                 return false;
729         }
730
731         if (!(vidx11_display = XOpenDisplay(NULL)))
732         {
733                 Con_Print("Couldn't open the X display\n");
734                 return false;
735         }
736
737         vidx11_screen = DefaultScreen(vidx11_display);
738         root = RootWindow(vidx11_display, vidx11_screen);
739
740         // Get video mode list
741         MajorVersion = MinorVersion = 0;
742         if (!XF86VidModeQueryVersion(vidx11_display, &MajorVersion, &MinorVersion))
743                 vidmode_ext = false;
744         else
745         {
746                 Con_DPrintf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
747                 vidmode_ext = true;
748         }
749
750         if ((qglXChooseVisual = GL_GetProcAddress("glXChooseVisual")) == NULL
751          || (qglXCreateContext = GL_GetProcAddress("glXCreateContext")) == NULL
752          || (qglXMakeCurrent = GL_GetProcAddress("glXMakeCurrent")) == NULL
753          || (qglXSwapBuffers = GL_GetProcAddress("glXSwapBuffers")) == NULL
754          || (qglXQueryExtensionsString = GL_GetProcAddress("glXQueryExtensionsString")) == NULL)
755         {
756                 Con_Printf("glX functions not found in %s\n", gl_driver);
757                 return false;
758         }
759
760         VID_BuildGLXAttrib(attrib, bpp == 32);
761         visinfo = qglXChooseVisual(vidx11_display, vidx11_screen, attrib);
762         if (!visinfo)
763         {
764                 Con_Print("Couldn't get an RGB, Double-buffered, Depth visual\n");
765                 return false;
766         }
767
768         if (vidmode_ext)
769         {
770                 int best_fit, best_dist, dist, x, y;
771
772                 // Are we going fullscreen?  If so, let's change video mode
773                 if (fullscreen)
774                 {
775                         XF86VidModeGetAllModeLines(vidx11_display, vidx11_screen, &num_vidmodes, &vidmodes);
776                         best_dist = 9999999;
777                         best_fit = -1;
778
779                         for (i = 0; i < num_vidmodes; i++)
780                         {
781                                 if (width > vidmodes[i]->hdisplay || height > vidmodes[i]->vdisplay)
782                                         continue;
783
784                                 x = width - vidmodes[i]->hdisplay;
785                                 y = height - vidmodes[i]->vdisplay;
786                                 dist = (x * x) + (y * y);
787                                 if (dist < best_dist)
788                                 {
789                                         best_dist = dist;
790                                         best_fit = i;
791                                 }
792                         }
793
794                         if (best_fit != -1)
795                         {
796                                 // LordHavoc: changed from ActualWidth/ActualHeight =,
797                                 // to width/height =, so the window will take the full area of
798                                 // the mode chosen
799                                 width = vidmodes[best_fit]->hdisplay;
800                                 height = vidmodes[best_fit]->vdisplay;
801
802                                 // change to the mode
803                                 XF86VidModeSwitchToMode(vidx11_display, vidx11_screen, vidmodes[best_fit]);
804                                 vid_isfullscreen = true;
805
806                                 // Move the viewport to top left
807                                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
808                         }
809                         else
810                                 fullscreen = 0;
811                 }
812         }
813
814         // LordHavoc: save the visual for use in gamma ramp settings later
815         vidx11_visual = visinfo->visual;
816
817         /* window attributes */
818         attr.background_pixel = 0;
819         attr.border_pixel = 0;
820         // LordHavoc: save the colormap for later, too
821         vidx11_colormap = attr.colormap = XCreateColormap(vidx11_display, root, visinfo->visual, AllocNone);
822         attr.event_mask = X_MASK;
823         if (vid_isfullscreen)
824         {
825                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | CWEventMask | CWOverrideRedirect;
826                 attr.override_redirect = True;
827                 attr.backing_store = NotUseful;
828                 attr.save_under = False;
829         }
830         else
831                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
832
833         win = XCreateWindow(vidx11_display, root, 0, 0, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr);
834         XStoreName(vidx11_display, win, gamename);
835         XMapWindow(vidx11_display, win);
836
837         // LordHavoc: making the close button on a window do the right thing
838         // seems to involve this mess, sigh...
839         wm_delete_window_atom = XInternAtom(vidx11_display, "WM_DELETE_WINDOW", false);
840         XSetWMProtocols(vidx11_display, win, &wm_delete_window_atom, 1);
841
842         if (vid_isfullscreen)
843         {
844                 XMoveWindow(vidx11_display, win, 0, 0);
845                 XRaiseWindow(vidx11_display, win);
846                 XWarpPointer(vidx11_display, None, win, 0, 0, 0, 0, 0, 0);
847                 XFlush(vidx11_display);
848                 // Move the viewport to top left
849                 XF86VidModeSetViewPort(vidx11_display, vidx11_screen, 0, 0);
850         }
851
852         //XSync(vidx11_display, False);
853
854         ctx = qglXCreateContext(vidx11_display, visinfo, NULL, True);
855         if (!ctx)
856                 Sys_Error ("glXCreateContext failed\n");
857
858         if (!qglXMakeCurrent(vidx11_display, win, ctx))
859                 Sys_Error ("glXMakeCurrent failed\n");
860
861         XSync(vidx11_display, False);
862
863         scr_width = width;
864         scr_height = height;
865
866         if ((qglGetString = GL_GetProcAddress("glGetString")) == NULL)
867                 Sys_Error("glGetString not found in %s", gl_driver);
868
869         gl_renderer = qglGetString(GL_RENDERER);
870         gl_vendor = qglGetString(GL_VENDOR);
871         gl_version = qglGetString(GL_VERSION);
872         gl_extensions = qglGetString(GL_EXTENSIONS);
873         gl_platform = "GLX";
874         gl_platformextensions = qglXQueryExtensionsString(vidx11_display, vidx11_screen);
875
876         gl_videosyncavailable = false;
877
878 // COMMANDLINEOPTION: Linux GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
879 // COMMANDLINEOPTION: BSD GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
880 // COMMANDLINEOPTION: MacOSX GLX: -nogetprocaddress disables GLX_ARB_get_proc_address (not required, more formal method of getting extension functions)
881         GL_CheckExtension("GLX_ARB_get_proc_address", getprocaddressfuncs, "-nogetprocaddress", false);
882 // COMMANDLINEOPTION: Linux GLX: -novideosync disables GLX_SGI_swap_control
883 // COMMANDLINEOPTION: BSD GLX: -novideosync disables GLX_SGI_swap_control
884 // COMMANDLINEOPTION: MacOSX GLX: -novideosync disables GLX_SGI_swap_control
885         gl_videosyncavailable = GL_CheckExtension("GLX_SGI_swap_control", swapcontrolfuncs, "-novideosync", false);
886
887         vid_usingmouse = false;
888         vid_usingvsync = false;
889         ignoremousemove = true;
890         vid_hidden = false;
891         vid_activewindow = true;
892         GL_Init();
893         return true;
894 }
895
896 void Sys_SendKeyEvents(void)
897 {
898         HandleEvents();
899 }
900
901 void IN_Move (void)
902 {
903         if (mouse_avail)
904         {
905                 in_mouse_x = mouse_x;
906                 in_mouse_y = mouse_y;
907         }
908         mouse_x = 0;
909         mouse_y = 0;
910 }