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