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