2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // gl_vidnt.c -- NT GL vid component
22 // we don't need a very new dinput
23 #define DIRECTINPUT_VERSION 0x0300
37 extern HINSTANCE global_hInstance;
41 #define WM_MOUSEWHEEL 0x020A
44 // Tell startup code that we have a client
45 int cl_available = true;
47 qboolean vid_supportrefreshrate = true;
49 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
50 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
51 //static int (WINAPI *qwglGetPixelFormat)(HDC);
52 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
53 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
54 static HGLRC (WINAPI *qwglCreateContext)(HDC);
55 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
56 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
57 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
58 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
59 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
60 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
61 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
62 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
63 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
65 static dllfunction_t wglfuncs[] =
67 {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
68 {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
69 // {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
70 {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
71 {"wglSwapBuffers", (void **) &qwglSwapBuffers},
72 {"wglCreateContext", (void **) &qwglCreateContext},
73 {"wglDeleteContext", (void **) &qwglDeleteContext},
74 {"wglGetProcAddress", (void **) &qwglGetProcAddress},
75 {"wglMakeCurrent", (void **) &qwglMakeCurrent},
76 {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
77 {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
81 static dllfunction_t wglswapintervalfuncs[] =
83 {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
87 static dllfunction_t wglpixelformatfuncs[] =
89 {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
90 {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
94 static DEVMODE gdevmode, initialdevmode;
95 static qboolean vid_initialized = false;
96 static qboolean vid_wassuspended = false;
97 static qboolean vid_usingmouse = false;
98 static qboolean vid_usingvsync = false;
99 static qboolean vid_usevsync = false;
102 // used by cd_win.c and snd_win.c
108 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
110 static qboolean vid_isfullscreen;
112 //void VID_MenuDraw (void);
113 //void VID_MenuKey (int key);
115 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
116 //void AppActivate(BOOL fActive, BOOL minimize);
117 //void ClearAllStates (void);
118 //void VID_UpdateWindowStatus (void);
120 //====================================
122 static int window_x, window_y;
124 static void IN_Activate (qboolean grab);
126 static qboolean mouseinitialized;
128 #ifdef SUPPORTDIRECTX
129 static qboolean dinput;
130 #define DINPUT_BUFFERSIZE 16
131 #define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d)
133 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
136 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
137 /* backslash :: imouse explorer buttons */
138 /* These are #ifdefed out for non-Win2K in the February 2001 version of
139 MS's platform SDK, but we need them for compilation. . . */
140 #ifndef WM_XBUTTONDOWN
141 #define WM_XBUTTONDOWN 0x020B
142 #define WM_XBUTTONUP 0x020C
145 #define MK_XBUTTON1 0x0020
146 #define MK_XBUTTON2 0x0040
149 // LordHavoc: lets hope this allows more buttons in the future...
150 #define MK_XBUTTON3 0x0080
151 #define MK_XBUTTON4 0x0100
152 #define MK_XBUTTON5 0x0200
153 #define MK_XBUTTON6 0x0400
154 #define MK_XBUTTON7 0x0800
159 static int mouse_buttons;
160 static int mouse_oldbuttonstate;
162 static unsigned int uiWheelMessage;
163 #ifdef SUPPORTDIRECTX
164 static qboolean dinput_acquired;
166 static unsigned int mstate_di;
169 // joystick defines and variables
170 // where should defines be moved?
171 #define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick
172 #define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball
173 #define JOY_MAX_AXES 6 // X, Y, Z, R, U, V
183 AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn
186 static DWORD dwAxisFlags[JOY_MAX_AXES] =
188 JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
191 static DWORD dwAxisMap[JOY_MAX_AXES];
192 static DWORD dwControlMap[JOY_MAX_AXES];
193 static PDWORD pdwRawValue[JOY_MAX_AXES];
195 // none of these cvars are saved over a session
196 // this means that advanced controller configuration needs to be executed
197 // each time. this avoids any problems with getting back to a default usage
198 // or when changing from one controller to another. this way at least something
200 static cvar_t in_joystick = {CVAR_SAVE, "joystick","0", "enables joysticks"};
201 static cvar_t joy_name = {0, "joyname", "joystick", "name of joystick to use (informational only, used only by joyadvanced 1 mode)"};
202 static cvar_t joy_advanced = {0, "joyadvanced", "0", "use more than 2 axis joysticks (configuring this is very technical)"};
203 static cvar_t joy_advaxisx = {0, "joyadvaxisx", "0", "axis mapping for joyadvanced 1 mode"};
204 static cvar_t joy_advaxisy = {0, "joyadvaxisy", "0", "axis mapping for joyadvanced 1 mode"};
205 static cvar_t joy_advaxisz = {0, "joyadvaxisz", "0", "axis mapping for joyadvanced 1 mode"};
206 static cvar_t joy_advaxisr = {0, "joyadvaxisr", "0", "axis mapping for joyadvanced 1 mode"};
207 static cvar_t joy_advaxisu = {0, "joyadvaxisu", "0", "axis mapping for joyadvanced 1 mode"};
208 static cvar_t joy_advaxisv = {0, "joyadvaxisv", "0", "axis mapping for joyadvanced 1 mode"};
209 static cvar_t joy_forwardthreshold = {0, "joyforwardthreshold", "0.15", "minimum joystick movement necessary to move forward"};
210 static cvar_t joy_sidethreshold = {0, "joysidethreshold", "0.15", "minimum joystick movement necessary to move sideways (strafing)"};
211 static cvar_t joy_pitchthreshold = {0, "joypitchthreshold", "0.15", "minimum joystick movement necessary to look up/down"};
212 static cvar_t joy_yawthreshold = {0, "joyyawthreshold", "0.15", "minimum joystick movement necessary to turn left/right"};
213 static cvar_t joy_forwardsensitivity = {0, "joyforwardsensitivity", "-1.0", "how fast the joystick moves forward"};
214 static cvar_t joy_sidesensitivity = {0, "joysidesensitivity", "-1.0", "how fast the joystick moves sideways (strafing)"};
215 static cvar_t joy_pitchsensitivity = {0, "joypitchsensitivity", "1.0", "how fast the joystick looks up/down"};
216 static cvar_t joy_yawsensitivity = {0, "joyyawsensitivity", "-1.0", "how fast the joystick turns left/right"};
217 static cvar_t joy_wwhack1 = {0, "joywwhack1", "0.0", "special hack for wingman warrior"};
218 static cvar_t joy_wwhack2 = {0, "joywwhack2", "0.0", "special hack for wingman warrior"};
220 static cvar_t vid_forcerefreshrate = {0, "vid_forcerefreshrate", "0", "try to set the given vid_refreshrate even if Windows doesn't list it as valid video mode"};
222 static qboolean joy_avail, joy_advancedinit, joy_haspov;
223 static DWORD joy_oldbuttonstate, joy_oldpovstate;
226 static DWORD joy_flags;
227 static DWORD joy_numbuttons;
229 #ifdef SUPPORTDIRECTX
230 static LPDIRECTINPUT g_pdi;
231 static LPDIRECTINPUTDEVICE g_pMouse;
232 static HINSTANCE hInstDI;
237 // forward-referenced functions
238 static void IN_StartupJoystick (void);
239 static void Joy_AdvancedUpdate_f (void);
240 static void IN_JoyMove (void);
241 static void IN_StartupMouse (void);
244 //====================================
246 void VID_Finish (qboolean allowmousegrab)
248 qboolean vid_usemouse;
250 vid_usevsync = vid_vsync.integer && !cls.timedemo && gl_videosyncavailable;
251 if (vid_usingvsync != vid_usevsync && gl_videosyncavailable)
253 vid_usingvsync = vid_usevsync;
254 qwglSwapIntervalEXT (vid_usevsync);
257 // handle the mouse state when windowed if that's changed
258 vid_usemouse = false;
259 if (allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback))
261 if (vid_isfullscreen)
263 if (!vid_activewindow)
264 vid_usemouse = false;
265 IN_Activate(vid_usemouse);
267 if (r_render.integer && !vid_hidden)
270 if (r_speeds.integer || gl_finish.integer)
272 qglFinish();CHECKGLERROR
277 // make sure a context switch can happen every frame - Logitech drivers
278 // input drivers sometimes eat cpu time every 3 seconds or lag badly
282 VID_UpdateGamma(false, 256);
285 //==========================================================================
290 static unsigned char scantokey[128] =
292 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
293 0 ,27 ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'0' ,'-' ,'=' ,K_BACKSPACE,9 ,//0
294 'q' ,'w' ,'e' ,'r' ,'t' ,'y' ,'u' ,'i' ,'o' ,'p' ,'[' ,']' ,13 ,K_CTRL ,'a' ,'s' ,//1
295 'd' ,'f' ,'g' ,'h' ,'j' ,'k' ,'l' ,';' ,'\'' ,'`' ,K_SHIFT ,'\\' ,'z' ,'x' ,'c' ,'v' ,//2
296 'b' ,'n' ,'m' ,',' ,'.' ,'/' ,K_SHIFT,'*' ,K_ALT ,' ' ,0 ,K_F1 ,K_F2 ,K_F3 ,K_F4 ,K_F5 ,//3
297 K_F6 ,K_F7 ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0 ,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5,K_RIGHTARROW,K_KP_PLUS ,K_END,//4
298 K_DOWNARROW,K_PGDN,K_INS,K_DEL,0 ,0 ,0 ,K_F11 ,K_F12 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//5
299 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//6
300 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 //7
308 Map from windows to quake keynums
311 static int MapKey (int key, int virtualkey)
314 int modified = (key >> 16) & 255;
315 qboolean is_extended = false;
317 if (modified < 128 && scantokey[modified])
318 result = scantokey[modified];
322 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
339 return K_KP_LEFTARROW;
341 return K_KP_RIGHTARROW;
345 return K_KP_DOWNARROW;
372 ===================================================================
376 ===================================================================
384 static void ClearAllStates (void)
388 mouse_oldbuttonstate = 0;
391 void AppActivate(BOOL fActive, BOOL minimize)
392 /****************************************************************************
394 * Function: AppActivate
395 * Parameters: fActive - True if app is activating
397 * Description: If the application is activating, then swap the system
398 * into SYSPAL_NOSTATIC mode so that our palettes will display
401 ****************************************************************************/
403 static qboolean sound_active = false; // initially blocked by Sys_InitConsole()
405 vid_activewindow = fActive;
406 vid_hidden = minimize;
408 // enable/disable sound on focus gain/loss
409 if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
422 sound_active = false;
428 if (vid_isfullscreen)
430 if (vid_wassuspended)
432 vid_wassuspended = false;
433 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
434 ShowWindow(mainwindow, SW_SHOWNORMAL);
437 // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
438 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
445 if (vid_isfullscreen)
447 ChangeDisplaySettings (NULL, 0);
448 vid_wassuspended = true;
450 VID_RestoreSystemGamma();
454 //TODO: move it around in vid_wgl.c since I dont think this is the right position
455 void Sys_SendKeyEvents (void)
459 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
461 if (!GetMessage (&msg, NULL, 0, 0))
464 TranslateMessage (&msg);
465 DispatchMessage (&msg);
469 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
471 static keynum_t buttonremap[16] =
491 /* main window procedure */
492 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
495 int fActive, fMinimized, temp;
500 qboolean down = false;
502 if ( uMsg == uiWheelMessage )
503 uMsg = WM_MOUSEWHEEL;
508 if (vid_isfullscreen)
509 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
516 window_x = (int) LOWORD(lParam);
517 window_y = (int) HIWORD(lParam);
526 vkey = MapKey(lParam, wParam);
527 GetKeyboardState (state);
528 // alt/ctrl/shift tend to produce funky ToAscii values,
529 // and if it's not a single character we don't know care about it
530 charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
531 if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
533 else if( charlength == 2 ) {
534 asciichar[0] = asciichar[1];
536 Key_Event (vkey, asciichar[0], down);
540 // keep Alt-Space from happening
544 // prevent screensaver from occuring while the active window
545 // note: password-locked screensavers on Vista still work
546 if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
549 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
552 // this is complicated because Win32 seems to pack multiple mouse events into
553 // one update sometimes, so we always check all states and look for events
560 case WM_XBUTTONDOWN: // backslash :: imouse explorer buttons
561 case WM_XBUTTONUP: // backslash :: imouse explorer buttons
565 if (wParam & MK_LBUTTON)
568 if (wParam & MK_RBUTTON)
571 if (wParam & MK_MBUTTON)
574 /* backslash :: imouse explorer buttons */
575 if (wParam & MK_XBUTTON1)
578 if (wParam & MK_XBUTTON2)
582 // LordHavoc: lets hope this allows more buttons in the future...
583 if (wParam & MK_XBUTTON3)
585 if (wParam & MK_XBUTTON4)
587 if (wParam & MK_XBUTTON5)
589 if (wParam & MK_XBUTTON6)
591 if (wParam & MK_XBUTTON7)
594 #ifdef SUPPORTDIRECTX
595 if (vid_usingmouse && !dinput_acquired)
600 // perform button actions
602 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
603 if ((temp ^ mouse_oldbuttonstate) & (1<<i))
604 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
605 mouse_oldbuttonstate = temp;
610 // JACK: This is the mouse wheel with the Intellimouse
611 // Its delta is either positive or neg, and we generate the proper
614 if ((short) HIWORD(wParam) > 0) {
615 Key_Event(K_MWHEELUP, 0, true);
616 Key_Event(K_MWHEELUP, 0, false);
618 Key_Event(K_MWHEELDOWN, 0, true);
619 Key_Event(K_MWHEELDOWN, 0, false);
627 if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
633 fActive = LOWORD(wParam);
634 fMinimized = (BOOL) HIWORD(wParam);
635 AppActivate(!(fActive == WA_INACTIVE), fMinimized);
637 // fix the leftover Alt from any Alt-Tab or the like that switched us away
643 // PostQuitMessage (0);
647 lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
651 /* pass all unhandled messages to DefWindowProc */
652 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
656 /* return 1 if handled message, 0 if not */
660 int VID_SetGamma(unsigned short *ramps, int rampsize)
662 HDC hdc = GetDC (NULL);
663 int i = SetDeviceGammaRamp(hdc, ramps);
664 ReleaseDC (NULL, hdc);
665 return i; // return success or failure
668 int VID_GetGamma(unsigned short *ramps, int rampsize)
670 HDC hdc = GetDC (NULL);
671 int i = GetDeviceGammaRamp(hdc, ramps);
672 ReleaseDC (NULL, hdc);
673 return i; // return success or failure
676 static HINSTANCE gldll;
678 static void GL_CloseLibrary(void)
683 qwglGetProcAddress = NULL;
686 gl_platformextensions = "";
689 static int GL_OpenLibrary(const char *name)
691 Con_Printf("Loading OpenGL driver %s\n", name);
693 if (!(gldll = LoadLibrary(name)))
695 Con_Printf("Unable to LoadLibrary %s\n", name);
698 strlcpy(gl_driver, name, sizeof(gl_driver));
702 void *GL_GetProcAddress(const char *name)
705 if (qwglGetProcAddress != NULL)
706 p = (void *) qwglGetProcAddress(name);
708 p = (void *) GetProcAddress(gldll, name);
712 #ifndef WGL_ARB_pixel_format
713 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
714 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
715 #define WGL_DRAW_TO_BITMAP_ARB 0x2002
716 #define WGL_ACCELERATION_ARB 0x2003
717 #define WGL_NEED_PALETTE_ARB 0x2004
718 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
719 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
720 #define WGL_SWAP_METHOD_ARB 0x2007
721 #define WGL_NUMBER_OVERLAYS_ARB 0x2008
722 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009
723 #define WGL_TRANSPARENT_ARB 0x200A
724 #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
725 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
726 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
727 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
728 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
729 #define WGL_SHARE_DEPTH_ARB 0x200C
730 #define WGL_SHARE_STENCIL_ARB 0x200D
731 #define WGL_SHARE_ACCUM_ARB 0x200E
732 #define WGL_SUPPORT_GDI_ARB 0x200F
733 #define WGL_SUPPORT_OPENGL_ARB 0x2010
734 #define WGL_DOUBLE_BUFFER_ARB 0x2011
735 #define WGL_STEREO_ARB 0x2012
736 #define WGL_PIXEL_TYPE_ARB 0x2013
737 #define WGL_COLOR_BITS_ARB 0x2014
738 #define WGL_RED_BITS_ARB 0x2015
739 #define WGL_RED_SHIFT_ARB 0x2016
740 #define WGL_GREEN_BITS_ARB 0x2017
741 #define WGL_GREEN_SHIFT_ARB 0x2018
742 #define WGL_BLUE_BITS_ARB 0x2019
743 #define WGL_BLUE_SHIFT_ARB 0x201A
744 #define WGL_ALPHA_BITS_ARB 0x201B
745 #define WGL_ALPHA_SHIFT_ARB 0x201C
746 #define WGL_ACCUM_BITS_ARB 0x201D
747 #define WGL_ACCUM_RED_BITS_ARB 0x201E
748 #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
749 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
750 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
751 #define WGL_DEPTH_BITS_ARB 0x2022
752 #define WGL_STENCIL_BITS_ARB 0x2023
753 #define WGL_AUX_BUFFERS_ARB 0x2024
754 #define WGL_NO_ACCELERATION_ARB 0x2025
755 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
756 #define WGL_FULL_ACCELERATION_ARB 0x2027
757 #define WGL_SWAP_EXCHANGE_ARB 0x2028
758 #define WGL_SWAP_COPY_ARB 0x2029
759 #define WGL_SWAP_UNDEFINED_ARB 0x202A
760 #define WGL_TYPE_RGBA_ARB 0x202B
761 #define WGL_TYPE_COLORINDEX_ARB 0x202C
764 #ifndef WGL_ARB_multisample
765 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
766 #define WGL_SAMPLES_ARB 0x2042
770 static void IN_Init(void);
775 InitCommonControls();
776 hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
778 // Register the frame class
780 wc.lpfnWndProc = (WNDPROC)MainWndProc;
783 wc.hInstance = global_hInstance;
785 wc.hCursor = LoadCursor (NULL,IDC_ARROW);
786 wc.hbrBackground = NULL;
788 wc.lpszClassName = "DarkPlacesWindowClass";
790 if (!RegisterClass (&wc))
791 Con_Printf ("Couldn't register window class\n");
793 memset(&initialdevmode, 0, sizeof(initialdevmode));
794 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
799 int VID_InitMode (int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer, int samples)
805 PIXELFORMATDESCRIPTOR pfd =
807 sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
809 PFD_DRAW_TO_WINDOW // support window
810 | PFD_SUPPORT_OPENGL // support OpenGL
811 | PFD_DOUBLEBUFFER , // double buffered
812 PFD_TYPE_RGBA, // RGBA type
813 24, // 24-bit color depth
814 0, 0, 0, 0, 0, 0, // color bits ignored
815 0, // no alpha buffer
816 0, // shift bit ignored
817 0, // no accumulation buffer
818 0, 0, 0, 0, // accum bits ignored
819 32, // 32-bit z-buffer
820 0, // no stencil buffer
821 0, // no auxiliary buffer
822 PFD_MAIN_PLANE, // main layer
824 0, 0, 0 // layer masks ignored
827 int pixelformat, newpixelformat;
829 DWORD WindowStyle, ExWindowStyle;
830 int CenterX, CenterY;
831 const char *gldrivername;
834 qboolean foundmode, foundgoodmode;
841 Sys_Error("VID_InitMode called when video is already initialised");
843 // if stencil is enabled, ask for alpha too
851 pfd.cStencilBits = 8;
860 pfd.cStencilBits = 0;
864 pfd.dwFlags |= PFD_STEREO;
868 *a++ = WGL_DRAW_TO_WINDOW_ARB;
870 *a++ = WGL_ACCELERATION_ARB;
871 *a++ = WGL_FULL_ACCELERATION_ARB;
872 *a++ = WGL_DOUBLE_BUFFER_ARB;
877 *a++ = WGL_RED_BITS_ARB;
879 *a++ = WGL_GREEN_BITS_ARB;
881 *a++ = WGL_BLUE_BITS_ARB;
883 *a++ = WGL_ALPHA_BITS_ARB;
885 *a++ = WGL_DEPTH_BITS_ARB;
887 *a++ = WGL_STENCIL_BITS_ARB;
892 *a++ = WGL_RED_BITS_ARB;
894 *a++ = WGL_GREEN_BITS_ARB;
896 *a++ = WGL_BLUE_BITS_ARB;
898 *a++ = WGL_DEPTH_BITS_ARB;
904 *a++ = WGL_STEREO_ARB;
910 *a++ = WGL_SAMPLE_BUFFERS_ARB;
912 *a++ = WGL_SAMPLES_ARB;
919 gldrivername = "opengl32.dll";
920 // COMMANDLINEOPTION: Windows WGL: -gl_driver <drivername> selects a GL driver library, default is opengl32.dll, useful only for 3dfxogl.dll or 3dfxvgl.dll, if you don't know what this is for, you don't need it
921 i = COM_CheckParm("-gl_driver");
922 if (i && i < com_argc - 1)
923 gldrivername = com_argv[i + 1];
924 if (!GL_OpenLibrary(gldrivername))
926 Con_Printf("Unable to load GL driver %s\n", gldrivername);
930 memset(&gdevmode, 0, sizeof(gdevmode));
932 vid_isfullscreen = false;
935 if(vid_forcerefreshrate.integer)
938 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
939 gdevmode.dmBitsPerPel = bpp;
940 gdevmode.dmPelsWidth = width;
941 gdevmode.dmPelsHeight = height;
942 gdevmode.dmSize = sizeof (gdevmode);
945 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
946 gdevmode.dmDisplayFrequency = refreshrate;
952 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
955 foundgoodmode = false;
957 thismode.dmSize = sizeof(thismode);
958 thismode.dmDriverExtra = 0;
959 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
961 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
963 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
966 if(developer.integer >= 100)
967 Con_Printf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
968 if(thismode.dmBitsPerPel != (DWORD)bpp)
970 if(developer.integer >= 100)
971 Con_Printf("wrong bpp\n");
974 if(thismode.dmPelsWidth != (DWORD)width)
976 if(developer.integer >= 100)
977 Con_Printf("wrong width\n");
980 if(thismode.dmPelsHeight != (DWORD)height)
982 if(developer.integer >= 100)
983 Con_Printf("wrong height\n");
989 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
990 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
992 if(developer.integer >= 100)
993 Con_Printf("too high refresh rate\n");
996 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
998 if(developer.integer >= 100)
999 Con_Printf("doesn't beat previous best match (too low)\n");
1005 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1006 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1008 if(developer.integer >= 100)
1009 Con_Printf("doesn't beat previous best match (too high)\n");
1013 // otherwise, take anything
1015 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1016 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1017 foundgoodmode = true;
1020 if(developer.integer >= 100)
1021 Con_Printf("(out of range)\n");
1024 if(developer.integer >= 100)
1025 Con_Printf("accepted\n");
1032 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1035 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1038 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1042 vid_isfullscreen = true;
1043 WindowStyle = WS_POPUP;
1044 ExWindowStyle = WS_EX_TOPMOST;
1049 i = GetDeviceCaps(hdc, RASTERCAPS);
1050 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1051 ReleaseDC (NULL, hdc);
1055 Con_Print("Can't run in non-RGB mode\n");
1061 Con_Print("A higher desktop depth is required to run this video mode\n");
1065 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1072 rect.bottom = height;
1073 AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1082 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1083 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1085 CenterX = max(0, CenterX);
1086 CenterY = max(0, CenterY);
1088 // x and y may be changed by WM_MOVE messages
1091 rect.left += CenterX;
1092 rect.right += CenterX;
1093 rect.top += CenterY;
1094 rect.bottom += CenterY;
1098 // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1099 for (windowpass = samples == 1;windowpass < 2;windowpass++)
1102 gl_platformextensions = "";
1104 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1107 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %d, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), NULL, NULL, (int)global_hInstance, NULL);
1112 baseDC = GetDC(mainwindow);
1114 if (!newpixelformat)
1115 newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1116 pixelformat = newpixelformat;
1120 Con_Printf("ChoosePixelFormat(%d, %p) failed\n", (int)baseDC, &pfd);
1124 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1127 Con_Printf("SetPixelFormat(%d, %d, %p) failed\n", (int)baseDC, pixelformat, &pfd);
1131 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1134 Con_Print("wgl functions not found\n");
1138 baseRC = qwglCreateContext(baseDC);
1142 Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1145 if (!qwglMakeCurrent(baseDC, baseRC))
1148 Con_Printf("wglMakeCurrent(%d, %d) failed\n", (int)baseDC, (int)baseRC);
1152 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1155 Con_Print("glGetString not found\n");
1158 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1159 Con_Print("wglGetExtensionsStringARB not found\n");
1161 gl_renderer = (const char *)qglGetString(GL_RENDERER);
1162 gl_vendor = (const char *)qglGetString(GL_VENDOR);
1163 gl_version = (const char *)qglGetString(GL_VERSION);
1164 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1165 gl_platform = "WGL";
1166 gl_platformextensions = "";
1168 if (qwglGetExtensionsStringARB)
1169 gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1173 if (!gl_platformextensions)
1174 gl_platformextensions = "";
1176 // now some nice Windows pain:
1177 // we have created a window, we needed one to find out if there are
1178 // any multisample pixel formats available, the problem is that to
1179 // actually use one of those multisample formats we now have to
1180 // recreate the window (yes Microsoft OpenGL really is that bad)
1182 if (windowpass == 0)
1184 if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1186 // ok we got one - do it all over again with newpixelformat
1187 qwglMakeCurrent(NULL, NULL);
1188 qwglDeleteContext(baseRC);baseRC = 0;
1189 ReleaseDC(mainwindow, baseDC);baseDC = 0;
1190 // eat up any messages waiting for us
1191 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1193 TranslateMessage (&msg);
1194 DispatchMessage (&msg);
1199 Con_DPrintf("GL_VENDOR: %s\n", gl_vendor);
1200 Con_DPrintf("GL_RENDERER: %s\n", gl_renderer);
1201 Con_DPrintf("GL_VERSION: %s\n", gl_version);
1202 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1203 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1207 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1210 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1211 UpdateWindow (mainwindow);
1213 // now we try to make sure we get the focus on the mode switch, because
1214 // sometimes in some systems we don't. We grab the foreground, then
1215 // finish setting up, pump all our messages, and sleep for a little while
1216 // to let messages finish bouncing around the system, then we put
1217 // ourselves at the top of the z order, then grab the foreground again,
1218 // Who knows if it helps, but it probably doesn't hurt
1219 SetForegroundWindow (mainwindow);
1221 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1223 TranslateMessage (&msg);
1224 DispatchMessage (&msg);
1229 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1231 SetForegroundWindow (mainwindow);
1233 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1236 gl_videosyncavailable = false;
1238 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1239 gl_videosyncavailable = GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1243 //vid_menudrawfn = VID_MenuDraw;
1244 //vid_menukeyfn = VID_MenuKey;
1245 vid_usingmouse = false;
1246 vid_usingvsync = false;
1248 vid_initialized = true;
1251 IN_StartupJoystick ();
1253 if (gl_videosyncavailable)
1255 vid_usevsync = vid_vsync.integer;
1256 vid_usingvsync = vid_vsync.integer;
1257 qwglSwapIntervalEXT (vid_usevsync);
1263 static void IN_Shutdown(void);
1264 void VID_Shutdown (void)
1266 if(vid_initialized == false)
1269 VID_RestoreSystemGamma();
1271 vid_initialized = false;
1273 if (qwglMakeCurrent)
1274 qwglMakeCurrent(NULL, NULL);
1275 if (baseRC && qwglDeleteContext)
1276 qwglDeleteContext(baseRC);
1277 // close the library before we get rid of the window
1279 if (baseDC && mainwindow)
1280 ReleaseDC(mainwindow, baseDC);
1281 AppActivate(false, false);
1283 DestroyWindow(mainwindow);
1285 if (vid_isfullscreen)
1286 ChangeDisplaySettings (NULL, 0);
1287 vid_isfullscreen = false;
1290 static void IN_Activate (qboolean grab)
1292 static qboolean restore_spi;
1293 static int originalmouseparms[3];
1295 if (!mouseinitialized)
1300 if (!vid_usingmouse)
1302 vid_usingmouse = true;
1303 cl_ignoremousemoves = 2;
1304 #ifdef SUPPORTDIRECTX
1305 if (dinput && g_pMouse)
1307 IDirectInputDevice_Acquire(g_pMouse);
1308 dinput_acquired = true;
1314 window_rect.left = window_x;
1315 window_rect.top = window_y;
1316 window_rect.right = window_x + vid.width;
1317 window_rect.bottom = window_y + vid.height;
1319 // change mouse settings to turn off acceleration
1320 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1321 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1323 int newmouseparms[3];
1324 newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1325 newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1326 newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1327 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
1330 restore_spi = false;
1331 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1333 SetCapture (mainwindow);
1334 ClipCursor (&window_rect);
1343 vid_usingmouse = false;
1344 cl_ignoremousemoves = 2;
1345 #ifdef SUPPORTDIRECTX
1346 if (dinput_acquired)
1348 IDirectInputDevice_Unacquire(g_pMouse);
1349 dinput_acquired = false;
1354 // restore system mouseparms if we changed them
1356 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1357 restore_spi = false;
1367 #ifdef SUPPORTDIRECTX
1373 static qboolean IN_InitDInput (void)
1376 DIPROPDWORD dipdw = {
1378 sizeof(DIPROPDWORD), // diph.dwSize
1379 sizeof(DIPROPHEADER), // diph.dwHeaderSize
1381 DIPH_DEVICE, // diph.dwHow
1383 DINPUT_BUFFERSIZE, // dwData
1388 hInstDI = LoadLibrary("dinput.dll");
1390 if (hInstDI == NULL)
1392 Con_Print("Couldn't load dinput.dll\n");
1397 if (!pDirectInputCreate)
1399 pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA");
1401 if (!pDirectInputCreate)
1403 Con_Print("Couldn't get DI proc addr\n");
1408 // register with DirectInput and get an IDirectInput to play with.
1409 hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1416 // obtain an interface to the system mouse device.
1417 hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1421 Con_Print("Couldn't open DI mouse device\n");
1425 // set the data format to "mouse format".
1426 hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1430 Con_Print("Couldn't set DI mouse format\n");
1434 // set the cooperativity level.
1435 hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1436 DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1440 Con_Print("Couldn't set DI coop level\n");
1445 // set the buffer size to DINPUT_BUFFERSIZE elements.
1446 // the buffer size is a DWORD property associated with the device
1447 hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1451 Con_Print("Couldn't set DI buffersize\n");
1465 static void IN_StartupMouse (void)
1467 if (COM_CheckParm ("-nomouse"))
1470 mouseinitialized = true;
1472 #ifdef SUPPORTDIRECTX
1473 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse/joystick input
1474 if (COM_CheckParm ("-dinput"))
1475 dinput = IN_InitDInput ();
1478 Con_Print("DirectInput initialized\n");
1480 Con_Print("DirectInput not initialized\n");
1492 static void IN_MouseMove (void)
1497 if (!vid_usingmouse)
1499 //GetCursorPos (¤t_pos);
1500 //ui_mouseupdate(current_pos.x - window_x, current_pos.y - window_y);
1504 #ifdef SUPPORTDIRECTX
1505 if (dinput_acquired)
1508 DIDEVICEOBJECTDATA od;
1518 hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1519 sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1521 if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1523 IDirectInputDevice_Acquire(g_pMouse);
1527 /* Unable to read data or no data available */
1528 if (FAILED(hr) || dwElements == 0)
1531 /* Look at the element to see what happened */
1536 mx += (LONG) od.dwData;
1540 my += (LONG) od.dwData;
1544 if((LONG) od.dwData < 0)
1546 Key_Event (K_MWHEELDOWN, 0, true);
1547 Key_Event (K_MWHEELDOWN, 0, false);
1549 else if((LONG) od.dwData > 0)
1551 Key_Event (K_MWHEELUP, 0, true);
1552 Key_Event (K_MWHEELUP, 0, false);
1556 case DIMOFS_BUTTON0:
1557 if (od.dwData & 0x80)
1563 case DIMOFS_BUTTON1:
1564 if (od.dwData & 0x80)
1565 mstate_di |= (1<<1);
1567 mstate_di &= ~(1<<1);
1570 case DIMOFS_BUTTON2:
1571 if (od.dwData & 0x80)
1572 mstate_di |= (1<<2);
1574 mstate_di &= ~(1<<2);
1577 case DIMOFS_BUTTON3:
1578 if (od.dwData & 0x80)
1579 mstate_di |= (1<<3);
1581 mstate_di &= ~(1<<3);
1586 // perform button actions
1587 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1588 if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1589 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1590 mouse_oldbuttonstate = mstate_di;
1598 GetCursorPos (¤t_pos);
1599 mx = current_pos.x - (window_x + vid.width / 2);
1600 my = current_pos.y - (window_y + vid.height / 2);
1605 // if the mouse has moved, force it to the center, so there's room to move
1606 if (!cl.csqc_wantsmousemove)
1608 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1620 if (vid_activewindow && !vid_hidden)
1633 static void IN_StartupJoystick (void)
1640 // assume no joystick
1643 // abort startup if user requests no joystick
1644 // COMMANDLINEOPTION: Windows Input: -nojoy disables joystick support, may be a small speed increase
1645 if (COM_CheckParm ("-nojoy"))
1648 // verify joystick driver is present
1649 if ((numdevs = joyGetNumDevs ()) == 0)
1651 Con_Print("\njoystick not found -- driver not present\n\n");
1655 // cycle through the joystick ids for the first valid one
1656 for (joy_id=0 ; joy_id<numdevs ; joy_id++)
1658 memset (&ji, 0, sizeof(ji));
1659 ji.dwSize = sizeof(ji);
1660 ji.dwFlags = JOY_RETURNCENTERED;
1662 if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
1666 // abort startup if we didn't find a valid joystick
1667 if (mmr != JOYERR_NOERROR)
1669 Con_Printf("\njoystick not found -- no valid joysticks (%x)\n\n", mmr);
1673 // get the capabilities of the selected joystick
1674 // abort startup if command fails
1675 memset (&jc, 0, sizeof(jc));
1676 if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
1678 Con_Printf("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
1682 // save the joystick's number of buttons and POV status
1683 joy_numbuttons = jc.wNumButtons;
1684 joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
1686 // old button and POV states default to no buttons pressed
1687 joy_oldbuttonstate = joy_oldpovstate = 0;
1689 // mark the joystick as available and advanced initialization not completed
1690 // this is needed as cvars are not available during initialization
1693 joy_advancedinit = false;
1695 Con_Print("\njoystick detected\n\n");
1704 static PDWORD RawValuePointer (int axis)
1721 return NULL; // LordHavoc: hush compiler warning
1727 Joy_AdvancedUpdate_f
1730 static void Joy_AdvancedUpdate_f (void)
1733 // called once by IN_ReadJoystick and by user whenever an update is needed
1734 // cvars are now available
1738 // initialize all the maps
1739 for (i = 0; i < JOY_MAX_AXES; i++)
1741 dwAxisMap[i] = AxisNada;
1742 dwControlMap[i] = JOY_ABSOLUTE_AXIS;
1743 pdwRawValue[i] = RawValuePointer(i);
1746 if( joy_advanced.integer == 0)
1748 // default joystick initialization
1749 // 2 axes only with joystick control
1750 dwAxisMap[JOY_AXIS_X] = AxisTurn;
1751 // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
1752 dwAxisMap[JOY_AXIS_Y] = AxisForward;
1753 // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
1757 if (strcmp (joy_name.string, "joystick") != 0)
1759 // notify user of advanced controller
1760 Con_Printf("\n%s configured\n\n", joy_name.string);
1763 // advanced initialization here
1764 // data supplied by user via joy_axisn cvars
1765 dwTemp = (DWORD) joy_advaxisx.value;
1766 dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
1767 dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
1768 dwTemp = (DWORD) joy_advaxisy.value;
1769 dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
1770 dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
1771 dwTemp = (DWORD) joy_advaxisz.value;
1772 dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
1773 dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
1774 dwTemp = (DWORD) joy_advaxisr.value;
1775 dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
1776 dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
1777 dwTemp = (DWORD) joy_advaxisu.value;
1778 dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
1779 dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
1780 dwTemp = (DWORD) joy_advaxisv.value;
1781 dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
1782 dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
1785 // compute the axes to collect from DirectInput
1786 joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
1787 for (i = 0; i < JOY_MAX_AXES; i++)
1789 if (dwAxisMap[i] != AxisNada)
1791 joy_flags |= dwAxisFlags[i];
1801 static qboolean IN_ReadJoystick (void)
1804 memset (&ji, 0, sizeof(ji));
1805 ji.dwSize = sizeof(ji);
1806 ji.dwFlags = joy_flags;
1808 if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
1810 // this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
1811 // rather than having 32768 be the zero point, they have the zero point at 32668
1812 // go figure -- anyway, now we get the full resolution out of the device
1813 if (joy_wwhack1.integer != 0.0)
1821 // read error occurred
1822 // turning off the joystick seems too harsh for 1 read error,
1823 // but what should be done?
1834 static void IN_JoyMove (void)
1836 float speed, aspeed;
1837 float fAxisValue, fTemp;
1838 int i, mouselook = (in_mlook.state & 1) || freelook.integer;
1840 // complete initialization if first time in
1841 // this is needed as cvars are not available at initialization time
1842 if( joy_advancedinit != true )
1844 Joy_AdvancedUpdate_f();
1845 joy_advancedinit = true;
1851 DWORD buttonstate, povstate;
1853 // loop through the joystick buttons
1854 // key a joystick event or auxillary event for higher number buttons for each state change
1855 buttonstate = ji.dwButtons;
1856 for (i=0 ; i < (int) joy_numbuttons ; i++)
1858 if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
1860 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1861 Key_Event (key_index + i, 0, true);
1864 if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
1866 key_index = (i < 16) ? K_JOY1 : K_AUX1;
1867 Key_Event (key_index + i, 0, false);
1870 joy_oldbuttonstate = buttonstate;
1874 // convert POV information into 4 bits of state information
1875 // this avoids any potential problems related to moving from one
1876 // direction to another without going through the center position
1878 if(ji.dwPOV != JOY_POVCENTERED)
1880 if (ji.dwPOV == JOY_POVFORWARD)
1882 if (ji.dwPOV == JOY_POVRIGHT)
1884 if (ji.dwPOV == JOY_POVBACKWARD)
1886 if (ji.dwPOV == JOY_POVLEFT)
1889 // determine which bits have changed and key an auxillary event for each change
1890 for (i=0 ; i < 4 ; i++)
1892 if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
1894 Key_Event (K_AUX29 + i, 0, true);
1897 if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
1899 Key_Event (K_AUX29 + i, 0, false);
1902 joy_oldpovstate = povstate;
1906 // verify joystick is available and that the user wants to use it
1907 if (!joy_avail || !in_joystick.integer)
1912 // collect the joystick data, if possible
1913 if (IN_ReadJoystick () != true)
1918 if (in_speed.state & 1)
1919 speed = cl_movespeedkey.value;
1922 // LordHavoc: viewzoom affects sensitivity for sniping
1923 aspeed = speed * cl.realframetime * cl.viewzoom;
1925 // loop through the axes
1926 for (i = 0; i < JOY_MAX_AXES; i++)
1928 // get the floating point zero-centered, potentially-inverted data for the current axis
1929 fAxisValue = (float) *pdwRawValue[i];
1930 // move centerpoint to zero
1931 fAxisValue -= 32768.0;
1933 if (joy_wwhack2.integer != 0.0)
1935 if (dwAxisMap[i] == AxisTurn)
1937 // this is a special formula for the Logitech WingMan Warrior
1938 // y=ax^b; where a = 300 and b = 1.3
1939 // also x values are in increments of 800 (so this is factored out)
1940 // then bounds check result to level out excessively high spin rates
1941 fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
1942 if (fTemp > 14000.0)
1944 // restore direction information
1945 fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
1949 // convert range from -32768..32767 to -1..1
1950 fAxisValue /= 32768.0;
1952 switch (dwAxisMap[i])
1955 if ((joy_advanced.integer == 0) && mouselook)
1957 // user wants forward control to become look control
1958 if (fabs(fAxisValue) > joy_pitchthreshold.value)
1960 // if mouse invert is on, invert the joystick pitch value
1961 // only absolute control support here (joy_advanced is false)
1962 if (m_pitch.value < 0.0)
1964 cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1968 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
1974 // no pitch movement
1975 // disable pitch return-to-center unless requested by user
1976 // *** this code can be removed when the lookspring bug is fixed
1977 // *** the bug always has the lookspring feature on
1978 if(lookspring.value == 0.0)
1984 // user wants forward control to be forward control
1985 if (fabs(fAxisValue) > joy_forwardthreshold.value)
1987 cl.cmd.forwardmove += (fAxisValue * joy_forwardsensitivity.value) * speed * cl_forwardspeed.value;
1993 if (fabs(fAxisValue) > joy_sidethreshold.value)
1995 cl.cmd.sidemove += (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
2000 if ((in_strafe.state & 1) || (lookstrafe.integer && mouselook))
2002 // user wants turn control to become side control
2003 if (fabs(fAxisValue) > joy_sidethreshold.value)
2005 cl.cmd.sidemove -= (fAxisValue * joy_sidesensitivity.value) * speed * cl_sidespeed.value;
2010 // user wants turn control to be turn control
2011 if (fabs(fAxisValue) > joy_yawthreshold.value)
2013 if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2015 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * aspeed * cl_yawspeed.value;
2019 cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity.value) * speed * 180.0;
2029 if (fabs(fAxisValue) > joy_pitchthreshold.value)
2031 // pitch movement detected and pitch movement desired by user
2032 if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
2034 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * aspeed * cl_pitchspeed.value;
2038 cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity.value) * speed * 180.0;
2044 // no pitch movement
2045 // disable pitch return-to-center unless requested by user
2046 // *** this code can be removed when the lookspring bug is fixed
2047 // *** the bug always has the lookspring feature on
2048 if(lookspring.integer == 0)
2060 static void IN_Init(void)
2062 uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2064 // joystick variables
2065 Cvar_RegisterVariable (&in_joystick);
2066 Cvar_RegisterVariable (&joy_name);
2067 Cvar_RegisterVariable (&joy_advanced);
2068 Cvar_RegisterVariable (&joy_advaxisx);
2069 Cvar_RegisterVariable (&joy_advaxisy);
2070 Cvar_RegisterVariable (&joy_advaxisz);
2071 Cvar_RegisterVariable (&joy_advaxisr);
2072 Cvar_RegisterVariable (&joy_advaxisu);
2073 Cvar_RegisterVariable (&joy_advaxisv);
2074 Cvar_RegisterVariable (&joy_forwardthreshold);
2075 Cvar_RegisterVariable (&joy_sidethreshold);
2076 Cvar_RegisterVariable (&joy_pitchthreshold);
2077 Cvar_RegisterVariable (&joy_yawthreshold);
2078 Cvar_RegisterVariable (&joy_forwardsensitivity);
2079 Cvar_RegisterVariable (&joy_sidesensitivity);
2080 Cvar_RegisterVariable (&joy_pitchsensitivity);
2081 Cvar_RegisterVariable (&joy_yawsensitivity);
2082 Cvar_RegisterVariable (&joy_wwhack1);
2083 Cvar_RegisterVariable (&joy_wwhack2);
2084 Cvar_RegisterVariable (&vid_forcerefreshrate);
2085 Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f, "applies current joyadv* cvar settings to the joystick driver");
2088 static void IN_Shutdown(void)
2090 IN_Activate (false);
2092 #ifdef SUPPORTDIRECTX
2094 IDirectInputDevice_Release(g_pMouse);
2098 IDirectInput_Release(g_pdi);