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