Fix for exit segfault preventing fullscreen cleanup, and for the segfault as well.
[divverent/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 "quakedef.h"
31
32 #include <GL/glx.h>
33
34 #include <X11/keysym.h>
35 #include <X11/cursorfont.h>
36
37 #include <X11/extensions/XShm.h>
38 #include <X11/extensions/xf86dga.h>
39 #include <X11/extensions/xf86vmode.h>
40
41 static Display *dpy = NULL;
42 static int scrnum;
43 static Window win;
44 static GLXContext ctx = NULL;
45
46 #define KEY_MASK (KeyPressMask | KeyReleaseMask)
47 #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | \
48                     PointerMotionMask | ButtonMotionMask )
49 #define X_MASK (KEY_MASK | MOUSE_MASK | VisibilityChangeMask | StructureNotifyMask )
50
51
52 unsigned                d_8to24table[256];
53 unsigned char   d_15to8table[65536];
54
55 cvar_t vid_mode = {"vid_mode", "0", false};
56 cvar_t vid_fullscreen = {"vid_fullscreen", "1"};
57
58 viddef_t        vid;                            // global video state
59
60 static qboolean         mouse_avail = true;
61 static qboolean         mouse_active = false;
62 // static qboolean              dga_active;
63 static float    mouse_x, mouse_y;
64 static float    old_mouse_x, old_mouse_y;
65 static int p_mouse_x, p_mouse_y;
66
67 static cvar_t in_mouse = {"in_mouse", "1", false};
68 static cvar_t in_dga = {"in_dga", "1", false};
69 static cvar_t in_dga_mouseaccel = {"in_dga_mouseaccel", "1", false};
70 static cvar_t m_filter = {"m_filter", "0"};
71 static cvar_t _windowed_mouse = {"_windowed_mouse", "1"};
72
73 qboolean vidmode_ext = false;
74
75 static int win_x, win_y;
76
77 static int scr_width, scr_height;
78
79 static XF86VidModeModeInfo **vidmodes;
80 //static int default_dotclock_vidmode;
81 static int num_vidmodes;
82 static qboolean vidmode_active = false;
83
84 /*-----------------------------------------------------------------------*/
85
86 int             texture_extension_number = 1;
87
88 float           gldepthmin, gldepthmax;
89
90 const char *gl_vendor;
91 const char *gl_renderer;
92 const char *gl_version;
93 const char *gl_extensions;
94
95 void (*qglMTexCoord2f) (GLenum, GLfloat, GLfloat);
96 void (*qglSelectTexture) (GLenum);
97
98 //static float vid_gamma = 1.0;
99
100 // LordHavoc: ARB multitexture support
101 int gl_mtex_enum = 0;
102
103 // LordHavoc: in GLX these are never set, simply provided to make the rest of the code work
104 qboolean isG200 = false;
105 qboolean isRagePro = false;
106 qboolean gl_mtexable = false;
107 qboolean gl_arrays = false;
108
109 /*-----------------------------------------------------------------------*/
110 static int
111 XLateKey(XKeyEvent *ev/*, qboolean modified*/)
112 {
113 //      char tmp[2];
114         int key = 0;
115         KeySym keysym;
116
117         keysym = XLookupKeysym(ev, 0);
118
119         switch(keysym) {
120                 case XK_KP_Page_Up:     key = KP_PGUP; break;
121                 case XK_Page_Up:        key = K_PGUP; break;
122
123                 case XK_KP_Page_Down:   key = KP_PGDN; break;
124                 case XK_Page_Down:      key = K_PGDN; break;
125
126                 case XK_KP_Home:        key = KP_HOME; break;
127                 case XK_Home:           key = K_HOME; break;
128
129                 case XK_KP_End:         key = KP_END; break;
130                 case XK_End:            key = K_END; break;
131
132                 case XK_KP_Left:        key = KP_LEFTARROW; break;
133                 case XK_Left:           key = K_LEFTARROW; break;
134
135                 case XK_KP_Right:       key = KP_RIGHTARROW; break;
136                 case XK_Right:          key = K_RIGHTARROW; break;
137
138                 case XK_KP_Down:        key = KP_DOWNARROW; break;
139                 case XK_Down:           key = K_DOWNARROW; break;
140
141                 case XK_KP_Up:          key = KP_UPARROW; break;
142                 case XK_Up:                     key = K_UPARROW; break;
143
144                 case XK_Escape:         key = K_ESCAPE; break;
145
146                 case XK_KP_Enter:       key = KP_ENTER; break;
147                 case XK_Return:         key = K_ENTER; break;
148
149                 case XK_Tab:            key = K_TAB; break;
150
151                 case XK_F1:                     key = K_F1; break;
152                 case XK_F2:                     key = K_F2; break;
153                 case XK_F3:                     key = K_F3; break;
154                 case XK_F4:                     key = K_F4; break;
155                 case XK_F5:                     key = K_F5; break;
156                 case XK_F6:                     key = K_F6; break;
157                 case XK_F7:                     key = K_F7; break;
158                 case XK_F8:                     key = K_F8; break;
159                 case XK_F9:                     key = K_F9; break;
160                 case XK_F10:            key = K_F10; break;
161                 case XK_F11:            key = K_F11; break;
162                 case XK_F12:            key = K_F12; break;
163
164                 case XK_BackSpace:      key = K_BACKSPACE; break;
165
166                 case XK_KP_Delete:      key = KP_DEL; break;
167                 case XK_Delete:         key = K_DEL; break;
168
169                 case XK_Pause:          key = K_PAUSE; break;
170
171                 case XK_Shift_L:
172                 case XK_Shift_R:        key = K_SHIFT; break;
173
174                 case XK_Execute:
175                 case XK_Control_L:
176                 case XK_Control_R:      key = K_CTRL; break;
177
178                 case XK_Mode_switch:
179                 case XK_Alt_L:
180                 case XK_Meta_L:
181                 case XK_Alt_R:
182                 case XK_Meta_R:         key = K_ALT; break;
183
184                 case XK_Caps_Lock:      key = K_CAPSLOCK; break;
185                 case XK_KP_Begin:       key = KP_5; break;
186
187                 case XK_Insert:         key = K_INS; break;
188                 case XK_KP_Insert:      key = KP_INS; break;
189
190                 case XK_KP_Multiply:    key = KP_MULTIPLY; break;
191                 case XK_KP_Add:         key = KP_PLUS; break;
192                 case XK_KP_Subtract:    key = KP_MINUS; break;
193                 case XK_KP_Divide:      key = KP_DIVIDE; break;
194
195                 /* For Sun keyboards */
196                 case XK_F27:            key = K_HOME; break;
197                 case XK_F29:            key = K_PGUP; break;
198                 case XK_F33:            key = K_END; break;
199                 case XK_F35:            key = K_PGDN; break;
200
201                 default:
202                         if (keysym < 128) {
203                                 /* ASCII keys */
204                                 key = keysym;
205                                 if (/*!modified && */((key >= 'A') && (key <= 'Z'))) {
206                                         key = key + ('a' - 'A');
207                                 }
208                         }
209                         break;
210         }
211
212         return key;
213 }
214
215 static Cursor CreateNullCursor(Display *display, Window root)
216 {
217     Pixmap cursormask; 
218     XGCValues xgc;
219     GC gc;
220     XColor dummycolour;
221     Cursor cursor;
222
223     cursormask = XCreatePixmap(display, root, 1, 1, 1/*depth*/);
224     xgc.function = GXclear;
225     gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
226     XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
227     dummycolour.pixel = 0;
228     dummycolour.red = 0;
229     dummycolour.flags = 04;
230     cursor = XCreatePixmapCursor(display, cursormask, cursormask,
231           &dummycolour,&dummycolour, 0,0);
232     XFreePixmap(display,cursormask);
233     XFreeGC(display,gc);
234     return cursor;
235 }
236
237 static void install_grabs(void)
238 {
239         XWindowAttributes attribs_1;
240         XSetWindowAttributes attribs_2;
241
242         XGetWindowAttributes(dpy, win, &attribs_1);
243         attribs_2.event_mask = attribs_1.your_event_mask | KEY_MASK | MOUSE_MASK;
244         XChangeWindowAttributes(dpy, win, CWEventMask, &attribs_2);
245
246 // inviso cursor
247         XDefineCursor(dpy, win, CreateNullCursor(dpy, win));
248
249         XGrabPointer(dpy, win,  True, 0, GrabModeAsync, GrabModeAsync,
250                      win, None, CurrentTime);
251
252         if (in_dga.value) {
253                 int MajorVersion, MinorVersion;
254
255                 if (!XF86DGAQueryVersion(dpy, &MajorVersion, &MinorVersion)) { 
256                         // unable to query, probalby not supported
257                         Con_Printf( "Failed to detect XF86DGA Mouse\n" );
258                         in_dga.value = 0;
259                 } else {
260                         in_dga.value = 1;
261                         XF86DGADirectVideo(dpy, DefaultScreen(dpy), XF86DGADirectMouse);
262                         XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0);
263                 }
264         } else {
265                 XWarpPointer(dpy, None, win,
266                                          0, 0, 0, 0,
267                                          vid.width / 2, vid.height / 2);
268         }
269
270         XGrabKeyboard(dpy, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
271
272         mouse_active = true;
273         mouse_x = mouse_y = 0;
274
275 //      XSync(dpy, True);
276 }
277
278 static void uninstall_grabs(void)
279 {
280         if (!dpy || !win)
281                 return;
282
283         if (in_dga.value == 1) {
284                 XF86DGADirectVideo(dpy, DefaultScreen(dpy), 0);
285         }
286
287         XUngrabPointer(dpy, CurrentTime);
288         XUngrabKeyboard(dpy, CurrentTime);
289
290 // inviso cursor
291         XUndefineCursor(dpy, win);
292
293         mouse_active = false;
294 }
295
296 static void HandleEvents(void)
297 {
298         XEvent event;
299 //      KeySym ks;
300         int b;
301         qboolean dowarp = false;
302
303         if (!dpy)
304                 return;
305
306         while (XPending(dpy)) {
307                 XNextEvent(dpy, &event);
308
309                 switch (event.type) {
310                 case KeyPress:
311                 case KeyRelease:
312                         Key_Event(XLateKey(&event.xkey), event.type == KeyPress);
313                         break;
314
315                 case MotionNotify:
316                         if (in_dga.value == 1) {
317                                 mouse_x += event.xmotion.x_root * in_dga_mouseaccel.value;
318                                 mouse_y += event.xmotion.y_root * in_dga_mouseaccel.value;
319                         } else {
320                                 if (!p_mouse_x && !p_mouse_y) {
321                                         Con_Printf("event->xmotion.x: %d\n", event.xmotion.x);
322                                         Con_Printf("event->xmotion.y: %d\n", event.xmotion.y);
323                                 }
324                                 if (vid_fullscreen.value || _windowed_mouse.value) {
325                                         if (!event.xmotion.send_event) {
326                                                 mouse_x += (event.xmotion.x - p_mouse_x);
327                                                 mouse_y += (event.xmotion.y - p_mouse_y);
328                                                 if (abs(vid.width/2 - event.xmotion.x) > vid.width / 4
329                                                 || abs(vid.height/2 - event.xmotion.y) > vid.height / 4) {
330                                                         dowarp = true;
331                                                 }
332                                         }
333                                 } else {
334                                         mouse_x += (event.xmotion.x - p_mouse_x);
335                                         mouse_y += (event.xmotion.y - p_mouse_y);
336                                 }
337                                 p_mouse_x = event.xmotion.x;
338                                 p_mouse_y = event.xmotion.y;
339                         }
340                         break;
341
342                 case ButtonPress:
343                         b=-1;
344                         if (event.xbutton.button == 1)
345                                 b = 0;
346                         else if (event.xbutton.button == 2)
347                                 b = 2;
348                         else if (event.xbutton.button == 3)
349                                 b = 1;
350                         if (b>=0)
351                                 Key_Event(K_MOUSE1 + b, true);
352                         break;
353
354                 case ButtonRelease:
355                         b=-1;
356                         if (event.xbutton.button == 1)
357                                 b = 0;
358                         else if (event.xbutton.button == 2)
359                                 b = 2;
360                         else if (event.xbutton.button == 3)
361                                 b = 1;
362                         if (b>=0)
363                                 Key_Event(K_MOUSE1 + b, false);
364                         break;
365
366                 case CreateNotify :
367                         win_x = event.xcreatewindow.x;
368                         win_y = event.xcreatewindow.y;
369                         break;
370
371                 case ConfigureNotify :
372                         win_x = event.xconfigure.x;
373                         win_y = event.xconfigure.y;
374                         break;
375                 }
376         }
377
378         if (dowarp) {
379                 /* move the mouse to the window center again */
380                 p_mouse_x = vid.width / 2;
381                 p_mouse_y = vid.height / 2;
382                 XWarpPointer(dpy, None, win, 0, 0, 0, 0, p_mouse_x, p_mouse_y);
383         }
384
385 }
386
387 static void IN_DeactivateMouse( void ) 
388 {
389         if (!mouse_avail || !dpy || !win)
390                 return;
391
392         if (mouse_active) {
393                 uninstall_grabs();
394                 mouse_active = false;
395         }
396 }
397
398 static void IN_ActivateMouse( void ) 
399 {
400         if (!mouse_avail || !dpy || !win)
401                 return;
402
403         if (!mouse_active) {
404                 mouse_x = mouse_y = 0; // don't spazz
405                 install_grabs();
406                 mouse_active = true;
407         }
408 }
409
410
411 void VID_Shutdown(void)
412 {
413         if (!ctx || !dpy)
414                 return;
415
416         if (dpy) {
417                 uninstall_grabs();
418
419                 if (vidmode_active)
420                         XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[0]);
421 /* Disabled, causes a segfault during shutdown.
422                 if (ctx)
423                         glXDestroyContext(dpy, ctx);
424 */
425                 if (win)
426                         XDestroyWindow(dpy, win);
427                 XCloseDisplay(dpy);
428         }
429         vidmode_active = false;
430         dpy = NULL;
431         win = 0;
432         ctx = NULL;
433 }
434
435 void signal_handler(int sig)
436 {
437         printf("Received signal %d, exiting...\n", sig);
438         Sys_Quit();
439         exit(0);
440 }
441
442 void InitSig(void)
443 {
444         signal(SIGHUP, signal_handler);
445         signal(SIGINT, signal_handler);
446         signal(SIGQUIT, signal_handler);
447         signal(SIGILL, signal_handler);
448         signal(SIGTRAP, signal_handler);
449         signal(SIGIOT, signal_handler);
450         signal(SIGBUS, signal_handler);
451         signal(SIGFPE, signal_handler);
452         signal(SIGSEGV, signal_handler);
453         signal(SIGTERM, signal_handler);
454 }
455
456 /*
457 void (*qglVertexPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr);
458 void (*qglColorPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr);
459 void (*qglTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr);
460 void (*qglArrayElement)(GLint i);
461 void (*qglDrawElements)(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
462 void (*qglMTexCoord2f)(GLenum, GLfloat, GLfloat);
463 void (*qglSelectTexture)(GLenum);
464
465 void VID_CheckVertexArrays (void)
466 {
467         void *prjobj;
468         if (COM_CheckParm("-novertex"))
469         {
470                 Con_Printf("...vertex array support disabled\n");
471                 return;
472         }
473         if ((prjobj = dlopen(NULL, RTLD_LAZY)) == NULL)
474         {
475                 Con_Printf("Unable to open symbol list for main program.\n");
476                 return;
477         }
478         qglMTexCoord2fSGIS = (void *) dlsym(prjobj, "glMTexCoord2fSGIS");
479         if ((qglArrayElement = (void *) dlsym(prjobj, "glArrayElement"))
480          && (qglColorPointer = (void *) dlsym(prjobj, "glColorPointer"))
481 //       && (qglDrawArrays = (void *) dlsym(prjobj, "glDrawArrays"))
482          && (qglDrawElements = (void *) dlsym(prjobj, "glDrawElements"))
483 //       && (qglInterleavedArrays = (void *) dlsym(prjobj, "glInterleavedArrays"))
484          && (qglTexCoordPointer = (void *) dlsym(prjobj, "glTexCoordPointer"))
485          && (qglVertexPointer = (void *) dlsym(prjobj, "glVertexPointer"))
486                 )
487         {
488                 Con_Printf("...vertex array support detected\n");
489                 gl_arrays = true;
490                 dlclose(prjobj);
491                 return;
492         }
493
494         Con_Printf("...vertex array support disabled (not detected - get a better driver)\n");
495         dlclose(prjobj);
496 }
497 */
498
499 // LordHavoc: require OpenGL 1.2.x
500 void VID_CheckVertexArrays (void)
501 {
502         gl_arrays = true;
503 }
504
505 void VID_CheckMultitexture(void) 
506 {
507         void *prjobj;
508         qglMTexCoord2f = NULL;
509         qglSelectTexture = NULL;
510         // Check to see if multitexture is disabled
511         if (COM_CheckParm("-nomtex"))
512         {
513                 Con_Printf("...multitexture disabled\n");
514                 return;
515         }
516         if ((prjobj = dlopen(NULL, RTLD_LAZY)) == NULL)
517         {
518                 Con_Printf("Unable to open symbol list for main program.\n");
519                 return;
520         }
521         // Test for ARB_multitexture
522         if (!COM_CheckParm("-SGISmtex") && strstr(gl_extensions, "GL_ARB_multitexture "))
523         {
524                 Con_Printf("...using GL_ARB_multitexture\n");
525                 qglMTexCoord2f = (void *) dlsym(prjobj, "glMultiTexCoord2fARB");
526                 qglSelectTexture = (void *) dlsym(prjobj, "glActiveTextureARB");
527                 gl_mtexable = true;
528                 gl_mtex_enum = GL_TEXTURE0_ARB;
529         }
530         else if (strstr(gl_extensions, "GL_SGIS_multitexture ")) // Test for SGIS_multitexture (if ARB_multitexture not found)
531         {
532                 Con_Printf("...using GL_SGIS_multitexture\n");
533                 qglMTexCoord2f = (void *) dlsym(prjobj, "glMTexCoord2fSGIS");
534                 qglSelectTexture = (void *) dlsym(prjobj, "glSelectTextureSGIS");
535                 gl_mtexable = true;
536                 gl_mtex_enum = TEXTURE0_SGIS;
537         }
538         if (!gl_mtexable)
539                 Con_Printf("...multitexture disabled (not detected)\n");
540         dlclose(prjobj);
541 }
542
543 /*
544 =================
545 GL_BeginRendering
546
547 =================
548 */
549 void GL_BeginRendering (int *x, int *y, int *width, int *height)
550 {
551         *x = *y = 0;
552         *width = scr_width;
553         *height = scr_height;
554
555 //      glViewport (*x, *y, *width, *height);
556 }
557
558
559 void GL_EndRendering (void)
560 {
561         if (!r_render.value)
562                 return;
563         glFlush();
564         glXSwapBuffers(dpy, win);
565 }
566
567 void VID_Init()
568 {
569         int i;
570         int attrib[] = {
571                 GLX_RGBA,
572                 GLX_RED_SIZE, 1,
573                 GLX_GREEN_SIZE, 1,
574                 GLX_BLUE_SIZE, 1,
575                 GLX_DOUBLEBUFFER,
576                 GLX_DEPTH_SIZE, 1,
577                 None
578         };
579 //      char    gldir[MAX_OSPATH];
580         int width = 640, height = 480;
581         XSetWindowAttributes attr;
582         unsigned long mask;
583         Window root;
584         XVisualInfo *visinfo;
585         qboolean fullscreen = true;
586         int MajorVersion, MinorVersion;
587         int actualWidth, actualHeight;
588
589         Cvar_RegisterVariable (&vid_mode);
590         Cvar_RegisterVariable (&vid_fullscreen);
591         Cvar_RegisterVariable (&in_mouse);
592         Cvar_RegisterVariable (&in_dga);
593         Cvar_RegisterVariable (&in_dga_mouseaccel);
594         Cvar_RegisterVariable (&m_filter);
595         
596 // interpret command-line params
597
598 // set vid parameters
599         if ((i = COM_CheckParm("-window")) != 0)
600                 fullscreen = false;
601
602         if ((i = COM_CheckParm("-width")) != 0)
603                 width = atoi(com_argv[i+1]);
604
605         if ((i = COM_CheckParm("-height")) != 0)
606                 height = atoi(com_argv[i+1]);
607
608         if ((i = COM_CheckParm("-conwidth")) != 0)
609                 vid.conwidth = atoi(com_argv[i+1]);
610         else
611                 vid.conwidth = 640;
612
613         vid.conwidth &= 0xfff8; // make it a multiple of eight
614
615         if (vid.conwidth < 320)
616                 vid.conwidth = 320;
617
618         // pick a conheight that matches with correct aspect
619         vid.conheight = vid.conwidth*3 / 4;
620
621         if ((i = COM_CheckParm("-conheight")) != 0)
622                 vid.conheight = atoi(com_argv[i+1]);
623         if (vid.conheight < 200)
624                 vid.conheight = 200;
625
626         if (!(dpy = XOpenDisplay(NULL))) {
627                 fprintf(stderr, "Error couldn't open the X display\n");
628                 exit(1);
629         }
630
631         scrnum = DefaultScreen(dpy);
632         root = RootWindow(dpy, scrnum);
633
634         // Get video mode list
635         MajorVersion = MinorVersion = 0;
636         if (!XF86VidModeQueryVersion(dpy, &MajorVersion, &MinorVersion)) { 
637                 vidmode_ext = false;
638         } else {
639                 Con_Printf("Using XFree86-VidModeExtension Version %d.%d\n", MajorVersion, MinorVersion);
640                 vidmode_ext = true;
641         }
642
643         visinfo = glXChooseVisual(dpy, scrnum, attrib);
644         if (!visinfo) {
645                 fprintf(stderr, "qkHack: Error couldn't get an RGB, Double-buffered, Depth visual\n");
646                 exit(1);
647         }
648
649         if (vidmode_ext) {
650                 int best_fit, best_dist, dist, x, y;
651                 
652                 XF86VidModeGetAllModeLines(dpy, scrnum, &num_vidmodes, &vidmodes);
653
654                 // Are we going fullscreen?  If so, let's change video mode
655                 if (fullscreen) {
656                         best_dist = 9999999;
657                         best_fit = -1;
658
659                         for (i = 0; i < num_vidmodes; i++) {
660                                 if (width > vidmodes[i]->hdisplay ||
661                                         height > vidmodes[i]->vdisplay)
662                                         continue;
663
664                                 x = width - vidmodes[i]->hdisplay;
665                                 y = height - vidmodes[i]->vdisplay;
666                                 dist = (x * x) + (y * y);
667                                 if (dist < best_dist) {
668                                         best_dist = dist;
669                                         best_fit = i;
670                                 }
671                         }
672
673                         if (best_fit != -1) {
674                                 actualWidth = vidmodes[best_fit]->hdisplay;
675                                 actualHeight = vidmodes[best_fit]->vdisplay;
676
677                                 // change to the mode
678                                 XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[best_fit]);
679                                 vidmode_active = true;
680
681                                 // Move the viewport to top left
682                                 XF86VidModeSetViewPort(dpy, scrnum, 0, 0);
683                         } else
684                                 fullscreen = 0;
685                 }
686         }
687
688         /* window attributes */
689         attr.background_pixel = 0;
690         attr.border_pixel = 0;
691         attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
692         attr.event_mask = X_MASK;
693         if (vidmode_active) {
694                 mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | 
695                         CWEventMask | CWOverrideRedirect;
696                 attr.override_redirect = True;
697                 attr.backing_store = NotUseful;
698                 attr.save_under = False;
699         } else
700                 mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
701
702         win = XCreateWindow(dpy, root, 0, 0, width, height,
703                                                 0, visinfo->depth, InputOutput,
704                                                 visinfo->visual, mask, &attr);
705         XMapWindow(dpy, win);
706
707         if (vidmode_active) {
708                 XMoveWindow(dpy, win, 0, 0);
709                 XRaiseWindow(dpy, win);
710                 XWarpPointer(dpy, None, win, 0, 0, 0, 0, 0, 0);
711                 XFlush(dpy);
712                 // Move the viewport to top left
713                 XF86VidModeSetViewPort(dpy, scrnum, 0, 0);
714         }
715
716         XFlush(dpy);
717
718         ctx = glXCreateContext(dpy, visinfo, NULL, True);
719
720         glXMakeCurrent(dpy, win, ctx);
721
722         scr_width = width;
723         scr_height = height;
724
725         if (vid.conheight > height)
726                 vid.conheight = height;
727         if (vid.conwidth > width)
728                 vid.conwidth = width;
729         vid.width = vid.conwidth;
730         vid.height = vid.conheight;
731
732         vid.aspect = ((float)vid.height / (float)vid.width) * (320.0 / 240.0);
733
734         InitSig(); // trap evil signals
735
736         GL_Init();
737
738         Con_SafePrintf ("Video mode %dx%d initialized.\n", width, height);
739
740         vid.recalc_refdef = 1;                          // force a surface cache flush
741
742         install_grabs();
743 }
744
745 void Sys_SendKeyEvents(void)
746 {
747         HandleEvents();
748 }
749
750 void Force_CenterView_f (void)
751 {
752         cl.viewangles[PITCH] = 0;
753 }
754
755 void IN_Init(void)
756 {
757 }
758
759 void IN_Shutdown(void)
760 {
761 }
762
763 /*
764 ===========
765 IN_Commands
766 ===========
767 */
768 void IN_Commands (void)
769 {
770         if (!dpy || !win)
771                 return;
772
773         if (vidmode_active || key_dest == key_game)
774                 IN_ActivateMouse();
775         else
776                 IN_DeactivateMouse ();
777 }
778
779 /*
780 ===========
781 IN_Move
782 ===========
783 */
784 void IN_MouseMove (usercmd_t *cmd)
785 {
786         if (!mouse_avail)
787                 return;
788
789         if (!mouse_avail)
790                 return;
791
792         if (m_filter.value) {
793                 mouse_x = (mouse_x + old_mouse_x) * 0.5;
794                 mouse_y = (mouse_y + old_mouse_y) * 0.5;
795
796                 old_mouse_x = mouse_x;
797                 old_mouse_y = mouse_y;
798         }
799
800         mouse_x *= sensitivity.value;
801         mouse_y *= sensitivity.value;
802         
803         if (in_strafe.state & 1)
804                 cmd->sidemove += m_side.value * mouse_x;
805         else
806                 cl.viewangles[YAW] -= m_yaw.value * mouse_x;
807                 
808 /*        if (freelook)*/
809                 V_StopPitchDrift ();
810
811         if (/*freelook && */!(in_strafe.state & 1)) {
812                 cl.viewangles[PITCH] += m_pitch.value * mouse_y;
813                 cl.viewangles[PITCH] = bound (-70, cl.viewangles[PITCH], 80);
814         } else {
815                 if ((in_strafe.state & 1) && noclip_anglehack)
816                         cmd->upmove -= m_forward.value * mouse_y;
817                 else
818                         cmd->forwardmove -= m_forward.value * mouse_y;
819         }
820         mouse_x = mouse_y = 0.0;
821 }
822
823 void IN_Move (usercmd_t *cmd)
824 {
825         IN_MouseMove(cmd);
826 }
827
828