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