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