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