]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_wgl.c
fixed.
[xonotic/darkplaces.git] / vid_wgl.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 // gl_vidnt.c -- NT GL vid component
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "resource.h"
25 #include <commctrl.h>
26
27 int cl_available = true;
28
29 int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
30 int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
31 //int (WINAPI *qwglGetPixelFormat)(HDC);
32 BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
33 BOOL (WINAPI *qwglSwapBuffers)(HDC);
34 HGLRC (WINAPI *qwglCreateContext)(HDC);
35 BOOL (WINAPI *qwglDeleteContext)(HGLRC);
36 HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
37 HDC (WINAPI *qwglGetCurrentDC)(VOID);
38 PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
39 BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
40 BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
41 const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
42
43 static gl_extensionfunctionlist_t getextensionsstringfuncs[] =
44 {
45         {"wglGetExtensionsString", (void **) &qwglGetExtensionsStringARB},
46         {NULL, NULL}
47 };
48
49 static gl_extensionfunctionlist_t wglfuncs[] =
50 {
51         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
52         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
53 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
54         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
55         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
56         {"wglCreateContext", (void **) &qwglCreateContext},
57         {"wglDeleteContext", (void **) &qwglDeleteContext},
58         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
59         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
60         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
61         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
62         {NULL, NULL}
63 };
64
65 static gl_extensionfunctionlist_t wglswapintervalfuncs[] =
66 {
67         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
68         {NULL, NULL}
69 };
70
71 void VID_RestoreGameGamma(void);
72 void VID_GetSystemGamma(void);
73 void VID_RestoreSystemGamma(void);
74
75 qboolean scr_skipupdate;
76
77 static DEVMODE gdevmode;
78 static qboolean vid_initialized = false;
79 static qboolean vid_wassuspended = false;
80 static int vid_usingmouse;
81 extern qboolean mouseactive;  // from in_win.c
82 static HICON hIcon;
83
84 HWND mainwindow;
85
86 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
87
88 static int vid_isfullscreen;
89
90 //void VID_MenuDraw (void);
91 //void VID_MenuKey (int key);
92
93 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
94 //void AppActivate(BOOL fActive, BOOL minimize);
95 //void ClearAllStates (void);
96 //void VID_UpdateWindowStatus (void);
97
98 //====================================
99
100 int window_x, window_y, window_width, window_height;
101 int window_center_x, window_center_y;
102
103 void IN_ShowMouse (void);
104 void IN_DeactivateMouse (void);
105 void IN_HideMouse (void);
106 void IN_ActivateMouse (void);
107 void IN_MouseEvent (int mstate);
108 void IN_UpdateClipCursor (void);
109
110 qboolean mouseinitialized;
111 static qboolean dinput;
112
113 /*
114 ================
115 VID_UpdateWindowStatus
116 ================
117 */
118 void VID_UpdateWindowStatus (void)
119 {
120         window_center_x = window_x + window_width / 2;
121         window_center_y = window_y + window_height / 2;
122
123         if (mouseinitialized && mouseactive && !dinput)
124         {
125                 RECT window_rect;
126                 window_rect.left = window_x;
127                 window_rect.top = window_y;
128                 window_rect.right = window_x + window_width;
129                 window_rect.bottom = window_y + window_height;
130                 ClipCursor (&window_rect);
131         }
132 }
133
134
135 //====================================
136
137 /*
138 =================
139 VID_GetWindowSize
140 =================
141 */
142 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
143 {
144         *x = 0;
145         *y = 0;
146         *width = window_width;
147         *height = window_height;
148 }
149
150
151 void VID_Finish (void)
152 {
153         HDC hdc;
154         int vid_usemouse;
155         if (r_render.integer && !scr_skipupdate)
156         {
157                 qglFinish();
158                 hdc = GetDC(mainwindow);
159                 SwapBuffers(hdc);
160                 ReleaseDC(mainwindow, hdc);
161         }
162
163 // handle the mouse state when windowed if that's changed
164         vid_usemouse = false;
165         if (vid_mouse.integer && !key_consoleactive)
166                 vid_usemouse = true;
167         if (vid_isfullscreen)
168                 vid_usemouse = true;
169         if (!vid_activewindow)
170                 vid_usemouse = false;
171         if (vid_usemouse)
172         {
173                 if (!vid_usingmouse)
174                 {
175                         vid_usingmouse = true;
176                         IN_ActivateMouse ();
177                         IN_HideMouse();
178                 }
179         }
180         else
181         {
182                 if (vid_usingmouse)
183                 {
184                         vid_usingmouse = false;
185                         IN_DeactivateMouse ();
186                         IN_ShowMouse();
187                 }
188         }
189 }
190
191 //==========================================================================
192
193
194
195
196 qbyte scantokey[128] =
197 {
198 //      0           1      2     3     4     5       6       7      8         9      A       B           C     D            E           F
199         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'    ,'0'        ,'-'  ,'='         ,K_BACKSPACE,9     , // 0
200         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['    ,']'        ,13   ,K_CTRL      ,'a'        ,'s'   , // 1
201         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT,'\\'       ,'z'  ,'x'         ,'c'        ,'v'   , // 2
202         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2 ,K_F3        ,K_F4       ,K_F5  , // 3
203         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,'-'    ,K_LEFTARROW,'5'  ,K_RIGHTARROW,'+'        ,K_END , // 4
204         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 5
205         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 6
206         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0       // 7
207 };
208
209
210 /*
211 =======
212 MapKey
213
214 Map from windows to quake keynums
215 =======
216 */
217 int MapKey (int key, int virtualkey)
218 {
219         key = (key>>16)&255;
220         if (key > 127)
221                 return 0;
222         if (scantokey[key] == 0)
223                 Con_DPrintf("key 0x%02x has no translation\n", key);
224         return scantokey[key];
225 }
226
227 /*
228 ===================================================================
229
230 MAIN WINDOW
231
232 ===================================================================
233 */
234
235 /*
236 ================
237 ClearAllStates
238 ================
239 */
240 void ClearAllStates (void)
241 {
242         int             i;
243
244 // send an up event for each key, to make sure the server clears them all
245         for (i=0 ; i<256 ; i++)
246         {
247                 Key_Event (i, false);
248         }
249
250         Key_ClearStates ();
251         IN_ClearStates ();
252 }
253
254 void VID_RestoreGameGamma(void);
255 extern qboolean host_loopactive;
256
257 void AppActivate(BOOL fActive, BOOL minimize)
258 /****************************************************************************
259 *
260 * Function:     AppActivate
261 * Parameters:   fActive - True if app is activating
262 *
263 * Description:  If the application is activating, then swap the system
264 *               into SYSPAL_NOSTATIC mode so that our palettes will display
265 *               correctly.
266 *
267 ****************************************************************************/
268 {
269         static BOOL     sound_active;
270
271         vid_activewindow = fActive;
272         vid_hidden = minimize;
273
274 // enable/disable sound on focus gain/loss
275         if (!vid_activewindow && sound_active)
276         {
277                 S_BlockSound ();
278                 sound_active = false;
279         }
280         else if (vid_activewindow && !sound_active)
281         {
282                 S_UnblockSound ();
283                 sound_active = true;
284         }
285
286         if (fActive)
287         {
288                 if (vid_isfullscreen)
289                 {
290                         if (vid_wassuspended)
291                         {
292                                 vid_wassuspended = false;
293                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
294                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
295                         }
296
297                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
298                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
299                 }
300                 if (host_loopactive)
301                         VID_RestoreGameGamma();
302         }
303
304         if (!fActive)
305         {
306                 vid_usingmouse = false;
307                 IN_DeactivateMouse ();
308                 IN_ShowMouse ();
309                 if (vid_isfullscreen)
310                 {
311                         ChangeDisplaySettings (NULL, 0);
312                         vid_wassuspended = true;
313                 }
314                 VID_RestoreSystemGamma();
315         }
316 }
317
318 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
319
320 /* main window procedure */
321 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
322 {
323         LONG    lRet = 1;
324         int             fActive, fMinimized, temp;
325         extern unsigned int uiWheelMessage;
326
327         if ( uMsg == uiWheelMessage )
328                 uMsg = WM_MOUSEWHEEL;
329
330         switch (uMsg)
331         {
332                 case WM_KILLFOCUS:
333                         if (vid_isfullscreen)
334                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
335                         break;
336
337                 case WM_CREATE:
338                         break;
339
340                 case WM_MOVE:
341                         window_x = (int) LOWORD(lParam);
342                         window_y = (int) HIWORD(lParam);
343                         VID_UpdateWindowStatus ();
344                         break;
345
346                 case WM_KEYDOWN:
347                 case WM_SYSKEYDOWN:
348                         Key_Event (MapKey(lParam, wParam), true);
349                         break;
350
351                 case WM_KEYUP:
352                 case WM_SYSKEYUP:
353                         Key_Event (MapKey(lParam, wParam), false);
354                         break;
355
356                 case WM_SYSCHAR:
357                 // keep Alt-Space from happening
358                         break;
359
360         // this is complicated because Win32 seems to pack multiple mouse events into
361         // one update sometimes, so we always check all states and look for events
362                 case WM_LBUTTONDOWN:
363                 case WM_LBUTTONUP:
364                 case WM_RBUTTONDOWN:
365                 case WM_RBUTTONUP:
366                 case WM_MBUTTONDOWN:
367                 case WM_MBUTTONUP:
368                 case WM_MOUSEMOVE:
369                         temp = 0;
370
371                         if (wParam & MK_LBUTTON)
372                                 temp |= 1;
373
374                         if (wParam & MK_RBUTTON)
375                                 temp |= 2;
376
377                         if (wParam & MK_MBUTTON)
378                                 temp |= 4;
379
380                         IN_MouseEvent (temp);
381
382                         break;
383
384                 // JACK: This is the mouse wheel with the Intellimouse
385                 // Its delta is either positive or neg, and we generate the proper
386                 // Event.
387                 case WM_MOUSEWHEEL:
388                         if ((short) HIWORD(wParam) > 0) {
389                                 Key_Event(K_MWHEELUP, true);
390                                 Key_Event(K_MWHEELUP, false);
391                         } else {
392                                 Key_Event(K_MWHEELDOWN, true);
393                                 Key_Event(K_MWHEELDOWN, false);
394                         }
395                         break;
396
397                 case WM_SIZE:
398                         break;
399
400                 case WM_CLOSE:
401                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
402                                 Sys_Quit ();
403
404                         break;
405
406                 case WM_ACTIVATE:
407                         fActive = LOWORD(wParam);
408                         fMinimized = (BOOL) HIWORD(wParam);
409                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
410
411                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
412                         ClearAllStates ();
413
414                         break;
415
416                 case WM_DESTROY:
417                 {
418                         if (mainwindow)
419                                 DestroyWindow (mainwindow);
420
421                         PostQuitMessage (0);
422                 }
423                 break;
424
425                 case MM_MCINOTIFY:
426                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
427                         break;
428
429                 default:
430                         /* pass all unhandled messages to DefWindowProc */
431                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
432                 break;
433         }
434
435         /* return 1 if handled message, 0 if not */
436         return lRet;
437 }
438
439
440 //static int grabsysgamma = true;
441 WORD systemgammaramps[3][256], currentgammaramps[3][256];
442
443 int VID_SetGamma(float prescale, float gamma, float scale, float base)
444 {
445         int i;
446         HDC hdc;
447         hdc = GetDC (NULL);
448
449         BuildGammaTable16(prescale, gamma, scale, base, &currentgammaramps[0][0]);
450         for (i = 0;i < 256;i++)
451                 currentgammaramps[1][i] = currentgammaramps[2][i] = currentgammaramps[0][i];
452
453         i = SetDeviceGammaRamp(hdc, &currentgammaramps[0][0]);
454
455         ReleaseDC (NULL, hdc);
456         return i; // return success or failure
457 }
458
459 void VID_RestoreGameGamma(void)
460 {
461         VID_UpdateGamma(true);
462 }
463
464 void VID_GetSystemGamma(void)
465 {
466         HDC hdc;
467         hdc = GetDC (NULL);
468
469         GetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
470
471         ReleaseDC (NULL, hdc);
472 }
473
474 void VID_RestoreSystemGamma(void)
475 {
476         HDC hdc;
477         hdc = GetDC (NULL);
478
479         SetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
480
481         ReleaseDC (NULL, hdc);
482 }
483
484 //========================================================
485 // Video menu stuff
486 //========================================================
487
488 #if 0
489 extern void M_Menu_Options_f (void);
490 extern void M_Print (float cx, float cy, char *str);
491 extern void M_PrintWhite (float cx, float cy, char *str);
492 extern void M_DrawCharacter (float cx, float cy, int num);
493 extern void M_DrawPic (float cx, float cy, char *picname);
494
495 static int vid_wmodes;
496
497 typedef struct
498 {
499         int modenum;
500         char *desc;
501         int iscur;
502 } modedesc_t;
503
504 #define MAX_COLUMN_SIZE         9
505 #define MODE_AREA_HEIGHT        (MAX_COLUMN_SIZE + 2)
506 #define MAX_MODEDESCS           (MAX_COLUMN_SIZE*3)
507
508 static modedesc_t modedescs[MAX_MODEDESCS];
509
510 /*
511 ================
512 VID_MenuDraw
513 ================
514 */
515 void VID_MenuDraw (void)
516 {
517         cachepic_t *p;
518         char *ptr;
519         int lnummodes, i, k, column, row;
520         vmode_t *pv;
521
522         p = Draw_CachePic ("gfx/vidmodes.lmp");
523         M_DrawPic ( (320-p->width)/2, 4, "gfx/vidmodes.lmp");
524
525         vid_wmodes = 0;
526         lnummodes = VID_NumModes ();
527
528         for (i=1 ; (i<lnummodes) && (vid_wmodes < MAX_MODEDESCS) ; i++)
529         {
530                 ptr = VID_GetModeDescription (i);
531                 pv = VID_GetModePtr (i);
532
533                 k = vid_wmodes;
534
535                 modedescs[k].modenum = i;
536                 modedescs[k].desc = ptr;
537                 modedescs[k].iscur = 0;
538
539                 if (i == vid_modenum)
540                         modedescs[k].iscur = 1;
541
542                 vid_wmodes++;
543
544         }
545
546         if (vid_wmodes > 0)
547         {
548                 M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)");
549
550                 column = 8;
551                 row = 36+2*8;
552
553                 for (i=0 ; i<vid_wmodes ; i++)
554                 {
555                         if (modedescs[i].iscur)
556                                 M_PrintWhite (column, row, modedescs[i].desc);
557                         else
558                                 M_Print (column, row, modedescs[i].desc);
559
560                         column += 13*8;
561
562                         if ((i % VID_ROW_SIZE) == (VID_ROW_SIZE - 1))
563                         {
564                                 column = 8;
565                                 row += 8;
566                         }
567                 }
568         }
569
570         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*2, "Video modes must be set from the");
571         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "command line with -width <width>");
572         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, "and -bpp <bits-per-pixel>");
573         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Select windowed mode with -window");
574 }
575
576
577 /*
578 ================
579 VID_MenuKey
580 ================
581 */
582 void VID_MenuKey (int key)
583 {
584         switch (key)
585         {
586         case K_ESCAPE:
587                 S_LocalSound ("misc/menu1.wav");
588                 M_Menu_Options_f ();
589                 break;
590
591         default:
592                 break;
593         }
594 }
595 #endif
596
597 static HINSTANCE gldll;
598
599 int GL_OpenLibrary(const char *name)
600 {
601         Con_Printf("Loading GL driver %s\n", name);
602         GL_CloseLibrary();
603         if (!(gldll = LoadLibrary(name)))
604         {
605                 Con_Printf("Unable to LoadLibrary %s\n", name);
606                 return false;
607         }
608         strcpy(gl_driver, name);
609         return true;
610 }
611
612 void GL_CloseLibrary(void)
613 {
614         FreeLibrary(gldll);
615         gldll = 0;
616         gl_driver[0] = 0;
617         qwglGetProcAddress = NULL;
618         gl_extensions = "";
619         gl_platform = "";
620         gl_platformextensions = "";
621 }
622
623 void *GL_GetProcAddress(const char *name)
624 {
625         void *p = NULL;
626         if (qwglGetProcAddress != NULL)
627                 p = (void *) qwglGetProcAddress(name);
628         if (p == NULL)
629                 p = (void *) GetProcAddress(gldll, name);
630         return p;
631 }
632
633 void VID_Init(void)
634 {
635         WNDCLASS wc;
636
637         InitCommonControls();
638         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON2));
639
640         // Register the frame class
641         wc.style         = 0;
642         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
643         wc.cbClsExtra    = 0;
644         wc.cbWndExtra    = 0;
645         wc.hInstance     = global_hInstance;
646         wc.hIcon         = 0;
647         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
648         wc.hbrBackground = NULL;
649         wc.lpszMenuName  = 0;
650         wc.lpszClassName = "DarkPlacesWindowClass";
651
652         if (!RegisterClass (&wc))
653                 Sys_Error("Couldn't register window class\n");
654 }
655
656 int VID_InitMode (int fullscreen, int width, int height, int bpp)
657 {
658         int i;
659         HDC hdc;
660         RECT rect;
661         MSG msg;
662         PIXELFORMATDESCRIPTOR pfd =
663         {
664                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
665                 1,                              // version number
666                 PFD_DRAW_TO_WINDOW              // support window
667                 |  PFD_SUPPORT_OPENGL   // support OpenGL
668                 |  PFD_DOUBLEBUFFER ,   // double buffered
669                 PFD_TYPE_RGBA,                  // RGBA type
670                 24,                             // 24-bit color depth
671                 0, 0, 0, 0, 0, 0,               // color bits ignored
672                 0,                              // no alpha buffer
673                 0,                              // shift bit ignored
674                 0,                              // no accumulation buffer
675                 0, 0, 0, 0,                     // accum bits ignored
676                 32,                             // 32-bit z-buffer
677                 0,                              // no stencil buffer
678                 0,                              // no auxiliary buffer
679                 PFD_MAIN_PLANE,                 // main layer
680                 0,                              // reserved
681                 0, 0, 0                         // layer masks ignored
682         };
683         int pixelformat;
684         DWORD WindowStyle, ExWindowStyle;
685         HGLRC baseRC;
686         int CenterX, CenterY;
687
688         if (vid_initialized)
689                 Sys_Error("VID_InitMode called when video is already initialised\n");
690
691         if (!GL_OpenLibrary("opengl32.dll"))
692         {
693                 Con_Printf("Unable to load GL driver\n");
694                 return false;
695         }
696
697         memset(&gdevmode, 0, sizeof(gdevmode));
698
699         VID_GetSystemGamma();
700
701         vid_isfullscreen = false;
702         if (fullscreen)
703         {
704                 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
705                 gdevmode.dmBitsPerPel = bpp;
706                 gdevmode.dmPelsWidth = width;
707                 gdevmode.dmPelsHeight = height;
708                 gdevmode.dmSize = sizeof (gdevmode);
709                 if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
710                 {
711                         VID_Shutdown();
712                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
713                         return false;
714                 }
715
716                 vid_isfullscreen = true;
717                 WindowStyle = WS_POPUP;
718                 ExWindowStyle = 0;
719         }
720         else
721         {
722                 hdc = GetDC (NULL);
723                 i = GetDeviceCaps(hdc, RASTERCAPS);
724                 ReleaseDC (NULL, hdc);
725                 if (i & RC_PALETTE)
726                 {
727                         VID_Shutdown();
728                         Con_Printf ("Can't run in non-RGB mode\n");
729                         return false;
730                 }
731
732                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
733                 ExWindowStyle = 0;
734         }
735
736         rect.top = 0;
737         rect.left = 0;
738         rect.right = width;
739         rect.bottom = height;
740         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
741
742         if (fullscreen)
743         {
744                 CenterX = 0;
745                 CenterY = 0;
746         }
747         else
748         {
749                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
750                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
751         }
752         CenterX = max(0, CenterX);
753         CenterY = max(0, CenterY);
754
755         // x and y may be changed by WM_MOVE messages
756         window_x = CenterX;
757         window_y = CenterY;
758         window_width = width;
759         window_height = height;
760         rect.left += CenterX;
761         rect.right += CenterX;
762         rect.top += CenterY;
763         rect.bottom += CenterY;
764
765         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
766         if (!mainwindow)
767         {
768                 VID_Shutdown();
769                 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %d, %p) failed\n", ExWindowStyle, gamename, gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
770                 return false;
771         }
772
773         /*
774         if (!fullscreen)
775                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
776         */
777
778         ShowWindow (mainwindow, SW_SHOWDEFAULT);
779         UpdateWindow (mainwindow);
780
781         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
782         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
783
784         VID_UpdateWindowStatus ();
785
786         // now we try to make sure we get the focus on the mode switch, because
787         // sometimes in some systems we don't.  We grab the foreground, then
788         // finish setting up, pump all our messages, and sleep for a little while
789         // to let messages finish bouncing around the system, then we put
790         // ourselves at the top of the z order, then grab the foreground again,
791         // Who knows if it helps, but it probably doesn't hurt
792         SetForegroundWindow (mainwindow);
793
794         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
795         {
796                 TranslateMessage (&msg);
797                 DispatchMessage (&msg);
798         }
799
800         Sleep (100);
801
802         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
803
804         SetForegroundWindow (mainwindow);
805
806         // fix the leftover Alt from any Alt-Tab or the like that switched us away
807         ClearAllStates ();
808         
809         hdc = GetDC(mainwindow);
810
811         if ((pixelformat = ChoosePixelFormat(hdc, &pfd)) == 0)
812         {
813                 VID_Shutdown();
814                 Con_Printf("ChoosePixelFormat(%d, %p) failed\n", hdc, &pfd);
815                 return false;
816         }
817
818         if (SetPixelFormat(hdc, pixelformat, &pfd) == false)
819         {
820                 VID_Shutdown();
821                 Con_Printf("SetPixelFormat(%d, %d, %p) failed\n", hdc, pixelformat, &pfd);
822                 return false;
823         }
824
825         if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
826         {
827                 VID_Shutdown();
828                 Con_Printf("wgl functions not found\n");
829                 return false;
830         }
831
832         baseRC = qwglCreateContext(hdc);
833         if (!baseRC)
834         {
835                 VID_Shutdown();
836                 Con_Printf("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
837                 return false;
838         }
839         if (!qwglMakeCurrent(hdc, baseRC))
840         {
841                 VID_Shutdown();
842                 Con_Printf("wglMakeCurrent(%d, %d) failed\n", hdc, baseRC);
843                 return false;
844         }
845
846         qglGetString = GL_GetProcAddress("glGetString");
847         qwglGetExtensionsStringARB = GL_GetProcAddress("wglGetExtensionsStringARB");
848         if (qglGetString == NULL)
849         {
850                 VID_Shutdown();
851                 Con_Printf("glGetString not found\n");
852                 return false;
853         }
854         gl_renderer = qglGetString(GL_RENDERER);
855         gl_vendor = qglGetString(GL_VENDOR);
856         gl_version = qglGetString(GL_VERSION);
857         gl_extensions = qglGetString(GL_EXTENSIONS);
858         gl_platform = "WGL";
859         gl_platformextensions = "";
860
861         if (qwglGetExtensionsStringARB)
862                 gl_platformextensions = qwglGetExtensionsStringARB(hdc);
863
864         gl_videosyncavailable = GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, NULL, false);
865         ReleaseDC(mainwindow, hdc);
866
867         GL_Init ();
868
869         // LordHavoc: special differences for ATI (broken 8bit color when also using 32bit? weird!)
870         if (strncasecmp(gl_vendor,"ATI",3)==0)
871         {
872                 if (strncasecmp(gl_renderer,"Rage Pro",8)==0)
873                         isRagePro = true;
874         }
875         if (strncasecmp(gl_renderer,"Matrox G200 Direct3D",20)==0) // a D3D driver for GL? sigh...
876                 isG200 = true;
877
878         //vid_menudrawfn = VID_MenuDraw;
879         //vid_menukeyfn = VID_MenuKey;
880         vid_hidden = false;
881         vid_initialized = true;
882         return true;
883 }
884
885 void VID_Shutdown (void)
886 {
887         HGLRC hRC = 0;
888         HDC hDC = 0;
889
890         if (vid_initialized)
891         {
892                 vid_initialized = false;
893                 if (qwglGetCurrentContext)
894                         hRC = qwglGetCurrentContext();
895                 if (qwglGetCurrentDC)
896                         hDC = qwglGetCurrentDC();
897
898                 if (qwglMakeCurrent)
899                         qwglMakeCurrent(NULL, NULL);
900
901                 if (hRC && qwglDeleteContext)
902                         qwglDeleteContext(hRC);
903
904                 // close the library before we get rid of the window
905                 GL_CloseLibrary();
906
907                 if (hDC && mainwindow)
908                         ReleaseDC(mainwindow, hDC);
909
910                 if (vid_isfullscreen)
911                         ChangeDisplaySettings (NULL, 0);
912
913                 AppActivate(false, false);
914
915                 VID_RestoreSystemGamma();
916         }
917 }
918
919
920 // input code
921
922 #include <dinput.h>
923
924 #define DINPUT_BUFFERSIZE           16
925 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
926
927 HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion,
928         LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
929
930 // mouse variables
931 int                     mouse_buttons;
932 int                     mouse_oldbuttonstate;
933 POINT           current_pos;
934 int                     mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum;
935
936 static qboolean restore_spi;
937 static int              originalmouseparms[3], newmouseparms[3] = {0, 0, 1};
938
939 unsigned int uiWheelMessage;
940 qboolean        mouseactive;
941 //qboolean              mouseinitialized;
942 static qboolean mouseparmsvalid, mouseactivatetoggle;
943 static qboolean mouseshowtoggle = 1;
944 static qboolean dinput_acquired;
945
946 static unsigned int             mstate_di;
947
948 // joystick defines and variables
949 // where should defines be moved?
950 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
951 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
952 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
953 #define JOY_AXIS_X                      0
954 #define JOY_AXIS_Y                      1
955 #define JOY_AXIS_Z                      2
956 #define JOY_AXIS_R                      3
957 #define JOY_AXIS_U                      4
958 #define JOY_AXIS_V                      5
959
960 enum _ControlList
961 {
962         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
963 };
964
965 DWORD   dwAxisFlags[JOY_MAX_AXES] =
966 {
967         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
968 };
969
970 DWORD   dwAxisMap[JOY_MAX_AXES];
971 DWORD   dwControlMap[JOY_MAX_AXES];
972 PDWORD  pdwRawValue[JOY_MAX_AXES];
973
974 // none of these cvars are saved over a session
975 // this means that advanced controller configuration needs to be executed
976 // each time.  this avoids any problems with getting back to a default usage
977 // or when changing from one controller to another.  this way at least something
978 // works.
979 cvar_t  in_joystick = {CVAR_SAVE, "joystick","0"};
980 cvar_t  joy_name = {0, "joyname", "joystick"};
981 cvar_t  joy_advanced = {0, "joyadvanced", "0"};
982 cvar_t  joy_advaxisx = {0, "joyadvaxisx", "0"};
983 cvar_t  joy_advaxisy = {0, "joyadvaxisy", "0"};
984 cvar_t  joy_advaxisz = {0, "joyadvaxisz", "0"};
985 cvar_t  joy_advaxisr = {0, "joyadvaxisr", "0"};
986 cvar_t  joy_advaxisu = {0, "joyadvaxisu", "0"};
987 cvar_t  joy_advaxisv = {0, "joyadvaxisv", "0"};
988 cvar_t  joy_forwardthreshold = {0, "joyforwardthreshold", "0.15"};
989 cvar_t  joy_sidethreshold = {0, "joysidethreshold", "0.15"};
990 cvar_t  joy_pitchthreshold = {0, "joypitchthreshold", "0.15"};
991 cvar_t  joy_yawthreshold = {0, "joyyawthreshold", "0.15"};
992 cvar_t  joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0"};
993 cvar_t  joy_sidesensitivity = {0, "joysidesensitivity", "-1.0"};
994 cvar_t  joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0"};
995 cvar_t  joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0"};
996 cvar_t  joy_wwhack1 = {0, "joywwhack1", "0.0"};
997 cvar_t  joy_wwhack2 = {0, "joywwhack2", "0.0"};
998
999 qboolean        joy_avail, joy_advancedinit, joy_haspov;
1000 DWORD           joy_oldbuttonstate, joy_oldpovstate;
1001
1002 int                     joy_id;
1003 DWORD           joy_flags;
1004 DWORD           joy_numbuttons;
1005
1006 static LPDIRECTINPUT            g_pdi;
1007 static LPDIRECTINPUTDEVICE      g_pMouse;
1008
1009 static JOYINFOEX        ji;
1010
1011 static HINSTANCE hInstDI;
1012
1013 //static qboolean       dinput;
1014
1015 typedef struct MYDATA {
1016         LONG  lX;                   // X axis goes here
1017         LONG  lY;                   // Y axis goes here
1018         LONG  lZ;                   // Z axis goes here
1019         BYTE  bButtonA;             // One button goes here
1020         BYTE  bButtonB;             // Another button goes here
1021         BYTE  bButtonC;             // Another button goes here
1022         BYTE  bButtonD;             // Another button goes here
1023 } MYDATA;
1024
1025 static DIOBJECTDATAFORMAT rgodf[] = {
1026   { &GUID_XAxis,    FIELD_OFFSET(MYDATA, lX),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1027   { &GUID_YAxis,    FIELD_OFFSET(MYDATA, lY),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1028   { &GUID_ZAxis,    FIELD_OFFSET(MYDATA, lZ),       0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1029   { 0,              FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1030   { 0,              FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1031   { 0,              FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1032   { 0,              FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1033 };
1034
1035 #define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0]))
1036
1037 static DIDATAFORMAT     df = {
1038         sizeof(DIDATAFORMAT),       // this structure
1039         sizeof(DIOBJECTDATAFORMAT), // size of object data format
1040         DIDF_RELAXIS,               // absolute axis coordinates
1041         sizeof(MYDATA),             // device data size
1042         NUM_OBJECTS,                // number of objects
1043         rgodf,                      // and here they are
1044 };
1045
1046 // forward-referenced functions
1047 void IN_StartupJoystick (void);
1048 void Joy_AdvancedUpdate_f (void);
1049 void IN_JoyMove (usercmd_t *cmd);
1050
1051
1052 /*
1053 ===========
1054 IN_ShowMouse
1055 ===========
1056 */
1057 void IN_ShowMouse (void)
1058 {
1059         if (!mouseshowtoggle)
1060         {
1061                 ShowCursor (true);
1062                 mouseshowtoggle = 1;
1063         }
1064 }
1065
1066
1067 /*
1068 ===========
1069 IN_HideMouse
1070 ===========
1071 */
1072 void IN_HideMouse (void)
1073 {
1074         if (mouseshowtoggle)
1075         {
1076                 ShowCursor (false);
1077                 mouseshowtoggle = 0;
1078         }
1079 }
1080
1081
1082 /*
1083 ===========
1084 IN_ActivateMouse
1085 ===========
1086 */
1087 void IN_ActivateMouse (void)
1088 {
1089
1090         mouseactivatetoggle = true;
1091
1092         if (mouseinitialized)
1093         {
1094                 if (dinput)
1095                 {
1096                         if (g_pMouse)
1097                         {
1098                                 if (!dinput_acquired)
1099                                 {
1100                                         IDirectInputDevice_Acquire(g_pMouse);
1101                                         dinput_acquired = true;
1102                                 }
1103                         }
1104                         else
1105                         {
1106                                 return;
1107                         }
1108                 }
1109                 else
1110                 {
1111                         RECT window_rect;
1112                         window_rect.left = window_x;
1113                         window_rect.top = window_y;
1114                         window_rect.right = window_x + window_width;
1115                         window_rect.bottom = window_y + window_height;
1116
1117                         if (mouseparmsvalid)
1118                                 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
1119
1120                         SetCursorPos (window_center_x, window_center_y);
1121                         SetCapture (mainwindow);
1122                         ClipCursor (&window_rect);
1123                 }
1124
1125                 mouseactive = true;
1126         }
1127 }
1128
1129
1130 /*
1131 ===========
1132 IN_DeactivateMouse
1133 ===========
1134 */
1135 void IN_DeactivateMouse (void)
1136 {
1137
1138         mouseactivatetoggle = false;
1139
1140         if (mouseinitialized)
1141         {
1142                 if (dinput)
1143                 {
1144                         if (g_pMouse)
1145                         {
1146                                 if (dinput_acquired)
1147                                 {
1148                                         IDirectInputDevice_Unacquire(g_pMouse);
1149                                         dinput_acquired = false;
1150                                 }
1151                         }
1152                 }
1153                 else
1154                 {
1155                         if (restore_spi)
1156                                 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1157
1158                         ClipCursor (NULL);
1159                         ReleaseCapture ();
1160                 }
1161
1162                 mouseactive = false;
1163         }
1164 }
1165
1166
1167 /*
1168 ===========
1169 IN_InitDInput
1170 ===========
1171 */
1172 qboolean IN_InitDInput (void)
1173 {
1174     HRESULT             hr;
1175         DIPROPDWORD     dipdw = {
1176                 {
1177                         sizeof(DIPROPDWORD),        // diph.dwSize
1178                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
1179                         0,                          // diph.dwObj
1180                         DIPH_DEVICE,                // diph.dwHow
1181                 },
1182                 DINPUT_BUFFERSIZE,              // dwData
1183         };
1184
1185         if (!hInstDI)
1186         {
1187                 hInstDI = LoadLibrary("dinput.dll");
1188                 
1189                 if (hInstDI == NULL)
1190                 {
1191                         Con_SafePrintf ("Couldn't load dinput.dll\n");
1192                         return false;
1193                 }
1194         }
1195
1196         if (!pDirectInputCreate)
1197         {
1198                 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
1199
1200                 if (!pDirectInputCreate)
1201                 {
1202                         Con_SafePrintf ("Couldn't get DI proc addr\n");
1203                         return false;
1204                 }
1205         }
1206
1207 // register with DirectInput and get an IDirectInput to play with.
1208         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1209
1210         if (FAILED(hr))
1211         {
1212                 return false;
1213         }
1214
1215 // obtain an interface to the system mouse device.
1216         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1217
1218         if (FAILED(hr))
1219         {
1220                 Con_SafePrintf ("Couldn't open DI mouse device\n");
1221                 return false;
1222         }
1223
1224 // set the data format to "mouse format".
1225         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df);
1226
1227         if (FAILED(hr))
1228         {
1229                 Con_SafePrintf ("Couldn't set DI mouse format\n");
1230                 return false;
1231         }
1232
1233 // set the cooperativity level.
1234         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1235                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1236
1237         if (FAILED(hr))
1238         {
1239                 Con_SafePrintf ("Couldn't set DI coop level\n");
1240                 return false;
1241         }
1242
1243
1244 // set the buffer size to DINPUT_BUFFERSIZE elements.
1245 // the buffer size is a DWORD property associated with the device
1246         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1247
1248         if (FAILED(hr))
1249         {
1250                 Con_SafePrintf ("Couldn't set DI buffersize\n");
1251                 return false;
1252         }
1253
1254         return true;
1255 }
1256
1257
1258 /*
1259 ===========
1260 IN_StartupMouse
1261 ===========
1262 */
1263 void IN_StartupMouse (void)
1264 {
1265         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe")) 
1266                 return; 
1267
1268         mouseinitialized = true;
1269
1270         if (COM_CheckParm ("-dinput"))
1271         {
1272                 dinput = IN_InitDInput ();
1273
1274                 if (dinput)
1275                 {
1276                         Con_SafePrintf ("DirectInput initialized\n");
1277                 }
1278                 else
1279                 {
1280                         Con_SafePrintf ("DirectInput not initialized\n");
1281                 }
1282         }
1283
1284         if (!dinput)
1285         {
1286                 mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0);
1287
1288                 if (mouseparmsvalid)
1289                 {
1290                         if ( COM_CheckParm ("-noforcemspd") ) 
1291                                 newmouseparms[2] = originalmouseparms[2];
1292
1293                         if ( COM_CheckParm ("-noforcemaccel") ) 
1294                         {
1295                                 newmouseparms[0] = originalmouseparms[0];
1296                                 newmouseparms[1] = originalmouseparms[1];
1297                         }
1298
1299                         if ( COM_CheckParm ("-noforcemparms") ) 
1300                         {
1301                                 newmouseparms[0] = originalmouseparms[0];
1302                                 newmouseparms[1] = originalmouseparms[1];
1303                                 newmouseparms[2] = originalmouseparms[2];
1304                         }
1305                 }
1306         }
1307
1308         mouse_buttons = 3;
1309
1310 // if a fullscreen video mode was set before the mouse was initialized,
1311 // set the mouse state appropriately
1312         if (mouseactivatetoggle)
1313                 IN_ActivateMouse ();
1314 }
1315
1316
1317 /*
1318 ===========
1319 IN_Init
1320 ===========
1321 */
1322 void IN_Init (void)
1323 {
1324         // joystick variables
1325         Cvar_RegisterVariable (&in_joystick);
1326         Cvar_RegisterVariable (&joy_name);
1327         Cvar_RegisterVariable (&joy_advanced);
1328         Cvar_RegisterVariable (&joy_advaxisx);
1329         Cvar_RegisterVariable (&joy_advaxisy);
1330         Cvar_RegisterVariable (&joy_advaxisz);
1331         Cvar_RegisterVariable (&joy_advaxisr);
1332         Cvar_RegisterVariable (&joy_advaxisu);
1333         Cvar_RegisterVariable (&joy_advaxisv);
1334         Cvar_RegisterVariable (&joy_forwardthreshold);
1335         Cvar_RegisterVariable (&joy_sidethreshold);
1336         Cvar_RegisterVariable (&joy_pitchthreshold);
1337         Cvar_RegisterVariable (&joy_yawthreshold);
1338         Cvar_RegisterVariable (&joy_forwardsensitivity);
1339         Cvar_RegisterVariable (&joy_sidesensitivity);
1340         Cvar_RegisterVariable (&joy_pitchsensitivity);
1341         Cvar_RegisterVariable (&joy_yawsensitivity);
1342         Cvar_RegisterVariable (&joy_wwhack1);
1343         Cvar_RegisterVariable (&joy_wwhack2);
1344
1345         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f);
1346
1347         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
1348
1349         IN_StartupMouse ();
1350         IN_StartupJoystick ();
1351 }
1352
1353 /*
1354 ===========
1355 IN_Shutdown
1356 ===========
1357 */
1358 void IN_Shutdown (void)
1359 {
1360         IN_DeactivateMouse ();
1361         IN_ShowMouse ();
1362
1363     if (g_pMouse)
1364         {
1365                 IDirectInputDevice_Release(g_pMouse);
1366                 g_pMouse = NULL;
1367         }
1368
1369     if (g_pdi)
1370         {
1371                 IDirectInput_Release(g_pdi);
1372                 g_pdi = NULL;
1373         }
1374 }
1375
1376
1377 /*
1378 ===========
1379 IN_MouseEvent
1380 ===========
1381 */
1382 void IN_MouseEvent (int mstate)
1383 {
1384         int     i;
1385
1386         if (mouseactive && !dinput)
1387         {
1388         // perform button actions
1389                 for (i=0 ; i<mouse_buttons ; i++)
1390                 {
1391                         if ( (mstate & (1<<i)) &&
1392                                 !(mouse_oldbuttonstate & (1<<i)) )
1393                         {
1394                                 Key_Event (K_MOUSE1 + i, true);
1395                         }
1396
1397                         if ( !(mstate & (1<<i)) &&
1398                                 (mouse_oldbuttonstate & (1<<i)) )
1399                         {
1400                                 Key_Event (K_MOUSE1 + i, false);
1401                         }
1402                 }       
1403                         
1404                 mouse_oldbuttonstate = mstate;
1405         }
1406 }
1407
1408
1409 /*
1410 ===========
1411 IN_MouseMove
1412 ===========
1413 */
1414 void IN_MouseMove (usercmd_t *cmd)
1415 {
1416         int                                     i, mx, my;
1417         DIDEVICEOBJECTDATA      od;
1418         DWORD                           dwElements;
1419         HRESULT                         hr;
1420
1421         if (!mouseactive)
1422         {
1423                 GetCursorPos (&current_pos);
1424                 ui_mouseupdate(current_pos.x - window_x, current_pos.y - window_y);
1425                 return;
1426         }
1427
1428         if (dinput)
1429         {
1430                 mx = 0;
1431                 my = 0;
1432
1433                 for (;;)
1434                 {
1435                         dwElements = 1;
1436
1437                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1438                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1439
1440                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1441                         {
1442                                 dinput_acquired = true;
1443                                 IDirectInputDevice_Acquire(g_pMouse);
1444                                 break;
1445                         }
1446
1447                         /* Unable to read data or no data available */
1448                         if (FAILED(hr) || dwElements == 0)
1449                                 break;
1450
1451                         /* Look at the element to see what happened */
1452
1453                         switch (od.dwOfs)
1454                         {
1455                                 case DIMOFS_X:
1456                                         mx += od.dwData;
1457                                         break;
1458
1459                                 case DIMOFS_Y:
1460                                         my += od.dwData;
1461                                         break;
1462
1463                                 case DIMOFS_BUTTON0:
1464                                         if (od.dwData & 0x80)
1465                                                 mstate_di |= 1;
1466                                         else
1467                                                 mstate_di &= ~1;
1468                                         break;
1469
1470                                 case DIMOFS_BUTTON1:
1471                                         if (od.dwData & 0x80)
1472                                                 mstate_di |= (1<<1);
1473                                         else
1474                                                 mstate_di &= ~(1<<1);
1475                                         break;
1476
1477                                 case DIMOFS_BUTTON2:
1478                                         if (od.dwData & 0x80)
1479                                                 mstate_di |= (1<<2);
1480                                         else
1481                                                 mstate_di &= ~(1<<2);
1482                                         break;
1483                         }
1484                 }
1485
1486         // perform button actions
1487                 for (i=0 ; i<mouse_buttons ; i++)
1488                 {
1489                         if ( (mstate_di & (1<<i)) &&
1490                                 !(mouse_oldbuttonstate & (1<<i)) )
1491                         {
1492                                 Key_Event (K_MOUSE1 + i, true);
1493                         }
1494
1495                         if ( !(mstate_di & (1<<i)) &&
1496                                 (mouse_oldbuttonstate & (1<<i)) )
1497                         {
1498                                 Key_Event (K_MOUSE1 + i, false);
1499                         }
1500                 }
1501
1502                 mouse_oldbuttonstate = mstate_di;
1503         }
1504         else
1505         {
1506                 GetCursorPos (&current_pos);
1507                 mx = current_pos.x - window_center_x + mx_accum;
1508                 my = current_pos.y - window_center_y + my_accum;
1509                 mx_accum = 0;
1510                 my_accum = 0;
1511         }
1512
1513         IN_Mouse(cmd, mx, my);
1514
1515         // if the mouse has moved, force it to the center, so there's room to move
1516         if (!dinput && (mx || my))
1517                 SetCursorPos (window_center_x, window_center_y);
1518 }
1519
1520
1521 /*
1522 ===========
1523 IN_Move
1524 ===========
1525 */
1526 void IN_Move (usercmd_t *cmd)
1527 {
1528         if (vid_activewindow && !vid_hidden)
1529         {
1530                 IN_MouseMove (cmd);
1531                 IN_JoyMove (cmd);
1532         }
1533
1534         cl.viewangles[PITCH] = bound (in_pitch_min.value, cl.viewangles[PITCH], in_pitch_max.value);
1535 }
1536
1537
1538 /*
1539 ===========
1540 IN_Accumulate
1541 ===========
1542 */
1543 void IN_Accumulate (void)
1544 {
1545         if (mouseactive)
1546         {
1547                 if (!dinput)
1548                 {
1549                         GetCursorPos (&current_pos);
1550
1551                         mx_accum += current_pos.x - window_center_x;
1552                         my_accum += current_pos.y - window_center_y;
1553
1554                 // force the mouse to the center, so there's room to move
1555                         SetCursorPos (window_center_x, window_center_y);
1556                 }
1557         }
1558 }
1559
1560
1561 /*
1562 ===================
1563 IN_ClearStates
1564 ===================
1565 */
1566 void IN_ClearStates (void)
1567 {
1568         if (mouseactive)
1569         {
1570                 mx_accum = 0;
1571                 my_accum = 0;
1572                 mouse_oldbuttonstate = 0;
1573         }
1574 }
1575
1576
1577 /* 
1578 =============== 
1579 IN_StartupJoystick 
1580 =============== 
1581 */  
1582 void IN_StartupJoystick (void) 
1583
1584         int                     numdevs;
1585         JOYCAPS         jc;
1586         MMRESULT        mmr;
1587         mmr = 0;
1588  
1589         // assume no joystick
1590         joy_avail = false; 
1591
1592         // abort startup if user requests no joystick
1593         if (COM_CheckParm ("-nojoy") || COM_CheckParm("-safe")) 
1594                 return; 
1595  
1596         // verify joystick driver is present
1597         if ((numdevs = joyGetNumDevs ()) == 0)
1598         {
1599                 Con_Printf ("\njoystick not found -- driver not present\n\n");
1600                 return;
1601         }
1602
1603         // cycle through the joystick ids for the first valid one
1604         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1605         {
1606                 memset (&ji, 0, sizeof(ji));
1607                 ji.dwSize = sizeof(ji);
1608                 ji.dwFlags = JOY_RETURNCENTERED;
1609
1610                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1611                         break;
1612         } 
1613
1614         // abort startup if we didn't find a valid joystick
1615         if (mmr != JOYERR_NOERROR)
1616         {
1617                 Con_Printf ("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1618                 return;
1619         }
1620
1621         // get the capabilities of the selected joystick
1622         // abort startup if command fails
1623         memset (&jc, 0, sizeof(jc));
1624         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1625         {
1626                 Con_Printf ("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr); 
1627                 return;
1628         }
1629
1630         // save the joystick's number of buttons and POV status
1631         joy_numbuttons = jc.wNumButtons;
1632         joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
1633
1634         // old button and POV states default to no buttons pressed
1635         joy_oldbuttonstate = joy_oldpovstate = 0;
1636
1637         // mark the joystick as available and advanced initialization not completed
1638         // this is needed as cvars are not available during initialization
1639
1640         joy_avail = true; 
1641         joy_advancedinit = false;
1642
1643         Con_Printf ("\njoystick detected\n\n"); 
1644 }
1645
1646
1647 /*
1648 ===========
1649 RawValuePointer
1650 ===========
1651 */
1652 PDWORD RawValuePointer (int axis)
1653 {
1654         switch (axis)
1655         {
1656         case JOY_AXIS_X:
1657                 return &ji.dwXpos;
1658         case JOY_AXIS_Y:
1659                 return &ji.dwYpos;
1660         case JOY_AXIS_Z:
1661                 return &ji.dwZpos;
1662         case JOY_AXIS_R:
1663                 return &ji.dwRpos;
1664         case JOY_AXIS_U:
1665                 return &ji.dwUpos;
1666         case JOY_AXIS_V:
1667                 return &ji.dwVpos;
1668         }
1669         return NULL; // LordHavoc: hush compiler warning
1670 }
1671
1672
1673 /*
1674 ===========
1675 Joy_AdvancedUpdate_f
1676 ===========
1677 */
1678 void Joy_AdvancedUpdate_f (void)
1679 {
1680
1681         // called once by IN_ReadJoystick and by user whenever an update is needed
1682         // cvars are now available
1683         int     i;
1684         DWORD dwTemp;
1685
1686         // initialize all the maps
1687         for (i = 0; i < JOY_MAX_AXES; i++)
1688         {
1689                 dwAxisMap[i] = AxisNada;
1690                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1691                 pdwRawValue[i] = RawValuePointer(i);
1692         }
1693
1694         if( joy_advanced.integer == 0)
1695         {
1696                 // default joystick initialization
1697                 // 2 axes only with joystick control
1698                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1699                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1700                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1701                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1702         }
1703         else
1704         {
1705                 if (strcmp (joy_name.string, "joystick") != 0)
1706                 {
1707                         // notify user of advanced controller
1708                         Con_Printf ("\n%s configured\n\n", joy_name.string);
1709                 }
1710
1711                 // advanced initialization here
1712                 // data supplied by user via joy_axisn cvars
1713                 dwTemp = (DWORD) joy_advaxisx.value;
1714                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1715                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1716                 dwTemp = (DWORD) joy_advaxisy.value;
1717                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1718                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1719                 dwTemp = (DWORD) joy_advaxisz.value;
1720                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1721                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1722                 dwTemp = (DWORD) joy_advaxisr.value;
1723                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1724                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1725                 dwTemp = (DWORD) joy_advaxisu.value;
1726                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1727                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1728                 dwTemp = (DWORD) joy_advaxisv.value;
1729                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1730                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1731         }
1732
1733         // compute the axes to collect from DirectInput
1734         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1735         for (i = 0; i < JOY_MAX_AXES; i++)
1736         {
1737                 if (dwAxisMap[i] != AxisNada)
1738                 {
1739                         joy_flags |= dwAxisFlags[i];
1740                 }
1741         }
1742 }
1743
1744
1745 /*
1746 ===========
1747 IN_Commands
1748 ===========
1749 */
1750 void IN_Commands (void)
1751 {
1752         int             i, key_index;
1753         DWORD   buttonstate, povstate;
1754
1755         if (!joy_avail)
1756         {
1757                 return;
1758         }
1759
1760         
1761         // loop through the joystick buttons
1762         // key a joystick event or auxillary event for higher number buttons for each state change
1763         buttonstate = ji.dwButtons;
1764         for (i=0 ; i < (int) joy_numbuttons ; i++)
1765         {
1766                 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1767                 {
1768                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
1769                         Key_Event (key_index + i, true);
1770                 }
1771
1772                 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1773                 {
1774                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
1775                         Key_Event (key_index + i, false);
1776                 }
1777         }
1778         joy_oldbuttonstate = buttonstate;
1779
1780         if (joy_haspov)
1781         {
1782                 // convert POV information into 4 bits of state information
1783                 // this avoids any potential problems related to moving from one
1784                 // direction to another without going through the center position
1785                 povstate = 0;
1786                 if(ji.dwPOV != JOY_POVCENTERED)
1787                 {
1788                         if (ji.dwPOV == JOY_POVFORWARD)
1789                                 povstate |= 0x01;
1790                         if (ji.dwPOV == JOY_POVRIGHT)
1791                                 povstate |= 0x02;
1792                         if (ji.dwPOV == JOY_POVBACKWARD)
1793                                 povstate |= 0x04;
1794                         if (ji.dwPOV == JOY_POVLEFT)
1795                                 povstate |= 0x08;
1796                 }
1797                 // determine which bits have changed and key an auxillary event for each change
1798                 for (i=0 ; i < 4 ; i++)
1799                 {
1800                         if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1801                         {
1802                                 Key_Event (K_AUX29 + i, true);
1803                         }
1804
1805                         if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1806                         {
1807                                 Key_Event (K_AUX29 + i, false);
1808                         }
1809                 }
1810                 joy_oldpovstate = povstate;
1811         }
1812 }
1813
1814
1815 /* 
1816 =============== 
1817 IN_ReadJoystick
1818 =============== 
1819 */  
1820 qboolean IN_ReadJoystick (void)
1821 {
1822
1823         memset (&ji, 0, sizeof(ji));
1824         ji.dwSize = sizeof(ji);
1825         ji.dwFlags = joy_flags;
1826
1827         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1828         {
1829                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1830                 // rather than having 32768 be the zero point, they have the zero point at 32668
1831                 // go figure -- anyway, now we get the full resolution out of the device
1832                 if (joy_wwhack1.integer != 0.0)
1833                 {
1834                         ji.dwUpos += 100;
1835                 }
1836                 return true;
1837         }
1838         else
1839         {
1840                 // read error occurred
1841                 // turning off the joystick seems too harsh for 1 read error,
1842                 // but what should be done?
1843                 return false;
1844         }
1845 }
1846
1847
1848 /*
1849 ===========
1850 IN_JoyMove
1851 ===========
1852 */
1853 void IN_JoyMove (usercmd_t *cmd)
1854 {
1855         float   speed, aspeed;
1856         float   fAxisValue, fTemp;
1857         int             i, mouselook = (in_mlook.state & 1) || freelook.integer;
1858
1859         // complete initialization if first time in
1860         // this is needed as cvars are not available at initialization time
1861         if( joy_advancedinit != true )
1862         {
1863                 Joy_AdvancedUpdate_f();
1864                 joy_advancedinit = true;
1865         }
1866
1867         // verify joystick is available and that the user wants to use it
1868         if (!joy_avail || !in_joystick.integer)
1869         {
1870                 return; 
1871         }
1872
1873         // collect the joystick data, if possible
1874         if (IN_ReadJoystick () != true)
1875         {
1876                 return;
1877         }
1878
1879         if (in_speed.state & 1)
1880                 speed = cl_movespeedkey.value;
1881         else
1882                 speed = 1;
1883         // LordHavoc: viewzoom affects sensitivity for sniping
1884         aspeed = speed * host_realframetime * cl.viewzoom;
1885
1886         // loop through the axes
1887         for (i = 0; i < JOY_MAX_AXES; i++)
1888         {
1889                 // get the floating point zero-centered, potentially-inverted data for the current axis
1890                 fAxisValue = (float) *pdwRawValue[i];
1891                 // move centerpoint to zero
1892                 fAxisValue -= 32768.0;
1893
1894                 if (joy_wwhack2.integer != 0.0)
1895                 {
1896                         if (dwAxisMap[i] == AxisTurn)
1897                         {
1898                                 // this is a special formula for the Logitech WingMan Warrior
1899                                 // y=ax^b; where a = 300 and b = 1.3
1900                                 // also x values are in increments of 800 (so this is factored out)
1901                                 // then bounds check result to level out excessively high spin rates
1902                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1903                                 if (fTemp > 14000.0)
1904                                         fTemp = 14000.0;
1905                                 // restore direction information
1906                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1907                         }
1908                 }
1909
1910                 // convert range from -32768..32767 to -1..1 
1911                 fAxisValue /= 32768.0;
1912
1913                 switch (dwAxisMap[i])
1914                 {
1915                 case AxisForward:
1916                         if ((joy_advanced.integer == 0) && mouselook)
1917                         {
1918                                 // user wants forward control to become look control
1919                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1920                                 {               
1921                                         // if mouse invert is on, invert the joystick pitch value
1922                                         // only absolute control support here (joy_advanced is false)
1923                                         if (m_pitch.value < 0.0)
1924                                         {
1925                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1926                                         }
1927                                         else
1928                                         {
1929                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1930                                         }
1931                                         V_StopPitchDrift();
1932                                 }
1933                                 else
1934                                 {
1935                                         // no pitch movement
1936                                         // disable pitch return-to-center unless requested by user
1937                                         // *** this code can be removed when the lookspring bug is fixed
1938                                         // *** the bug always has the lookspring feature on
1939                                         if(lookspring.value == 0.0)
1940                                                 V_StopPitchDrift();
1941                                 }
1942                         }
1943                         else
1944                         {
1945                                 // user wants forward control to be forward control
1946                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1947                                 {
1948                                         cmd->forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1949                                 }
1950                         }
1951                         break;
1952
1953                 case AxisSide:
1954                         if (fabs(fAxisValue) > joy_sidethreshold.value)
1955                         {
1956                                 cmd->sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1957                         }
1958                         break;
1959
1960                 case AxisTurn:
1961                         if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
1962                         {
1963                                 // user wants turn control to become side control
1964                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
1965                                 {
1966                                         cmd->sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1967                                 }
1968                         }
1969                         else
1970                         {
1971                                 // user wants turn control to be turn control
1972                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
1973                                 {
1974                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1975                                         {
1976                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1977                                         }
1978                                         else
1979                                         {
1980                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
1981                                         }
1982
1983                                 }
1984                         }
1985                         break;
1986
1987                 case AxisLook:
1988                         if (mouselook)
1989                         {
1990                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1991                                 {
1992                                         // pitch movement detected and pitch movement desired by user
1993                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1994                                         {
1995                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1996                                         }
1997                                         else
1998                                         {
1999                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
2000                                         }
2001                                         V_StopPitchDrift();
2002                                 }
2003                                 else
2004                                 {
2005                                         // no pitch movement
2006                                         // disable pitch return-to-center unless requested by user
2007                                         // *** this code can be removed when the lookspring bug is fixed
2008                                         // *** the bug always has the lookspring feature on
2009                                         if(lookspring.integer == 0)
2010                                                 V_StopPitchDrift();
2011                                 }
2012                         }
2013                         break;
2014
2015                 default:
2016                         break;
2017                 }
2018         }
2019 }
2020