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