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