remove an unused extension function list
[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
650 int VID_InitMode (int fullscreen, int width, int height, int bpp)
651 {
652         int i;
653         HDC hdc;
654         RECT rect;
655         MSG msg;
656         PIXELFORMATDESCRIPTOR pfd =
657         {
658                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
659                 1,                              // version number
660                 PFD_DRAW_TO_WINDOW              // support window
661                 |  PFD_SUPPORT_OPENGL   // support OpenGL
662                 |  PFD_DOUBLEBUFFER ,   // double buffered
663                 PFD_TYPE_RGBA,                  // RGBA type
664                 24,                             // 24-bit color depth
665                 0, 0, 0, 0, 0, 0,               // color bits ignored
666                 0,                              // no alpha buffer
667                 0,                              // shift bit ignored
668                 0,                              // no accumulation buffer
669                 0, 0, 0, 0,                     // accum bits ignored
670                 32,                             // 32-bit z-buffer
671                 0,                              // no stencil buffer
672                 0,                              // no auxiliary buffer
673                 PFD_MAIN_PLANE,                 // main layer
674                 0,                              // reserved
675                 0, 0, 0                         // layer masks ignored
676         };
677         int pixelformat;
678         DWORD WindowStyle, ExWindowStyle;
679         HGLRC baseRC;
680         int CenterX, CenterY;
681
682         if (vid_initialized)
683                 Sys_Error("VID_InitMode called when video is already initialised\n");
684
685         if (!GL_OpenLibrary("opengl32.dll"))
686         {
687                 Con_Printf("Unable to load GL driver\n");
688                 return false;
689         }
690
691         memset(&gdevmode, 0, sizeof(gdevmode));
692
693         VID_GetSystemGamma();
694
695         vid_isfullscreen = false;
696         if (fullscreen)
697         {
698                 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
699                 gdevmode.dmBitsPerPel = bpp;
700                 gdevmode.dmPelsWidth = width;
701                 gdevmode.dmPelsHeight = height;
702                 gdevmode.dmSize = sizeof (gdevmode);
703                 if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
704                 {
705                         VID_Shutdown();
706                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
707                         return false;
708                 }
709
710                 vid_isfullscreen = true;
711                 WindowStyle = WS_POPUP;
712                 ExWindowStyle = 0;
713         }
714         else
715         {
716                 hdc = GetDC (NULL);
717                 i = GetDeviceCaps(hdc, RASTERCAPS);
718                 ReleaseDC (NULL, hdc);
719                 if (i & RC_PALETTE)
720                 {
721                         VID_Shutdown();
722                         Con_Printf ("Can't run in non-RGB mode\n");
723                         return false;
724                 }
725
726                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
727                 ExWindowStyle = 0;
728         }
729
730         rect.top = 0;
731         rect.left = 0;
732         rect.right = width;
733         rect.bottom = height;
734         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
735
736         if (fullscreen)
737         {
738                 CenterX = 0;
739                 CenterY = 0;
740         }
741         else
742         {
743                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
744                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
745         }
746         CenterX = max(0, CenterX);
747         CenterY = max(0, CenterY);
748
749         // x and y may be changed by WM_MOVE messages
750         window_x = CenterX;
751         window_y = CenterY;
752         window_width = width;
753         window_height = height;
754         rect.left += CenterX;
755         rect.right += CenterX;
756         rect.top += CenterY;
757         rect.bottom += CenterY;
758
759         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
760         if (!mainwindow)
761         {
762                 VID_Shutdown();
763                 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);
764                 return false;
765         }
766
767         /*
768         if (!fullscreen)
769                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
770         */
771
772         ShowWindow (mainwindow, SW_SHOWDEFAULT);
773         UpdateWindow (mainwindow);
774
775         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
776         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
777
778         VID_UpdateWindowStatus ();
779
780         // now we try to make sure we get the focus on the mode switch, because
781         // sometimes in some systems we don't.  We grab the foreground, then
782         // finish setting up, pump all our messages, and sleep for a little while
783         // to let messages finish bouncing around the system, then we put
784         // ourselves at the top of the z order, then grab the foreground again,
785         // Who knows if it helps, but it probably doesn't hurt
786         SetForegroundWindow (mainwindow);
787
788         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
789         {
790                 TranslateMessage (&msg);
791                 DispatchMessage (&msg);
792         }
793
794         Sleep (100);
795
796         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
797
798         SetForegroundWindow (mainwindow);
799
800         // fix the leftover Alt from any Alt-Tab or the like that switched us away
801         ClearAllStates ();
802         
803         hdc = GetDC(mainwindow);
804
805         if ((pixelformat = ChoosePixelFormat(hdc, &pfd)) == 0)
806         {
807                 VID_Shutdown();
808                 Con_Printf("ChoosePixelFormat(%d, %p) failed\n", hdc, &pfd);
809                 return false;
810         }
811
812         if (SetPixelFormat(hdc, pixelformat, &pfd) == false)
813         {
814                 VID_Shutdown();
815                 Con_Printf("SetPixelFormat(%d, %d, %p) failed\n", hdc, pixelformat, &pfd);
816                 return false;
817         }
818
819         if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
820         {
821                 VID_Shutdown();
822                 Con_Printf("wgl functions not found\n");
823                 return false;
824         }
825
826         baseRC = qwglCreateContext(hdc);
827         if (!baseRC)
828         {
829                 VID_Shutdown();
830                 Con_Printf("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
831                 return false;
832         }
833         if (!qwglMakeCurrent(hdc, baseRC))
834         {
835                 VID_Shutdown();
836                 Con_Printf("wglMakeCurrent(%d, %d) failed\n", hdc, baseRC);
837                 return false;
838         }
839
840         qglGetString = GL_GetProcAddress("glGetString");
841         qwglGetExtensionsStringARB = GL_GetProcAddress("wglGetExtensionsStringARB");
842         if (qglGetString == NULL)
843         {
844                 VID_Shutdown();
845                 Con_Printf("glGetString not found\n");
846                 return false;
847         }
848         gl_renderer = qglGetString(GL_RENDERER);
849         gl_vendor = qglGetString(GL_VENDOR);
850         gl_version = qglGetString(GL_VERSION);
851         gl_extensions = qglGetString(GL_EXTENSIONS);
852         gl_platform = "WGL";
853         gl_platformextensions = "";
854
855         if (qwglGetExtensionsStringARB)
856                 gl_platformextensions = qwglGetExtensionsStringARB(hdc);
857
858         gl_videosyncavailable = GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, NULL, false);
859         ReleaseDC(mainwindow, hdc);
860
861         GL_Init ();
862
863         // LordHavoc: special differences for ATI (broken 8bit color when also using 32bit? weird!)
864         if (strncasecmp(gl_vendor,"ATI",3)==0)
865         {
866                 if (strncasecmp(gl_renderer,"Rage Pro",8)==0)
867                         isRagePro = true;
868         }
869         if (strncasecmp(gl_renderer,"Matrox G200 Direct3D",20)==0) // a D3D driver for GL? sigh...
870                 isG200 = true;
871
872         //vid_menudrawfn = VID_MenuDraw;
873         //vid_menukeyfn = VID_MenuKey;
874         vid_hidden = false;
875         vid_initialized = true;
876         return true;
877 }
878
879 void VID_Shutdown (void)
880 {
881         HGLRC hRC = 0;
882         HDC hDC = 0;
883
884         if (vid_initialized)
885         {
886                 vid_initialized = false;
887                 if (qwglGetCurrentContext)
888                         hRC = qwglGetCurrentContext();
889                 if (qwglGetCurrentDC)
890                         hDC = qwglGetCurrentDC();
891
892                 if (qwglMakeCurrent)
893                         qwglMakeCurrent(NULL, NULL);
894
895                 if (hRC && qwglDeleteContext)
896                         qwglDeleteContext(hRC);
897
898                 // close the library before we get rid of the window
899                 GL_CloseLibrary();
900
901                 if (hDC && mainwindow)
902                         ReleaseDC(mainwindow, hDC);
903
904                 if (vid_isfullscreen)
905                         ChangeDisplaySettings (NULL, 0);
906
907                 AppActivate(false, false);
908
909                 VID_RestoreSystemGamma();
910         }
911 }
912
913
914 // input code
915
916 #include <dinput.h>
917
918 #define DINPUT_BUFFERSIZE           16
919 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
920
921 HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion,
922         LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
923
924 // mouse variables
925 int                     mouse_buttons;
926 int                     mouse_oldbuttonstate;
927 POINT           current_pos;
928 int                     mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum;
929
930 static qboolean restore_spi;
931 static int              originalmouseparms[3], newmouseparms[3] = {0, 0, 1};
932
933 unsigned int uiWheelMessage;
934 qboolean        mouseactive;
935 //qboolean              mouseinitialized;
936 static qboolean mouseparmsvalid, mouseactivatetoggle;
937 static qboolean mouseshowtoggle = 1;
938 static qboolean dinput_acquired;
939
940 static unsigned int             mstate_di;
941
942 // joystick defines and variables
943 // where should defines be moved?
944 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
945 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
946 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
947 #define JOY_AXIS_X                      0
948 #define JOY_AXIS_Y                      1
949 #define JOY_AXIS_Z                      2
950 #define JOY_AXIS_R                      3
951 #define JOY_AXIS_U                      4
952 #define JOY_AXIS_V                      5
953
954 enum _ControlList
955 {
956         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
957 };
958
959 DWORD   dwAxisFlags[JOY_MAX_AXES] =
960 {
961         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
962 };
963
964 DWORD   dwAxisMap[JOY_MAX_AXES];
965 DWORD   dwControlMap[JOY_MAX_AXES];
966 PDWORD  pdwRawValue[JOY_MAX_AXES];
967
968 // none of these cvars are saved over a session
969 // this means that advanced controller configuration needs to be executed
970 // each time.  this avoids any problems with getting back to a default usage
971 // or when changing from one controller to another.  this way at least something
972 // works.
973 cvar_t  in_joystick = {CVAR_SAVE, "joystick","0"};
974 cvar_t  joy_name = {0, "joyname", "joystick"};
975 cvar_t  joy_advanced = {0, "joyadvanced", "0"};
976 cvar_t  joy_advaxisx = {0, "joyadvaxisx", "0"};
977 cvar_t  joy_advaxisy = {0, "joyadvaxisy", "0"};
978 cvar_t  joy_advaxisz = {0, "joyadvaxisz", "0"};
979 cvar_t  joy_advaxisr = {0, "joyadvaxisr", "0"};
980 cvar_t  joy_advaxisu = {0, "joyadvaxisu", "0"};
981 cvar_t  joy_advaxisv = {0, "joyadvaxisv", "0"};
982 cvar_t  joy_forwardthreshold = {0, "joyforwardthreshold", "0.15"};
983 cvar_t  joy_sidethreshold = {0, "joysidethreshold", "0.15"};
984 cvar_t  joy_pitchthreshold = {0, "joypitchthreshold", "0.15"};
985 cvar_t  joy_yawthreshold = {0, "joyyawthreshold", "0.15"};
986 cvar_t  joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0"};
987 cvar_t  joy_sidesensitivity = {0, "joysidesensitivity", "-1.0"};
988 cvar_t  joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0"};
989 cvar_t  joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0"};
990 cvar_t  joy_wwhack1 = {0, "joywwhack1", "0.0"};
991 cvar_t  joy_wwhack2 = {0, "joywwhack2", "0.0"};
992
993 qboolean        joy_avail, joy_advancedinit, joy_haspov;
994 DWORD           joy_oldbuttonstate, joy_oldpovstate;
995
996 int                     joy_id;
997 DWORD           joy_flags;
998 DWORD           joy_numbuttons;
999
1000 static LPDIRECTINPUT            g_pdi;
1001 static LPDIRECTINPUTDEVICE      g_pMouse;
1002
1003 static JOYINFOEX        ji;
1004
1005 static HINSTANCE hInstDI;
1006
1007 //static qboolean       dinput;
1008
1009 typedef struct MYDATA {
1010         LONG  lX;                   // X axis goes here
1011         LONG  lY;                   // Y axis goes here
1012         LONG  lZ;                   // Z axis goes here
1013         BYTE  bButtonA;             // One button goes here
1014         BYTE  bButtonB;             // Another button goes here
1015         BYTE  bButtonC;             // Another button goes here
1016         BYTE  bButtonD;             // Another button goes here
1017 } MYDATA;
1018
1019 static DIOBJECTDATAFORMAT rgodf[] = {
1020   { &GUID_XAxis,    FIELD_OFFSET(MYDATA, lX),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1021   { &GUID_YAxis,    FIELD_OFFSET(MYDATA, lY),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1022   { &GUID_ZAxis,    FIELD_OFFSET(MYDATA, lZ),       0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
1023   { 0,              FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1024   { 0,              FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1025   { 0,              FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1026   { 0,              FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
1027 };
1028
1029 #define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0]))
1030
1031 static DIDATAFORMAT     df = {
1032         sizeof(DIDATAFORMAT),       // this structure
1033         sizeof(DIOBJECTDATAFORMAT), // size of object data format
1034         DIDF_RELAXIS,               // absolute axis coordinates
1035         sizeof(MYDATA),             // device data size
1036         NUM_OBJECTS,                // number of objects
1037         rgodf,                      // and here they are
1038 };
1039
1040 // forward-referenced functions
1041 void IN_StartupJoystick (void);
1042 void Joy_AdvancedUpdate_f (void);
1043 void IN_JoyMove (usercmd_t *cmd);
1044
1045
1046 /*
1047 ===========
1048 IN_ShowMouse
1049 ===========
1050 */
1051 void IN_ShowMouse (void)
1052 {
1053         if (!mouseshowtoggle)
1054         {
1055                 ShowCursor (true);
1056                 mouseshowtoggle = 1;
1057         }
1058 }
1059
1060
1061 /*
1062 ===========
1063 IN_HideMouse
1064 ===========
1065 */
1066 void IN_HideMouse (void)
1067 {
1068         if (mouseshowtoggle)
1069         {
1070                 ShowCursor (false);
1071                 mouseshowtoggle = 0;
1072         }
1073 }
1074
1075
1076 /*
1077 ===========
1078 IN_ActivateMouse
1079 ===========
1080 */
1081 void IN_ActivateMouse (void)
1082 {
1083
1084         mouseactivatetoggle = true;
1085
1086         if (mouseinitialized)
1087         {
1088                 if (dinput)
1089                 {
1090                         if (g_pMouse)
1091                         {
1092                                 if (!dinput_acquired)
1093                                 {
1094                                         IDirectInputDevice_Acquire(g_pMouse);
1095                                         dinput_acquired = true;
1096                                 }
1097                         }
1098                         else
1099                         {
1100                                 return;
1101                         }
1102                 }
1103                 else
1104                 {
1105                         RECT window_rect;
1106                         window_rect.left = window_x;
1107                         window_rect.top = window_y;
1108                         window_rect.right = window_x + window_width;
1109                         window_rect.bottom = window_y + window_height;
1110
1111                         if (mouseparmsvalid)
1112                                 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
1113
1114                         SetCursorPos (window_center_x, window_center_y);
1115                         SetCapture (mainwindow);
1116                         ClipCursor (&window_rect);
1117                 }
1118
1119                 mouseactive = true;
1120         }
1121 }
1122
1123
1124 /*
1125 ===========
1126 IN_DeactivateMouse
1127 ===========
1128 */
1129 void IN_DeactivateMouse (void)
1130 {
1131
1132         mouseactivatetoggle = false;
1133
1134         if (mouseinitialized)
1135         {
1136                 if (dinput)
1137                 {
1138                         if (g_pMouse)
1139                         {
1140                                 if (dinput_acquired)
1141                                 {
1142                                         IDirectInputDevice_Unacquire(g_pMouse);
1143                                         dinput_acquired = false;
1144                                 }
1145                         }
1146                 }
1147                 else
1148                 {
1149                         if (restore_spi)
1150                                 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1151
1152                         ClipCursor (NULL);
1153                         ReleaseCapture ();
1154                 }
1155
1156                 mouseactive = false;
1157         }
1158 }
1159
1160
1161 /*
1162 ===========
1163 IN_InitDInput
1164 ===========
1165 */
1166 qboolean IN_InitDInput (void)
1167 {
1168     HRESULT             hr;
1169         DIPROPDWORD     dipdw = {
1170                 {
1171                         sizeof(DIPROPDWORD),        // diph.dwSize
1172                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
1173                         0,                          // diph.dwObj
1174                         DIPH_DEVICE,                // diph.dwHow
1175                 },
1176                 DINPUT_BUFFERSIZE,              // dwData
1177         };
1178
1179         if (!hInstDI)
1180         {
1181                 hInstDI = LoadLibrary("dinput.dll");
1182                 
1183                 if (hInstDI == NULL)
1184                 {
1185                         Con_SafePrintf ("Couldn't load dinput.dll\n");
1186                         return false;
1187                 }
1188         }
1189
1190         if (!pDirectInputCreate)
1191         {
1192                 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
1193
1194                 if (!pDirectInputCreate)
1195                 {
1196                         Con_SafePrintf ("Couldn't get DI proc addr\n");
1197                         return false;
1198                 }
1199         }
1200
1201 // register with DirectInput and get an IDirectInput to play with.
1202         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1203
1204         if (FAILED(hr))
1205         {
1206                 return false;
1207         }
1208
1209 // obtain an interface to the system mouse device.
1210         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1211
1212         if (FAILED(hr))
1213         {
1214                 Con_SafePrintf ("Couldn't open DI mouse device\n");
1215                 return false;
1216         }
1217
1218 // set the data format to "mouse format".
1219         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df);
1220
1221         if (FAILED(hr))
1222         {
1223                 Con_SafePrintf ("Couldn't set DI mouse format\n");
1224                 return false;
1225         }
1226
1227 // set the cooperativity level.
1228         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1229                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1230
1231         if (FAILED(hr))
1232         {
1233                 Con_SafePrintf ("Couldn't set DI coop level\n");
1234                 return false;
1235         }
1236
1237
1238 // set the buffer size to DINPUT_BUFFERSIZE elements.
1239 // the buffer size is a DWORD property associated with the device
1240         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1241
1242         if (FAILED(hr))
1243         {
1244                 Con_SafePrintf ("Couldn't set DI buffersize\n");
1245                 return false;
1246         }
1247
1248         return true;
1249 }
1250
1251
1252 /*
1253 ===========
1254 IN_StartupMouse
1255 ===========
1256 */
1257 void IN_StartupMouse (void)
1258 {
1259         if (COM_CheckParm ("-nomouse") || COM_CheckParm("-safe")) 
1260                 return; 
1261
1262         mouseinitialized = true;
1263
1264         if (COM_CheckParm ("-dinput"))
1265         {
1266                 dinput = IN_InitDInput ();
1267
1268                 if (dinput)
1269                 {
1270                         Con_SafePrintf ("DirectInput initialized\n");
1271                 }
1272                 else
1273                 {
1274                         Con_SafePrintf ("DirectInput not initialized\n");
1275                 }
1276         }
1277
1278         if (!dinput)
1279         {
1280                 mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0);
1281
1282                 if (mouseparmsvalid)
1283                 {
1284                         if ( COM_CheckParm ("-noforcemspd") ) 
1285                                 newmouseparms[2] = originalmouseparms[2];
1286
1287                         if ( COM_CheckParm ("-noforcemaccel") ) 
1288                         {
1289                                 newmouseparms[0] = originalmouseparms[0];
1290                                 newmouseparms[1] = originalmouseparms[1];
1291                         }
1292
1293                         if ( COM_CheckParm ("-noforcemparms") ) 
1294                         {
1295                                 newmouseparms[0] = originalmouseparms[0];
1296                                 newmouseparms[1] = originalmouseparms[1];
1297                                 newmouseparms[2] = originalmouseparms[2];
1298                         }
1299                 }
1300         }
1301
1302         mouse_buttons = 3;
1303
1304 // if a fullscreen video mode was set before the mouse was initialized,
1305 // set the mouse state appropriately
1306         if (mouseactivatetoggle)
1307                 IN_ActivateMouse ();
1308 }
1309
1310
1311 /*
1312 ===========
1313 IN_Init
1314 ===========
1315 */
1316 void IN_Init (void)
1317 {
1318         // joystick variables
1319         Cvar_RegisterVariable (&in_joystick);
1320         Cvar_RegisterVariable (&joy_name);
1321         Cvar_RegisterVariable (&joy_advanced);
1322         Cvar_RegisterVariable (&joy_advaxisx);
1323         Cvar_RegisterVariable (&joy_advaxisy);
1324         Cvar_RegisterVariable (&joy_advaxisz);
1325         Cvar_RegisterVariable (&joy_advaxisr);
1326         Cvar_RegisterVariable (&joy_advaxisu);
1327         Cvar_RegisterVariable (&joy_advaxisv);
1328         Cvar_RegisterVariable (&joy_forwardthreshold);
1329         Cvar_RegisterVariable (&joy_sidethreshold);
1330         Cvar_RegisterVariable (&joy_pitchthreshold);
1331         Cvar_RegisterVariable (&joy_yawthreshold);
1332         Cvar_RegisterVariable (&joy_forwardsensitivity);
1333         Cvar_RegisterVariable (&joy_sidesensitivity);
1334         Cvar_RegisterVariable (&joy_pitchsensitivity);
1335         Cvar_RegisterVariable (&joy_yawsensitivity);
1336         Cvar_RegisterVariable (&joy_wwhack1);
1337         Cvar_RegisterVariable (&joy_wwhack2);
1338
1339         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f);
1340
1341         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
1342
1343         IN_StartupMouse ();
1344         IN_StartupJoystick ();
1345 }
1346
1347 /*
1348 ===========
1349 IN_Shutdown
1350 ===========
1351 */
1352 void IN_Shutdown (void)
1353 {
1354         IN_DeactivateMouse ();
1355         IN_ShowMouse ();
1356
1357     if (g_pMouse)
1358         {
1359                 IDirectInputDevice_Release(g_pMouse);
1360                 g_pMouse = NULL;
1361         }
1362
1363     if (g_pdi)
1364         {
1365                 IDirectInput_Release(g_pdi);
1366                 g_pdi = NULL;
1367         }
1368 }
1369
1370
1371 /*
1372 ===========
1373 IN_MouseEvent
1374 ===========
1375 */
1376 void IN_MouseEvent (int mstate)
1377 {
1378         int     i;
1379
1380         if (mouseactive && !dinput)
1381         {
1382         // perform button actions
1383                 for (i=0 ; i<mouse_buttons ; i++)
1384                 {
1385                         if ( (mstate & (1<<i)) &&
1386                                 !(mouse_oldbuttonstate & (1<<i)) )
1387                         {
1388                                 Key_Event (K_MOUSE1 + i, true);
1389                         }
1390
1391                         if ( !(mstate & (1<<i)) &&
1392                                 (mouse_oldbuttonstate & (1<<i)) )
1393                         {
1394                                 Key_Event (K_MOUSE1 + i, false);
1395                         }
1396                 }       
1397                         
1398                 mouse_oldbuttonstate = mstate;
1399         }
1400 }
1401
1402
1403 /*
1404 ===========
1405 IN_MouseMove
1406 ===========
1407 */
1408 void IN_MouseMove (usercmd_t *cmd)
1409 {
1410         int                                     i, mx, my;
1411         DIDEVICEOBJECTDATA      od;
1412         DWORD                           dwElements;
1413         HRESULT                         hr;
1414
1415         if (!mouseactive)
1416         {
1417                 GetCursorPos (&current_pos);
1418                 ui_mouseupdate(current_pos.x - window_x, current_pos.y - window_y);
1419                 return;
1420         }
1421
1422         if (dinput)
1423         {
1424                 mx = 0;
1425                 my = 0;
1426
1427                 for (;;)
1428                 {
1429                         dwElements = 1;
1430
1431                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1432                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1433
1434                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1435                         {
1436                                 dinput_acquired = true;
1437                                 IDirectInputDevice_Acquire(g_pMouse);
1438                                 break;
1439                         }
1440
1441                         /* Unable to read data or no data available */
1442                         if (FAILED(hr) || dwElements == 0)
1443                                 break;
1444
1445                         /* Look at the element to see what happened */
1446
1447                         switch (od.dwOfs)
1448                         {
1449                                 case DIMOFS_X:
1450                                         mx += od.dwData;
1451                                         break;
1452
1453                                 case DIMOFS_Y:
1454                                         my += od.dwData;
1455                                         break;
1456
1457                                 case DIMOFS_BUTTON0:
1458                                         if (od.dwData & 0x80)
1459                                                 mstate_di |= 1;
1460                                         else
1461                                                 mstate_di &= ~1;
1462                                         break;
1463
1464                                 case DIMOFS_BUTTON1:
1465                                         if (od.dwData & 0x80)
1466                                                 mstate_di |= (1<<1);
1467                                         else
1468                                                 mstate_di &= ~(1<<1);
1469                                         break;
1470
1471                                 case DIMOFS_BUTTON2:
1472                                         if (od.dwData & 0x80)
1473                                                 mstate_di |= (1<<2);
1474                                         else
1475                                                 mstate_di &= ~(1<<2);
1476                                         break;
1477                         }
1478                 }
1479
1480         // perform button actions
1481                 for (i=0 ; i<mouse_buttons ; i++)
1482                 {
1483                         if ( (mstate_di & (1<<i)) &&
1484                                 !(mouse_oldbuttonstate & (1<<i)) )
1485                         {
1486                                 Key_Event (K_MOUSE1 + i, true);
1487                         }
1488
1489                         if ( !(mstate_di & (1<<i)) &&
1490                                 (mouse_oldbuttonstate & (1<<i)) )
1491                         {
1492                                 Key_Event (K_MOUSE1 + i, false);
1493                         }
1494                 }
1495
1496                 mouse_oldbuttonstate = mstate_di;
1497         }
1498         else
1499         {
1500                 GetCursorPos (&current_pos);
1501                 mx = current_pos.x - window_center_x + mx_accum;
1502                 my = current_pos.y - window_center_y + my_accum;
1503                 mx_accum = 0;
1504                 my_accum = 0;
1505         }
1506
1507         IN_Mouse(cmd, mx, my);
1508
1509         // if the mouse has moved, force it to the center, so there's room to move
1510         if (!dinput && (mx || my))
1511                 SetCursorPos (window_center_x, window_center_y);
1512 }
1513
1514
1515 /*
1516 ===========
1517 IN_Move
1518 ===========
1519 */
1520 void IN_Move (usercmd_t *cmd)
1521 {
1522         if (vid_activewindow && !vid_hidden)
1523         {
1524                 IN_MouseMove (cmd);
1525                 IN_JoyMove (cmd);
1526         }
1527
1528         cl.viewangles[PITCH] = bound (in_pitch_min.value, cl.viewangles[PITCH], in_pitch_max.value);
1529 }
1530
1531
1532 /*
1533 ===========
1534 IN_Accumulate
1535 ===========
1536 */
1537 void IN_Accumulate (void)
1538 {
1539         if (mouseactive)
1540         {
1541                 if (!dinput)
1542                 {
1543                         GetCursorPos (&current_pos);
1544
1545                         mx_accum += current_pos.x - window_center_x;
1546                         my_accum += current_pos.y - window_center_y;
1547
1548                 // force the mouse to the center, so there's room to move
1549                         SetCursorPos (window_center_x, window_center_y);
1550                 }
1551         }
1552 }
1553
1554
1555 /*
1556 ===================
1557 IN_ClearStates
1558 ===================
1559 */
1560 void IN_ClearStates (void)
1561 {
1562         if (mouseactive)
1563         {
1564                 mx_accum = 0;
1565                 my_accum = 0;
1566                 mouse_oldbuttonstate = 0;
1567         }
1568 }
1569
1570
1571 /* 
1572 =============== 
1573 IN_StartupJoystick 
1574 =============== 
1575 */  
1576 void IN_StartupJoystick (void) 
1577
1578         int                     numdevs;
1579         JOYCAPS         jc;
1580         MMRESULT        mmr;
1581         mmr = 0;
1582  
1583         // assume no joystick
1584         joy_avail = false; 
1585
1586         // abort startup if user requests no joystick
1587         if (COM_CheckParm ("-nojoy") || COM_CheckParm("-safe")) 
1588                 return; 
1589  
1590         // verify joystick driver is present
1591         if ((numdevs = joyGetNumDevs ()) == 0)
1592         {
1593                 Con_Printf ("\njoystick not found -- driver not present\n\n");
1594                 return;
1595         }
1596
1597         // cycle through the joystick ids for the first valid one
1598         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1599         {
1600                 memset (&ji, 0, sizeof(ji));
1601                 ji.dwSize = sizeof(ji);
1602                 ji.dwFlags = JOY_RETURNCENTERED;
1603
1604                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1605                         break;
1606         } 
1607
1608         // abort startup if we didn't find a valid joystick
1609         if (mmr != JOYERR_NOERROR)
1610         {
1611                 Con_Printf ("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1612                 return;
1613         }
1614
1615         // get the capabilities of the selected joystick
1616         // abort startup if command fails
1617         memset (&jc, 0, sizeof(jc));
1618         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1619         {
1620                 Con_Printf ("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr); 
1621                 return;
1622         }
1623
1624         // save the joystick's number of buttons and POV status
1625         joy_numbuttons = jc.wNumButtons;
1626         joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
1627
1628         // old button and POV states default to no buttons pressed
1629         joy_oldbuttonstate = joy_oldpovstate = 0;
1630
1631         // mark the joystick as available and advanced initialization not completed
1632         // this is needed as cvars are not available during initialization
1633
1634         joy_avail = true; 
1635         joy_advancedinit = false;
1636
1637         Con_Printf ("\njoystick detected\n\n"); 
1638 }
1639
1640
1641 /*
1642 ===========
1643 RawValuePointer
1644 ===========
1645 */
1646 PDWORD RawValuePointer (int axis)
1647 {
1648         switch (axis)
1649         {
1650         case JOY_AXIS_X:
1651                 return &ji.dwXpos;
1652         case JOY_AXIS_Y:
1653                 return &ji.dwYpos;
1654         case JOY_AXIS_Z:
1655                 return &ji.dwZpos;
1656         case JOY_AXIS_R:
1657                 return &ji.dwRpos;
1658         case JOY_AXIS_U:
1659                 return &ji.dwUpos;
1660         case JOY_AXIS_V:
1661                 return &ji.dwVpos;
1662         }
1663         return NULL; // LordHavoc: hush compiler warning
1664 }
1665
1666
1667 /*
1668 ===========
1669 Joy_AdvancedUpdate_f
1670 ===========
1671 */
1672 void Joy_AdvancedUpdate_f (void)
1673 {
1674
1675         // called once by IN_ReadJoystick and by user whenever an update is needed
1676         // cvars are now available
1677         int     i;
1678         DWORD dwTemp;
1679
1680         // initialize all the maps
1681         for (i = 0; i < JOY_MAX_AXES; i++)
1682         {
1683                 dwAxisMap[i] = AxisNada;
1684                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1685                 pdwRawValue[i] = RawValuePointer(i);
1686         }
1687
1688         if( joy_advanced.integer == 0)
1689         {
1690                 // default joystick initialization
1691                 // 2 axes only with joystick control
1692                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1693                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1694                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1695                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1696         }
1697         else
1698         {
1699                 if (strcmp (joy_name.string, "joystick") != 0)
1700                 {
1701                         // notify user of advanced controller
1702                         Con_Printf ("\n%s configured\n\n", joy_name.string);
1703                 }
1704
1705                 // advanced initialization here
1706                 // data supplied by user via joy_axisn cvars
1707                 dwTemp = (DWORD) joy_advaxisx.value;
1708                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1709                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1710                 dwTemp = (DWORD) joy_advaxisy.value;
1711                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1712                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1713                 dwTemp = (DWORD) joy_advaxisz.value;
1714                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1715                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1716                 dwTemp = (DWORD) joy_advaxisr.value;
1717                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1718                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1719                 dwTemp = (DWORD) joy_advaxisu.value;
1720                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1721                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1722                 dwTemp = (DWORD) joy_advaxisv.value;
1723                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1724                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1725         }
1726
1727         // compute the axes to collect from DirectInput
1728         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1729         for (i = 0; i < JOY_MAX_AXES; i++)
1730         {
1731                 if (dwAxisMap[i] != AxisNada)
1732                 {
1733                         joy_flags |= dwAxisFlags[i];
1734                 }
1735         }
1736 }
1737
1738
1739 /*
1740 ===========
1741 IN_Commands
1742 ===========
1743 */
1744 void IN_Commands (void)
1745 {
1746         int             i, key_index;
1747         DWORD   buttonstate, povstate;
1748
1749         if (!joy_avail)
1750         {
1751                 return;
1752         }
1753
1754         
1755         // loop through the joystick buttons
1756         // key a joystick event or auxillary event for higher number buttons for each state change
1757         buttonstate = ji.dwButtons;
1758         for (i=0 ; i < (int) joy_numbuttons ; i++)
1759         {
1760                 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1761                 {
1762                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
1763                         Key_Event (key_index + i, true);
1764                 }
1765
1766                 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1767                 {
1768                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
1769                         Key_Event (key_index + i, false);
1770                 }
1771         }
1772         joy_oldbuttonstate = buttonstate;
1773
1774         if (joy_haspov)
1775         {
1776                 // convert POV information into 4 bits of state information
1777                 // this avoids any potential problems related to moving from one
1778                 // direction to another without going through the center position
1779                 povstate = 0;
1780                 if(ji.dwPOV != JOY_POVCENTERED)
1781                 {
1782                         if (ji.dwPOV == JOY_POVFORWARD)
1783                                 povstate |= 0x01;
1784                         if (ji.dwPOV == JOY_POVRIGHT)
1785                                 povstate |= 0x02;
1786                         if (ji.dwPOV == JOY_POVBACKWARD)
1787                                 povstate |= 0x04;
1788                         if (ji.dwPOV == JOY_POVLEFT)
1789                                 povstate |= 0x08;
1790                 }
1791                 // determine which bits have changed and key an auxillary event for each change
1792                 for (i=0 ; i < 4 ; i++)
1793                 {
1794                         if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1795                         {
1796                                 Key_Event (K_AUX29 + i, true);
1797                         }
1798
1799                         if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1800                         {
1801                                 Key_Event (K_AUX29 + i, false);
1802                         }
1803                 }
1804                 joy_oldpovstate = povstate;
1805         }
1806 }
1807
1808
1809 /* 
1810 =============== 
1811 IN_ReadJoystick
1812 =============== 
1813 */  
1814 qboolean IN_ReadJoystick (void)
1815 {
1816
1817         memset (&ji, 0, sizeof(ji));
1818         ji.dwSize = sizeof(ji);
1819         ji.dwFlags = joy_flags;
1820
1821         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1822         {
1823                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1824                 // rather than having 32768 be the zero point, they have the zero point at 32668
1825                 // go figure -- anyway, now we get the full resolution out of the device
1826                 if (joy_wwhack1.integer != 0.0)
1827                 {
1828                         ji.dwUpos += 100;
1829                 }
1830                 return true;
1831         }
1832         else
1833         {
1834                 // read error occurred
1835                 // turning off the joystick seems too harsh for 1 read error,
1836                 // but what should be done?
1837                 return false;
1838         }
1839 }
1840
1841
1842 /*
1843 ===========
1844 IN_JoyMove
1845 ===========
1846 */
1847 void IN_JoyMove (usercmd_t *cmd)
1848 {
1849         float   speed, aspeed;
1850         float   fAxisValue, fTemp;
1851         int             i, mouselook = (in_mlook.state & 1) || freelook.integer;
1852
1853         // complete initialization if first time in
1854         // this is needed as cvars are not available at initialization time
1855         if( joy_advancedinit != true )
1856         {
1857                 Joy_AdvancedUpdate_f();
1858                 joy_advancedinit = true;
1859         }
1860
1861         // verify joystick is available and that the user wants to use it
1862         if (!joy_avail || !in_joystick.integer)
1863         {
1864                 return; 
1865         }
1866
1867         // collect the joystick data, if possible
1868         if (IN_ReadJoystick () != true)
1869         {
1870                 return;
1871         }
1872
1873         if (in_speed.state & 1)
1874                 speed = cl_movespeedkey.value;
1875         else
1876                 speed = 1;
1877         // LordHavoc: viewzoom affects sensitivity for sniping
1878         aspeed = speed * host_realframetime * cl.viewzoom;
1879
1880         // loop through the axes
1881         for (i = 0; i < JOY_MAX_AXES; i++)
1882         {
1883                 // get the floating point zero-centered, potentially-inverted data for the current axis
1884                 fAxisValue = (float) *pdwRawValue[i];
1885                 // move centerpoint to zero
1886                 fAxisValue -= 32768.0;
1887
1888                 if (joy_wwhack2.integer != 0.0)
1889                 {
1890                         if (dwAxisMap[i] == AxisTurn)
1891                         {
1892                                 // this is a special formula for the Logitech WingMan Warrior
1893                                 // y=ax^b; where a = 300 and b = 1.3
1894                                 // also x values are in increments of 800 (so this is factored out)
1895                                 // then bounds check result to level out excessively high spin rates
1896                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1897                                 if (fTemp > 14000.0)
1898                                         fTemp = 14000.0;
1899                                 // restore direction information
1900                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1901                         }
1902                 }
1903
1904                 // convert range from -32768..32767 to -1..1 
1905                 fAxisValue /= 32768.0;
1906
1907                 switch (dwAxisMap[i])
1908                 {
1909                 case AxisForward:
1910                         if ((joy_advanced.integer == 0) && mouselook)
1911                         {
1912                                 // user wants forward control to become look control
1913                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1914                                 {               
1915                                         // if mouse invert is on, invert the joystick pitch value
1916                                         // only absolute control support here (joy_advanced is false)
1917                                         if (m_pitch.value < 0.0)
1918                                         {
1919                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1920                                         }
1921                                         else
1922                                         {
1923                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1924                                         }
1925                                         V_StopPitchDrift();
1926                                 }
1927                                 else
1928                                 {
1929                                         // no pitch movement
1930                                         // disable pitch return-to-center unless requested by user
1931                                         // *** this code can be removed when the lookspring bug is fixed
1932                                         // *** the bug always has the lookspring feature on
1933                                         if(lookspring.value == 0.0)
1934                                                 V_StopPitchDrift();
1935                                 }
1936                         }
1937                         else
1938                         {
1939                                 // user wants forward control to be forward control
1940                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1941                                 {
1942                                         cmd->forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1943                                 }
1944                         }
1945                         break;
1946
1947                 case AxisSide:
1948                         if (fabs(fAxisValue) > joy_sidethreshold.value)
1949                         {
1950                                 cmd->sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1951                         }
1952                         break;
1953
1954                 case AxisTurn:
1955                         if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
1956                         {
1957                                 // user wants turn control to become side control
1958                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
1959                                 {
1960                                         cmd->sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1961                                 }
1962                         }
1963                         else
1964                         {
1965                                 // user wants turn control to be turn control
1966                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
1967                                 {
1968                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1969                                         {
1970                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1971                                         }
1972                                         else
1973                                         {
1974                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
1975                                         }
1976
1977                                 }
1978                         }
1979                         break;
1980
1981                 case AxisLook:
1982                         if (mouselook)
1983                         {
1984                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1985                                 {
1986                                         // pitch movement detected and pitch movement desired by user
1987                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1988                                         {
1989                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1990                                         }
1991                                         else
1992                                         {
1993                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
1994                                         }
1995                                         V_StopPitchDrift();
1996                                 }
1997                                 else
1998                                 {
1999                                         // no pitch movement
2000                                         // disable pitch return-to-center unless requested by user
2001                                         // *** this code can be removed when the lookspring bug is fixed
2002                                         // *** the bug always has the lookspring feature on
2003                                         if(lookspring.integer == 0)
2004                                                 V_StopPitchDrift();
2005                                 }
2006                         }
2007                         break;
2008
2009                 default:
2010                         break;
2011                 }
2012         }
2013 }
2014