]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - in_win.c
optimized AngleVectors calls (pass NULL for vectors that should not be generated)
[xonotic/darkplaces.git] / in_win.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 // in_win.c -- windows 95 mouse and joystick code
21 // 02/21/97 JCB Added extended DirectInput code to support external controllers.
22
23 #include <dinput.h>
24 #include "quakedef.h"
25 #include "winquake.h"
26 //#include "dosisms.h"
27
28 #define DINPUT_BUFFERSIZE           16
29 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
30
31 HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion,
32         LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
33
34 // mouse variables
35 cvar_t  m_filter = {"m_filter","0"};
36
37 int                     mouse_buttons;
38 int                     mouse_oldbuttonstate;
39 POINT           current_pos;
40 int                     mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum;
41
42 static qboolean restore_spi;
43 static int              originalmouseparms[3], newmouseparms[3] = {0, 0, 1};
44
45 unsigned int uiWheelMessage;
46 qboolean        mouseactive;
47 qboolean                mouseinitialized;
48 static qboolean mouseparmsvalid, mouseactivatetoggle;
49 static qboolean mouseshowtoggle = 1;
50 static qboolean dinput_acquired;
51
52 static unsigned int             mstate_di;
53
54 // joystick defines and variables
55 // where should defines be moved?
56 #define JOY_ABSOLUTE_AXIS       0x00000000              // control like a joystick
57 #define JOY_RELATIVE_AXIS       0x00000010              // control like a mouse, spinner, trackball
58 #define JOY_MAX_AXES            6                               // X, Y, Z, R, U, V
59 #define JOY_AXIS_X                      0
60 #define JOY_AXIS_Y                      1
61 #define JOY_AXIS_Z                      2
62 #define JOY_AXIS_R                      3
63 #define JOY_AXIS_U                      4
64 #define JOY_AXIS_V                      5
65
66 enum _ControlList
67 {
68         AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
69 };
70
71 DWORD   dwAxisFlags[JOY_MAX_AXES] =
72 {
73         JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
74 };
75
76 DWORD   dwAxisMap[JOY_MAX_AXES];
77 DWORD   dwControlMap[JOY_MAX_AXES];
78 PDWORD  pdwRawValue[JOY_MAX_AXES];
79
80 // none of these cvars are saved over a session
81 // this means that advanced controller configuration needs to be executed
82 // each time.  this avoids any problems with getting back to a default usage
83 // or when changing from one controller to another.  this way at least something
84 // works.
85 cvar_t  in_joystick = {"joystick","0", true};
86 cvar_t  joy_name = {"joyname", "joystick"};
87 cvar_t  joy_advanced = {"joyadvanced", "0"};
88 cvar_t  joy_advaxisx = {"joyadvaxisx", "0"};
89 cvar_t  joy_advaxisy = {"joyadvaxisy", "0"};
90 cvar_t  joy_advaxisz = {"joyadvaxisz", "0"};
91 cvar_t  joy_advaxisr = {"joyadvaxisr", "0"};
92 cvar_t  joy_advaxisu = {"joyadvaxisu", "0"};
93 cvar_t  joy_advaxisv = {"joyadvaxisv", "0"};
94 cvar_t  joy_forwardthreshold = {"joyforwardthreshold", "0.15"};
95 cvar_t  joy_sidethreshold = {"joysidethreshold", "0.15"};
96 cvar_t  joy_pitchthreshold = {"joypitchthreshold", "0.15"};
97 cvar_t  joy_yawthreshold = {"joyyawthreshold", "0.15"};
98 cvar_t  joy_forwardsensitivity = {"joyforwardsensitivity", "-1.0"};
99 cvar_t  joy_sidesensitivity = {"joysidesensitivity", "-1.0"};
100 cvar_t  joy_pitchsensitivity = {"joypitchsensitivity", "1.0"};
101 cvar_t  joy_yawsensitivity = {"joyyawsensitivity", "-1.0"};
102 cvar_t  joy_wwhack1 = {"joywwhack1", "0.0"};
103 cvar_t  joy_wwhack2 = {"joywwhack2", "0.0"};
104
105 qboolean        joy_avail, joy_advancedinit, joy_haspov;
106 DWORD           joy_oldbuttonstate, joy_oldpovstate;
107
108 int                     joy_id;
109 DWORD           joy_flags;
110 DWORD           joy_numbuttons;
111
112 static LPDIRECTINPUT            g_pdi;
113 static LPDIRECTINPUTDEVICE      g_pMouse;
114
115 static JOYINFOEX        ji;
116
117 static HINSTANCE hInstDI;
118
119 static qboolean dinput;
120
121 typedef struct MYDATA {
122         LONG  lX;                   // X axis goes here
123         LONG  lY;                   // Y axis goes here
124         LONG  lZ;                   // Z axis goes here
125         BYTE  bButtonA;             // One button goes here
126         BYTE  bButtonB;             // Another button goes here
127         BYTE  bButtonC;             // Another button goes here
128         BYTE  bButtonD;             // Another button goes here
129 } MYDATA;
130
131 static DIOBJECTDATAFORMAT rgodf[] = {
132   { &GUID_XAxis,    FIELD_OFFSET(MYDATA, lX),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
133   { &GUID_YAxis,    FIELD_OFFSET(MYDATA, lY),       DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
134   { &GUID_ZAxis,    FIELD_OFFSET(MYDATA, lZ),       0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE,   0,},
135   { 0,              FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
136   { 0,              FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
137   { 0,              FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
138   { 0,              FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,},
139 };
140
141 #define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0]))
142
143 static DIDATAFORMAT     df = {
144         sizeof(DIDATAFORMAT),       // this structure
145         sizeof(DIOBJECTDATAFORMAT), // size of object data format
146         DIDF_RELAXIS,               // absolute axis coordinates
147         sizeof(MYDATA),             // device data size
148         NUM_OBJECTS,                // number of objects
149         rgodf,                      // and here they are
150 };
151
152 // forward-referenced functions
153 void IN_StartupJoystick (void);
154 void Joy_AdvancedUpdate_f (void);
155 void IN_JoyMove (usercmd_t *cmd);
156
157
158 /*
159 ===========
160 Force_CenterView_f
161 ===========
162 */
163 void Force_CenterView_f (void)
164 {
165         cl.viewangles[PITCH] = 0;
166 }
167
168
169 /*
170 ===========
171 IN_UpdateClipCursor
172 ===========
173 */
174 void IN_UpdateClipCursor (void)
175 {
176
177         if (mouseinitialized && mouseactive && !dinput)
178         {
179                 ClipCursor (&window_rect);
180         }
181 }
182
183
184 /*
185 ===========
186 IN_ShowMouse
187 ===========
188 */
189 void IN_ShowMouse (void)
190 {
191
192         if (!mouseshowtoggle)
193         {
194                 ShowCursor (true);
195                 mouseshowtoggle = 1;
196         }
197 }
198
199
200 /*
201 ===========
202 IN_HideMouse
203 ===========
204 */
205 void IN_HideMouse (void)
206 {
207
208         if (mouseshowtoggle)
209         {
210                 ShowCursor (false);
211                 mouseshowtoggle = 0;
212         }
213 }
214
215
216 /*
217 ===========
218 IN_ActivateMouse
219 ===========
220 */
221 void IN_ActivateMouse (void)
222 {
223
224         mouseactivatetoggle = true;
225
226         if (mouseinitialized)
227         {
228                 if (dinput)
229                 {
230                         if (g_pMouse)
231                         {
232                                 if (!dinput_acquired)
233                                 {
234                                         IDirectInputDevice_Acquire(g_pMouse);
235                                         dinput_acquired = true;
236                                 }
237                         }
238                         else
239                         {
240                                 return;
241                         }
242                 }
243                 else
244                 {
245                         if (mouseparmsvalid)
246                                 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
247
248                         SetCursorPos (window_center_x, window_center_y);
249                         SetCapture (mainwindow);
250                         ClipCursor (&window_rect);
251                 }
252
253                 mouseactive = true;
254         }
255 }
256
257
258 /*
259 ===========
260 IN_SetQuakeMouseState
261 ===========
262 */
263 void IN_SetQuakeMouseState (void)
264 {
265         if (mouseactivatetoggle)
266                 IN_ActivateMouse ();
267 }
268
269
270 /*
271 ===========
272 IN_DeactivateMouse
273 ===========
274 */
275 void IN_DeactivateMouse (void)
276 {
277
278         mouseactivatetoggle = false;
279
280         if (mouseinitialized)
281         {
282                 if (dinput)
283                 {
284                         if (g_pMouse)
285                         {
286                                 if (dinput_acquired)
287                                 {
288                                         IDirectInputDevice_Unacquire(g_pMouse);
289                                         dinput_acquired = false;
290                                 }
291                         }
292                 }
293                 else
294                 {
295                         if (restore_spi)
296                                 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
297
298                         ClipCursor (NULL);
299                         ReleaseCapture ();
300                 }
301
302                 mouseactive = false;
303         }
304 }
305
306
307 /*
308 ===========
309 IN_RestoreOriginalMouseState
310 ===========
311 */
312 void IN_RestoreOriginalMouseState (void)
313 {
314         if (mouseactivatetoggle)
315         {
316                 IN_DeactivateMouse ();
317                 mouseactivatetoggle = true;
318         }
319
320 // try to redraw the cursor so it gets reinitialized, because sometimes it
321 // has garbage after the mode switch
322         ShowCursor (true);
323         ShowCursor (false);
324 }
325
326
327 /*
328 ===========
329 IN_InitDInput
330 ===========
331 */
332 qboolean IN_InitDInput (void)
333 {
334     HRESULT             hr;
335         DIPROPDWORD     dipdw = {
336                 {
337                         sizeof(DIPROPDWORD),        // diph.dwSize
338                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
339                         0,                          // diph.dwObj
340                         DIPH_DEVICE,                // diph.dwHow
341                 },
342                 DINPUT_BUFFERSIZE,              // dwData
343         };
344
345         if (!hInstDI)
346         {
347                 hInstDI = LoadLibrary("dinput.dll");
348                 
349                 if (hInstDI == NULL)
350                 {
351                         Con_SafePrintf ("Couldn't load dinput.dll\n");
352                         return false;
353                 }
354         }
355
356         if (!pDirectInputCreate)
357         {
358                 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
359
360                 if (!pDirectInputCreate)
361                 {
362                         Con_SafePrintf ("Couldn't get DI proc addr\n");
363                         return false;
364                 }
365         }
366
367 // register with DirectInput and get an IDirectInput to play with.
368         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
369
370         if (FAILED(hr))
371         {
372                 return false;
373         }
374
375 // obtain an interface to the system mouse device.
376         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
377
378         if (FAILED(hr))
379         {
380                 Con_SafePrintf ("Couldn't open DI mouse device\n");
381                 return false;
382         }
383
384 // set the data format to "mouse format".
385         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df);
386
387         if (FAILED(hr))
388         {
389                 Con_SafePrintf ("Couldn't set DI mouse format\n");
390                 return false;
391         }
392
393 // set the cooperativity level.
394         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
395                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
396
397         if (FAILED(hr))
398         {
399                 Con_SafePrintf ("Couldn't set DI coop level\n");
400                 return false;
401         }
402
403
404 // set the buffer size to DINPUT_BUFFERSIZE elements.
405 // the buffer size is a DWORD property associated with the device
406         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
407
408         if (FAILED(hr))
409         {
410                 Con_SafePrintf ("Couldn't set DI buffersize\n");
411                 return false;
412         }
413
414         return true;
415 }
416
417
418 /*
419 ===========
420 IN_StartupMouse
421 ===========
422 */
423 void IN_StartupMouse (void)
424 {
425         if ( COM_CheckParm ("-nomouse") ) 
426                 return; 
427
428         mouseinitialized = true;
429
430         if (COM_CheckParm ("-dinput"))
431         {
432                 dinput = IN_InitDInput ();
433
434                 if (dinput)
435                 {
436                         Con_SafePrintf ("DirectInput initialized\n");
437                 }
438                 else
439                 {
440                         Con_SafePrintf ("DirectInput not initialized\n");
441                 }
442         }
443
444         if (!dinput)
445         {
446                 mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0);
447
448                 if (mouseparmsvalid)
449                 {
450                         if ( COM_CheckParm ("-noforcemspd") ) 
451                                 newmouseparms[2] = originalmouseparms[2];
452
453                         if ( COM_CheckParm ("-noforcemaccel") ) 
454                         {
455                                 newmouseparms[0] = originalmouseparms[0];
456                                 newmouseparms[1] = originalmouseparms[1];
457                         }
458
459                         if ( COM_CheckParm ("-noforcemparms") ) 
460                         {
461                                 newmouseparms[0] = originalmouseparms[0];
462                                 newmouseparms[1] = originalmouseparms[1];
463                                 newmouseparms[2] = originalmouseparms[2];
464                         }
465                 }
466         }
467
468         mouse_buttons = 3;
469
470 // if a fullscreen video mode was set before the mouse was initialized,
471 // set the mouse state appropriately
472         if (mouseactivatetoggle)
473                 IN_ActivateMouse ();
474 }
475
476
477 /*
478 ===========
479 IN_Init
480 ===========
481 */
482 void IN_Init (void)
483 {
484         // mouse variables
485         Cvar_RegisterVariable (&m_filter);
486
487         // joystick variables
488         Cvar_RegisterVariable (&in_joystick);
489         Cvar_RegisterVariable (&joy_name);
490         Cvar_RegisterVariable (&joy_advanced);
491         Cvar_RegisterVariable (&joy_advaxisx);
492         Cvar_RegisterVariable (&joy_advaxisy);
493         Cvar_RegisterVariable (&joy_advaxisz);
494         Cvar_RegisterVariable (&joy_advaxisr);
495         Cvar_RegisterVariable (&joy_advaxisu);
496         Cvar_RegisterVariable (&joy_advaxisv);
497         Cvar_RegisterVariable (&joy_forwardthreshold);
498         Cvar_RegisterVariable (&joy_sidethreshold);
499         Cvar_RegisterVariable (&joy_pitchthreshold);
500         Cvar_RegisterVariable (&joy_yawthreshold);
501         Cvar_RegisterVariable (&joy_forwardsensitivity);
502         Cvar_RegisterVariable (&joy_sidesensitivity);
503         Cvar_RegisterVariable (&joy_pitchsensitivity);
504         Cvar_RegisterVariable (&joy_yawsensitivity);
505         Cvar_RegisterVariable (&joy_wwhack1);
506         Cvar_RegisterVariable (&joy_wwhack2);
507
508         Cmd_AddCommand ("force_centerview", Force_CenterView_f);
509         Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f);
510
511         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
512
513         IN_StartupMouse ();
514         IN_StartupJoystick ();
515 }
516
517 /*
518 ===========
519 IN_Shutdown
520 ===========
521 */
522 void IN_Shutdown (void)
523 {
524
525         IN_DeactivateMouse ();
526         IN_ShowMouse ();
527
528     if (g_pMouse)
529         {
530                 IDirectInputDevice_Release(g_pMouse);
531                 g_pMouse = NULL;
532         }
533
534     if (g_pdi)
535         {
536                 IDirectInput_Release(g_pdi);
537                 g_pdi = NULL;
538         }
539 }
540
541
542 /*
543 ===========
544 IN_MouseEvent
545 ===========
546 */
547 void IN_MouseEvent (int mstate)
548 {
549         int     i;
550
551         if (mouseactive && !dinput)
552         {
553         // perform button actions
554                 for (i=0 ; i<mouse_buttons ; i++)
555                 {
556                         if ( (mstate & (1<<i)) &&
557                                 !(mouse_oldbuttonstate & (1<<i)) )
558                         {
559                                 Key_Event (K_MOUSE1 + i, true);
560                         }
561
562                         if ( !(mstate & (1<<i)) &&
563                                 (mouse_oldbuttonstate & (1<<i)) )
564                         {
565                                 Key_Event (K_MOUSE1 + i, false);
566                         }
567                 }       
568                         
569                 mouse_oldbuttonstate = mstate;
570         }
571 }
572
573
574 /*
575 ===========
576 IN_MouseMove
577 ===========
578 */
579 void IN_MouseMove (usercmd_t *cmd)
580 {
581         int                                     mx, my;
582         int                                     i;
583         DIDEVICEOBJECTDATA      od;
584         DWORD                           dwElements;
585         HRESULT                         hr;
586
587         if (!mouseactive)
588                 return;
589
590         if (dinput)
591         {
592                 mx = 0;
593                 my = 0;
594
595                 for (;;)
596                 {
597                         dwElements = 1;
598
599                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
600                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
601
602                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
603                         {
604                                 dinput_acquired = true;
605                                 IDirectInputDevice_Acquire(g_pMouse);
606                                 break;
607                         }
608
609                         /* Unable to read data or no data available */
610                         if (FAILED(hr) || dwElements == 0)
611                         {
612                                 break;
613                         }
614
615                         /* Look at the element to see what happened */
616
617                         switch (od.dwOfs)
618                         {
619                                 case DIMOFS_X:
620                                         mx += od.dwData;
621                                         break;
622
623                                 case DIMOFS_Y:
624                                         my += od.dwData;
625                                         break;
626
627                                 case DIMOFS_BUTTON0:
628                                         if (od.dwData & 0x80)
629                                                 mstate_di |= 1;
630                                         else
631                                                 mstate_di &= ~1;
632                                         break;
633
634                                 case DIMOFS_BUTTON1:
635                                         if (od.dwData & 0x80)
636                                                 mstate_di |= (1<<1);
637                                         else
638                                                 mstate_di &= ~(1<<1);
639                                         break;
640                                         
641                                 case DIMOFS_BUTTON2:
642                                         if (od.dwData & 0x80)
643                                                 mstate_di |= (1<<2);
644                                         else
645                                                 mstate_di &= ~(1<<2);
646                                         break;
647                         }
648                 }
649
650         // perform button actions
651                 for (i=0 ; i<mouse_buttons ; i++)
652                 {
653                         if ( (mstate_di & (1<<i)) &&
654                                 !(mouse_oldbuttonstate & (1<<i)) )
655                         {
656                                 Key_Event (K_MOUSE1 + i, true);
657                         }
658
659                         if ( !(mstate_di & (1<<i)) &&
660                                 (mouse_oldbuttonstate & (1<<i)) )
661                         {
662                                 Key_Event (K_MOUSE1 + i, false);
663                         }
664                 }       
665                         
666                 mouse_oldbuttonstate = mstate_di;
667         }
668         else
669         {
670                 GetCursorPos (&current_pos);
671                 mx = current_pos.x - window_center_x + mx_accum;
672                 my = current_pos.y - window_center_y + my_accum;
673                 mx_accum = 0;
674                 my_accum = 0;
675         }
676
677 //if (mx ||  my)
678 //      Con_DPrintf("mx=%d, my=%d\n", mx, my);
679
680         if (m_filter.value)
681         {
682                 mouse_x = (mx + old_mouse_x) * 0.5;
683                 mouse_y = (my + old_mouse_y) * 0.5;
684         }
685         else
686         {
687                 mouse_x = mx;
688                 mouse_y = my;
689         }
690
691         old_mouse_x = mx;
692         old_mouse_y = my;
693
694         mouse_x *= sensitivity.value;
695         mouse_y *= sensitivity.value;
696
697 // add mouse X/Y movement to cmd
698         if ( (in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1) ))
699                 cmd->sidemove += m_side.value * mouse_x;
700         else
701                 cl.viewangles[YAW] -= m_yaw.value * mouse_x;
702
703         if (in_mlook.state & 1)
704                 V_StopPitchDrift ();
705         
706         // LordHavoc: changed limits on pitch from -70 to 80, to -90 to 90
707         if ( (in_mlook.state & 1) && !(in_strafe.state & 1))
708         {
709                 cl.viewangles[PITCH] += m_pitch.value * mouse_y;
710                 if (cl.viewangles[PITCH] > 90)
711                         cl.viewangles[PITCH] = 90;
712                 if (cl.viewangles[PITCH] < -90)
713                         cl.viewangles[PITCH] = -90;
714         }
715         else
716         {
717                 if ((in_strafe.state & 1) && noclip_anglehack)
718                         cmd->upmove -= m_forward.value * mouse_y;
719                 else
720                         cmd->forwardmove -= m_forward.value * mouse_y;
721         }
722
723 // if the mouse has moved, force it to the center, so there's room to move
724         if (mx || my)
725         {
726                 SetCursorPos (window_center_x, window_center_y);
727         }
728 }
729
730
731 /*
732 ===========
733 IN_Move
734 ===========
735 */
736 void IN_Move (usercmd_t *cmd)
737 {
738
739         if (ActiveApp && !Minimized)
740         {
741                 IN_MouseMove (cmd);
742                 IN_JoyMove (cmd);
743         }
744 }
745
746
747 /*
748 ===========
749 IN_Accumulate
750 ===========
751 */
752 void IN_Accumulate (void)
753 {
754         if (mouseactive)
755         {
756                 if (!dinput)
757                 {
758                         GetCursorPos (&current_pos);
759
760                         mx_accum += current_pos.x - window_center_x;
761                         my_accum += current_pos.y - window_center_y;
762
763                 // force the mouse to the center, so there's room to move
764                         SetCursorPos (window_center_x, window_center_y);
765                 }
766         }
767 }
768
769
770 /*
771 ===================
772 IN_ClearStates
773 ===================
774 */
775 void IN_ClearStates (void)
776 {
777
778         if (mouseactive)
779         {
780                 mx_accum = 0;
781                 my_accum = 0;
782                 mouse_oldbuttonstate = 0;
783         }
784 }
785
786
787 /* 
788 =============== 
789 IN_StartupJoystick 
790 =============== 
791 */  
792 void IN_StartupJoystick (void) 
793
794         int                     numdevs;
795         JOYCAPS         jc;
796         MMRESULT        mmr;
797  
798         // assume no joystick
799         joy_avail = false; 
800
801         // abort startup if user requests no joystick
802         if ( COM_CheckParm ("-nojoy") ) 
803                 return; 
804  
805         // verify joystick driver is present
806         if ((numdevs = joyGetNumDevs ()) == 0)
807         {
808                 Con_Printf ("\njoystick not found -- driver not present\n\n");
809                 return;
810         }
811
812         // cycle through the joystick ids for the first valid one
813         for (joy_id=0 ; joy_id<numdevs ; joy_id++)
814         {
815                 memset (&ji, 0, sizeof(ji));
816                 ji.dwSize = sizeof(ji);
817                 ji.dwFlags = JOY_RETURNCENTERED;
818
819                 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
820                         break;
821         } 
822
823         // abort startup if we didn't find a valid joystick
824         if (mmr != JOYERR_NOERROR)
825         {
826                 Con_Printf ("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
827                 return;
828         }
829
830         // get the capabilities of the selected joystick
831         // abort startup if command fails
832         memset (&jc, 0, sizeof(jc));
833         if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
834         {
835                 Con_Printf ("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr); 
836                 return;
837         }
838
839         // save the joystick's number of buttons and POV status
840         joy_numbuttons = jc.wNumButtons;
841         joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
842
843         // old button and POV states default to no buttons pressed
844         joy_oldbuttonstate = joy_oldpovstate = 0;
845
846         // mark the joystick as available and advanced initialization not completed
847         // this is needed as cvars are not available during initialization
848
849         joy_avail = true; 
850         joy_advancedinit = false;
851
852         Con_Printf ("\njoystick detected\n\n"); 
853 }
854
855
856 /*
857 ===========
858 RawValuePointer
859 ===========
860 */
861 PDWORD RawValuePointer (int axis)
862 {
863         switch (axis)
864         {
865         case JOY_AXIS_X:
866                 return &ji.dwXpos;
867         case JOY_AXIS_Y:
868                 return &ji.dwYpos;
869         case JOY_AXIS_Z:
870                 return &ji.dwZpos;
871         case JOY_AXIS_R:
872                 return &ji.dwRpos;
873         case JOY_AXIS_U:
874                 return &ji.dwUpos;
875         case JOY_AXIS_V:
876                 return &ji.dwVpos;
877         }
878         return NULL; // LordHavoc: hush compiler warning
879 }
880
881
882 /*
883 ===========
884 Joy_AdvancedUpdate_f
885 ===========
886 */
887 void Joy_AdvancedUpdate_f (void)
888 {
889
890         // called once by IN_ReadJoystick and by user whenever an update is needed
891         // cvars are now available
892         int     i;
893         DWORD dwTemp;
894
895         // initialize all the maps
896         for (i = 0; i < JOY_MAX_AXES; i++)
897         {
898                 dwAxisMap[i] = AxisNada;
899                 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
900                 pdwRawValue[i] = RawValuePointer(i);
901         }
902
903         if( joy_advanced.value == 0.0)
904         {
905                 // default joystick initialization
906                 // 2 axes only with joystick control
907                 dwAxisMap[JOY_AXIS_X] = AxisTurn;
908                 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
909                 dwAxisMap[JOY_AXIS_Y] = AxisForward;
910                 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
911         }
912         else
913         {
914                 if (strcmp (joy_name.string, "joystick") != 0)
915                 {
916                         // notify user of advanced controller
917                         Con_Printf ("\n%s configured\n\n", joy_name.string);
918                 }
919
920                 // advanced initialization here
921                 // data supplied by user via joy_axisn cvars
922                 dwTemp = (DWORD) joy_advaxisx.value;
923                 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
924                 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
925                 dwTemp = (DWORD) joy_advaxisy.value;
926                 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
927                 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
928                 dwTemp = (DWORD) joy_advaxisz.value;
929                 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
930                 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
931                 dwTemp = (DWORD) joy_advaxisr.value;
932                 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
933                 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
934                 dwTemp = (DWORD) joy_advaxisu.value;
935                 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
936                 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
937                 dwTemp = (DWORD) joy_advaxisv.value;
938                 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
939                 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
940         }
941
942         // compute the axes to collect from DirectInput
943         joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
944         for (i = 0; i < JOY_MAX_AXES; i++)
945         {
946                 if (dwAxisMap[i] != AxisNada)
947                 {
948                         joy_flags |= dwAxisFlags[i];
949                 }
950         }
951 }
952
953
954 /*
955 ===========
956 IN_Commands
957 ===========
958 */
959 void IN_Commands (void)
960 {
961         int             i, key_index;
962         DWORD   buttonstate, povstate;
963
964         if (!joy_avail)
965         {
966                 return;
967         }
968
969         
970         // loop through the joystick buttons
971         // key a joystick event or auxillary event for higher number buttons for each state change
972         buttonstate = ji.dwButtons;
973         for (i=0 ; i < (int) joy_numbuttons ; i++)
974         {
975                 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
976                 {
977                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
978                         Key_Event (key_index + i, true);
979                 }
980
981                 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
982                 {
983                         key_index = (i < 4) ? K_JOY1 : K_AUX1;
984                         Key_Event (key_index + i, false);
985                 }
986         }
987         joy_oldbuttonstate = buttonstate;
988
989         if (joy_haspov)
990         {
991                 // convert POV information into 4 bits of state information
992                 // this avoids any potential problems related to moving from one
993                 // direction to another without going through the center position
994                 povstate = 0;
995                 if(ji.dwPOV != JOY_POVCENTERED)
996                 {
997                         if (ji.dwPOV == JOY_POVFORWARD)
998                                 povstate |= 0x01;
999                         if (ji.dwPOV == JOY_POVRIGHT)
1000                                 povstate |= 0x02;
1001                         if (ji.dwPOV == JOY_POVBACKWARD)
1002                                 povstate |= 0x04;
1003                         if (ji.dwPOV == JOY_POVLEFT)
1004                                 povstate |= 0x08;
1005                 }
1006                 // determine which bits have changed and key an auxillary event for each change
1007                 for (i=0 ; i < 4 ; i++)
1008                 {
1009                         if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1010                         {
1011                                 Key_Event (K_AUX29 + i, true);
1012                         }
1013
1014                         if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1015                         {
1016                                 Key_Event (K_AUX29 + i, false);
1017                         }
1018                 }
1019                 joy_oldpovstate = povstate;
1020         }
1021 }
1022
1023
1024 /* 
1025 =============== 
1026 IN_ReadJoystick
1027 =============== 
1028 */  
1029 qboolean IN_ReadJoystick (void)
1030 {
1031
1032         memset (&ji, 0, sizeof(ji));
1033         ji.dwSize = sizeof(ji);
1034         ji.dwFlags = joy_flags;
1035
1036         if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1037         {
1038                 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1039                 // rather than having 32768 be the zero point, they have the zero point at 32668
1040                 // go figure -- anyway, now we get the full resolution out of the device
1041                 if (joy_wwhack1.value != 0.0)
1042                 {
1043                         ji.dwUpos += 100;
1044                 }
1045                 return true;
1046         }
1047         else
1048         {
1049                 // read error occurred
1050                 // turning off the joystick seems too harsh for 1 read error,\
1051                 // but what should be done?
1052                 // Con_Printf ("IN_ReadJoystick: no response\n");
1053                 // joy_avail = false;
1054                 return false;
1055         }
1056 }
1057
1058
1059 /*
1060 ===========
1061 IN_JoyMove
1062 ===========
1063 */
1064 void IN_JoyMove (usercmd_t *cmd)
1065 {
1066         float   speed, aspeed;
1067         float   fAxisValue, fTemp;
1068         int             i;
1069
1070         // complete initialization if first time in
1071         // this is needed as cvars are not available at initialization time
1072         if( joy_advancedinit != true )
1073         {
1074                 Joy_AdvancedUpdate_f();
1075                 joy_advancedinit = true;
1076         }
1077
1078         // verify joystick is available and that the user wants to use it
1079         if (!joy_avail || !in_joystick.value)
1080         {
1081                 return; 
1082         }
1083  
1084         // collect the joystick data, if possible
1085         if (IN_ReadJoystick () != true)
1086         {
1087                 return;
1088         }
1089
1090         if (in_speed.state & 1)
1091                 speed = cl_movespeedkey.value;
1092         else
1093                 speed = 1;
1094         aspeed = speed * host_realframetime;
1095
1096         // loop through the axes
1097         for (i = 0; i < JOY_MAX_AXES; i++)
1098         {
1099                 // get the floating point zero-centered, potentially-inverted data for the current axis
1100                 fAxisValue = (float) *pdwRawValue[i];
1101                 // move centerpoint to zero
1102                 fAxisValue -= 32768.0;
1103
1104                 if (joy_wwhack2.value != 0.0)
1105                 {
1106                         if (dwAxisMap[i] == AxisTurn)
1107                         {
1108                                 // this is a special formula for the Logitech WingMan Warrior
1109                                 // y=ax^b; where a = 300 and b = 1.3
1110                                 // also x values are in increments of 800 (so this is factored out)
1111                                 // then bounds check result to level out excessively high spin rates
1112                                 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1113                                 if (fTemp > 14000.0)
1114                                         fTemp = 14000.0;
1115                                 // restore direction information
1116                                 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1117                         }
1118                 }
1119
1120                 // convert range from -32768..32767 to -1..1 
1121                 fAxisValue /= 32768.0;
1122
1123                 switch (dwAxisMap[i])
1124                 {
1125                 case AxisForward:
1126                         if ((joy_advanced.value == 0.0) && (in_mlook.state & 1))
1127                         {
1128                                 // user wants forward control to become look control
1129                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1130                                 {               
1131                                         // if mouse invert is on, invert the joystick pitch value
1132                                         // only absolute control support here (joy_advanced is false)
1133                                         if (m_pitch.value < 0.0)
1134                                         {
1135                                                 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1136                                         }
1137                                         else
1138                                         {
1139                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1140                                         }
1141                                         V_StopPitchDrift();
1142                                 }
1143                                 else
1144                                 {
1145                                         // no pitch movement
1146                                         // disable pitch return-to-center unless requested by user
1147                                         // *** this code can be removed when the lookspring bug is fixed
1148                                         // *** the bug always has the lookspring feature on
1149                                         if(lookspring.value == 0.0)
1150                                                 V_StopPitchDrift();
1151                                 }
1152                         }
1153                         else
1154                         {
1155                                 // user wants forward control to be forward control
1156                                 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1157                                 {
1158                                         cmd->forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1159                                 }
1160                         }
1161                         break;
1162
1163                 case AxisSide:
1164                         if (fabs(fAxisValue) > joy_sidethreshold.value)
1165                         {
1166                                 cmd->sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1167                         }
1168                         break;
1169
1170                 case AxisTurn:
1171                         if ((in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1)))
1172                         {
1173                                 // user wants turn control to become side control
1174                                 if (fabs(fAxisValue) > joy_sidethreshold.value)
1175                                 {
1176                                         cmd->sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
1177                                 }
1178                         }
1179                         else
1180                         {
1181                                 // user wants turn control to be turn control
1182                                 if (fabs(fAxisValue) > joy_yawthreshold.value)
1183                                 {
1184                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1185                                         {
1186                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
1187                                         }
1188                                         else
1189                                         {
1190                                                 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
1191                                         }
1192
1193                                 }
1194                         }
1195                         break;
1196
1197                 case AxisLook:
1198                         if (in_mlook.state & 1)
1199                         {
1200                                 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1201                                 {
1202                                         // pitch movement detected and pitch movement desired by user
1203                                         if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
1204                                         {
1205                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1206                                         }
1207                                         else
1208                                         {
1209                                                 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
1210                                         }
1211                                         V_StopPitchDrift();
1212                                 }
1213                                 else
1214                                 {
1215                                         // no pitch movement
1216                                         // disable pitch return-to-center unless requested by user
1217                                         // *** this code can be removed when the lookspring bug is fixed
1218                                         // *** the bug always has the lookspring feature on
1219                                         if(lookspring.value == 0.0)
1220                                                 V_StopPitchDrift();
1221                                 }
1222                         }
1223                         break;
1224
1225                 default:
1226                         break;
1227                 }
1228         }
1229
1230         // bounds check pitch
1231         if (cl.viewangles[PITCH] > 80.0)
1232                 cl.viewangles[PITCH] = 80.0;
1233         if (cl.viewangles[PITCH] < -70.0)
1234                 cl.viewangles[PITCH] = -70.0;
1235 }