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