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