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