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 // vid_wgl.c -- NT GL vid component
23 #pragma comment(lib, "comctl32.lib")
29 #pragma comment(lib, "dinput8.lib")
30 #pragma comment(lib, "dxguid.lib")
32 #ifndef DIRECTINPUT_VERSION
33 # define DIRECTINPUT_VERSION 0x0500 /* Version 5.0 */
49 extern HINSTANCE global_hInstance;
51 static HINSTANCE gldll;
54 #define WM_MOUSEWHEEL 0x020A
57 // Tell startup code that we have a client
58 int cl_available = true;
60 qboolean vid_supportrefreshrate = true;
62 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
63 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
64 //static int (WINAPI *qwglGetPixelFormat)(HDC);
65 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
66 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
67 static HGLRC (WINAPI *qwglCreateContext)(HDC);
68 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
69 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
70 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
71 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
72 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
73 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
74 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
75 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
76 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
78 static dllfunction_t wglfuncs[] =
80 {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
81 {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
82 // {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
83 {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
84 {"wglSwapBuffers", (void **) &qwglSwapBuffers},
85 {"wglCreateContext", (void **) &qwglCreateContext},
86 {"wglDeleteContext", (void **) &qwglDeleteContext},
87 {"wglGetProcAddress", (void **) &qwglGetProcAddress},
88 {"wglMakeCurrent", (void **) &qwglMakeCurrent},
89 {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
90 {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
94 static dllfunction_t wglswapintervalfuncs[] =
96 {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
100 static dllfunction_t wglpixelformatfuncs[] =
102 {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
103 {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
107 static DEVMODE gdevmode, initialdevmode;
108 static vid_mode_t desktop_mode;
109 static qboolean vid_initialized = false;
110 static qboolean vid_wassuspended = false;
111 static qboolean vid_usingmouse = false;
112 static qboolean vid_usinghidecursor = false;
113 static qboolean vid_usingvsync = false;
114 static qboolean vid_usevsync = false;
117 // used by cd_win.c and snd_win.c
123 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
125 static qboolean vid_isfullscreen;
127 //void VID_MenuDraw (void);
128 //void VID_MenuKey (int key);
130 LONG WINAPI MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
131 void AppActivate(BOOL fActive, BOOL minimize);
132 static void ClearAllStates(void);
133 qboolean VID_InitModeGL(viddef_mode_t *mode);
134 qboolean VID_InitModeSOFT(viddef_mode_t *mode);
136 //====================================
138 static int window_x, window_y;
140 static qboolean mouseinitialized;
142 #ifdef SUPPORTDIRECTX
143 static qboolean dinput;
144 #define DINPUT_BUFFERSIZE 16
145 #define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d)
147 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
150 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
151 /* backslash :: imouse explorer buttons */
152 /* These are #ifdefed out for non-Win2K in the February 2001 version of
153 MS's platform SDK, but we need them for compilation. . . */
154 #ifndef WM_XBUTTONDOWN
155 #define WM_XBUTTONDOWN 0x020B
156 #define WM_XBUTTONUP 0x020C
159 #define MK_XBUTTON1 0x0020
160 #define MK_XBUTTON2 0x0040
163 // LordHavoc: lets hope this allows more buttons in the future...
164 #define MK_XBUTTON3 0x0080
165 #define MK_XBUTTON4 0x0100
166 #define MK_XBUTTON5 0x0200
167 #define MK_XBUTTON6 0x0400
168 #define MK_XBUTTON7 0x0800
173 static int mouse_buttons;
174 static int mouse_oldbuttonstate;
176 static unsigned int uiWheelMessage;
177 #ifdef SUPPORTDIRECTX
178 static qboolean dinput_acquired;
180 static unsigned int mstate_di;
183 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"};
185 #ifdef SUPPORTDIRECTX
186 static LPDIRECTINPUT g_pdi;
187 static LPDIRECTINPUTDEVICE g_pMouse;
188 static HINSTANCE hInstDI;
191 // forward-referenced functions
192 static void IN_StartupMouse (void);
193 static void AdjustWindowBounds(int fullscreen, int *width, int *height, viddef_mode_t *mode, DWORD WindowStyle, RECT *rect);
195 //====================================
197 qboolean vid_reallyhidden = true;
198 void VID_Finish (void)
200 vid_hidden = vid_reallyhidden;
202 vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
206 switch(vid.renderpath)
208 case RENDERPATH_GL20:
209 case RENDERPATH_GLES2:
210 if (vid_usingvsync != vid_usevsync)
212 vid_usingvsync = vid_usevsync;
213 qwglSwapIntervalEXT (vid_usevsync);
215 if (r_speeds.integer == 2 || gl_finish.integer)
222 // make sure a context switch can happen every frame - Logitech drivers
223 // input drivers sometimes eat cpu time every 3 seconds or lag badly
230 //==========================================================================
233 static unsigned char scantokey[128] =
235 // 0 1 2 3 4 5 6 7 8 9 A B C D E F
236 0 ,K_ESCAPE,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'0' ,'-' ,'=' ,K_BACKSPACE,K_TAB,//0
237 'q' ,'w' ,'e' ,'r' ,'t' ,'y' ,'u' ,'i' ,'o' ,'p' ,'[' ,']' ,K_ENTER,K_CTRL ,'a' ,'s' ,//1
238 'd' ,'f' ,'g' ,'h' ,'j' ,'k' ,'l' ,';' ,'\'' ,'`' ,K_SHIFT ,'\\' ,'z' ,'x' ,'c' ,'v' ,//2
239 'b' ,'n' ,'m' ,',' ,'.' ,'/' ,K_SHIFT ,'*' ,K_ALT ,' ' ,K_CAPSLOCK,K_F1 ,K_F2 ,K_F3 ,K_F4 ,K_F5 ,//3
240 K_F6 ,K_F7 ,K_F8 ,K_F9 ,K_F10,K_PAUSE,K_SCROLLOCK,K_HOME,K_UPARROW,K_PGUP,K_KP_MINUS,K_LEFTARROW,K_KP_5 ,K_RIGHTARROW,K_KP_PLUS ,K_END,//4
241 K_DOWNARROW,K_PGDN ,K_INS,K_DEL,0 ,0 ,0 ,K_F11 ,K_F12 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//5
242 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,//6
243 0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 //7
251 Map from windows to quake keynums
254 static int MapKey (int key, int virtualkey)
257 int modified = (key >> 16) & 255;
258 qboolean is_extended = false;
260 if (modified < 128 && scantokey[modified])
261 result = scantokey[modified];
265 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
273 if(((GetKeyState(VK_NUMLOCK)) & 0xffff) == 0)
285 return K_KP_LEFTARROW;
287 return K_KP_RIGHTARROW;
291 return K_KP_DOWNARROW;
304 if(virtualkey == VK_NUMLOCK)
321 ===================================================================
325 ===================================================================
333 static void ClearAllStates (void)
337 mouse_oldbuttonstate = 0;
340 void AppActivate(BOOL fActive, BOOL minimize)
341 /****************************************************************************
343 * Function: AppActivate
344 * Parameters: fActive - True if app is activating
346 * Description: If the application is activating, then swap the system
347 * into SYSPAL_NOSTATIC mode so that our palettes will display
350 ****************************************************************************/
352 static qboolean sound_active = false; // initially blocked by Sys_InitConsole()
354 vid_activewindow = fActive != FALSE;
355 vid_reallyhidden = minimize != FALSE;
357 // enable/disable sound on focus gain/loss
358 if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
371 sound_active = false;
377 if (vid_isfullscreen)
379 if (vid_wassuspended)
381 vid_wassuspended = false;
384 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
385 ShowWindow(mainwindow, SW_SHOWNORMAL);
389 // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
391 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
397 VID_SetMouse(false, false, false);
398 if (vid_isfullscreen)
401 ChangeDisplaySettings (NULL, CDS_FULLSCREEN);
402 vid_wassuspended = true;
407 //TODO: move it around in vid_wgl.c since I dont think this is the right position
408 void Sys_SendKeyEvents (void)
412 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
414 if (!GetMessage (&msg, NULL, 0, 0))
417 TranslateMessage (&msg);
418 DispatchMessage (&msg);
423 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
426 static keynum_t buttonremap[16] =
446 /* main window procedure */
447 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
450 int fActive, fMinimized, temp;
451 unsigned char state[256];
452 const unsigned int UNICODE_BUFFER_LENGTH = 4;
453 WCHAR unicode[UNICODE_BUFFER_LENGTH];
456 qboolean down = false;
458 if ( uMsg == uiWheelMessage )
459 uMsg = WM_MOUSEWHEEL;
464 if (vid_isfullscreen)
465 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
472 window_x = (short) LOWORD(lParam);
473 window_y = (short) HIWORD(lParam);
474 VID_SetMouse(false, false, false);
482 vkey = MapKey(lParam, wParam);
483 GetKeyboardState (state);
484 // alt/ctrl/shift tend to produce funky ToAscii values,
485 // and if it's not a single character we don't know care about it
486 charlength = ToUnicode(wParam, lParam >> 16, state, unicode, UNICODE_BUFFER_LENGTH, 0);
487 if(vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
489 else if(charlength == 2)
490 unicode[0] = unicode[1];
491 if (!VID_JoyBlockEmulatedKeys(vkey))
492 Key_Event(vkey, unicode[0], down);
496 // keep Alt-Space from happening
500 // prevent screensaver from occuring while the active window
501 // note: password-locked screensavers on Vista still work
502 if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
505 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
508 // this is complicated because Win32 seems to pack multiple mouse events into
509 // one update sometimes, so we always check all states and look for events
516 case WM_XBUTTONDOWN: // backslash :: imouse explorer buttons
517 case WM_XBUTTONUP: // backslash :: imouse explorer buttons
521 if (wParam & MK_LBUTTON)
524 if (wParam & MK_RBUTTON)
527 if (wParam & MK_MBUTTON)
530 /* backslash :: imouse explorer buttons */
531 if (wParam & MK_XBUTTON1)
534 if (wParam & MK_XBUTTON2)
538 // LordHavoc: lets hope this allows more buttons in the future...
539 if (wParam & MK_XBUTTON3)
541 if (wParam & MK_XBUTTON4)
543 if (wParam & MK_XBUTTON5)
545 if (wParam & MK_XBUTTON6)
547 if (wParam & MK_XBUTTON7)
550 #ifdef SUPPORTDIRECTX
551 if (!dinput_acquired)
554 // perform button actions
556 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
557 if ((temp ^ mouse_oldbuttonstate) & (1<<i))
558 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
559 mouse_oldbuttonstate = temp;
564 // JACK: This is the mouse wheel with the Intellimouse
565 // Its delta is either positive or neg, and we generate the proper
568 if ((short) HIWORD(wParam) > 0) {
569 Key_Event(K_MWHEELUP, 0, true);
570 Key_Event(K_MWHEELUP, 0, false);
572 Key_Event(K_MWHEELDOWN, 0, true);
573 Key_Event(K_MWHEELDOWN, 0, false);
581 if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
587 fActive = LOWORD(wParam);
588 fMinimized = (BOOL) HIWORD(wParam);
589 AppActivate(!(fActive == WA_INACTIVE), fMinimized);
591 // fix the leftover Alt from any Alt-Tab or the like that switched us away
597 // PostQuitMessage (0);
602 lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
607 /* pass all unhandled messages to DefWindowProc */
608 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
612 /* return 1 if handled message, 0 if not */
616 static void GL_CloseLibrary(void)
623 qwglGetProcAddress = NULL;
626 gl_platformextensions = "";
630 static int GL_OpenLibrary(const char *name)
632 Con_Printf("Loading OpenGL driver %s\n", name);
634 if (!(gldll = LoadLibrary(name)))
636 Con_Printf("Unable to LoadLibrary %s\n", name);
639 strlcpy(gl_driver, name, sizeof(gl_driver));
643 void *GL_GetProcAddress(const char *name)
648 if (qwglGetProcAddress != NULL)
649 p = (void *) qwglGetProcAddress(name);
651 p = (void *) GetProcAddress(gldll, name);
658 #ifndef WGL_ARB_pixel_format
659 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
660 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
661 #define WGL_DRAW_TO_BITMAP_ARB 0x2002
662 #define WGL_ACCELERATION_ARB 0x2003
663 #define WGL_NEED_PALETTE_ARB 0x2004
664 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
665 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
666 #define WGL_SWAP_METHOD_ARB 0x2007
667 #define WGL_NUMBER_OVERLAYS_ARB 0x2008
668 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009
669 #define WGL_TRANSPARENT_ARB 0x200A
670 #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
671 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
672 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
673 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
674 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
675 #define WGL_SHARE_DEPTH_ARB 0x200C
676 #define WGL_SHARE_STENCIL_ARB 0x200D
677 #define WGL_SHARE_ACCUM_ARB 0x200E
678 #define WGL_SUPPORT_GDI_ARB 0x200F
679 #define WGL_SUPPORT_OPENGL_ARB 0x2010
680 #define WGL_DOUBLE_BUFFER_ARB 0x2011
681 #define WGL_STEREO_ARB 0x2012
682 #define WGL_PIXEL_TYPE_ARB 0x2013
683 #define WGL_COLOR_BITS_ARB 0x2014
684 #define WGL_RED_BITS_ARB 0x2015
685 #define WGL_RED_SHIFT_ARB 0x2016
686 #define WGL_GREEN_BITS_ARB 0x2017
687 #define WGL_GREEN_SHIFT_ARB 0x2018
688 #define WGL_BLUE_BITS_ARB 0x2019
689 #define WGL_BLUE_SHIFT_ARB 0x201A
690 #define WGL_ALPHA_BITS_ARB 0x201B
691 #define WGL_ALPHA_SHIFT_ARB 0x201C
692 #define WGL_ACCUM_BITS_ARB 0x201D
693 #define WGL_ACCUM_RED_BITS_ARB 0x201E
694 #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
695 #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
696 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
697 #define WGL_DEPTH_BITS_ARB 0x2022
698 #define WGL_STENCIL_BITS_ARB 0x2023
699 #define WGL_AUX_BUFFERS_ARB 0x2024
700 #define WGL_NO_ACCELERATION_ARB 0x2025
701 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
702 #define WGL_FULL_ACCELERATION_ARB 0x2027
703 #define WGL_SWAP_EXCHANGE_ARB 0x2028
704 #define WGL_SWAP_COPY_ARB 0x2029
705 #define WGL_SWAP_UNDEFINED_ARB 0x202A
706 #define WGL_TYPE_RGBA_ARB 0x202B
707 #define WGL_TYPE_COLORINDEX_ARB 0x202C
710 #ifndef WGL_ARB_multisample
711 #define WGL_SAMPLE_BUFFERS_ARB 0x2041
712 #define WGL_SAMPLES_ARB 0x2042
716 static void IN_Init(void);
721 InitCommonControls();
722 hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
724 // Register the frame class
726 wc.lpfnWndProc = (WNDPROC)MainWndProc;
729 wc.hInstance = global_hInstance;
731 wc.hCursor = LoadCursor (NULL,IDC_ARROW);
732 wc.hbrBackground = NULL;
734 wc.lpszClassName = "DarkPlacesWindowClass";
736 if (!RegisterClass (&wc))
737 Con_Printf ("Couldn't register window class\n");
739 memset(&initialdevmode, 0, sizeof(initialdevmode));
740 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
742 desktop_mode.width = initialdevmode.dmPelsWidth;
743 desktop_mode.height = initialdevmode.dmPelsHeight;
744 desktop_mode.bpp = initialdevmode.dmBitsPerPel;
745 desktop_mode.refreshrate = initialdevmode.dmDisplayFrequency;
746 desktop_mode.pixelheight_num = 1;
747 desktop_mode.pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
752 qboolean VID_InitModeGL(viddef_mode_t *mode)
758 PIXELFORMATDESCRIPTOR pfd =
760 sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
762 PFD_DRAW_TO_WINDOW // support window
763 | PFD_SUPPORT_OPENGL // support OpenGL
764 | PFD_DOUBLEBUFFER , // double buffered
765 PFD_TYPE_RGBA, // RGBA type
766 24, // 24-bit color depth
767 0, 0, 0, 0, 0, 0, // color bits ignored
768 0, // no alpha buffer
769 0, // shift bit ignored
770 0, // no accumulation buffer
771 0, 0, 0, 0, // accum bits ignored
772 32, // 32-bit z-buffer
773 0, // no stencil buffer
774 0, // no auxiliary buffer
775 PFD_MAIN_PLANE, // main layer
777 0, 0, 0 // layer masks ignored
780 int pixelformat, newpixelformat;
781 UINT numpixelformats;
782 DWORD WindowStyle, ExWindowStyle;
783 const char *gldrivername;
786 qboolean foundmode, foundgoodmode;
791 int bpp = mode->bitsperpixel;
792 int width = mode->width;
793 int height = mode->height;
794 int refreshrate = (int)floor(mode->refreshrate+0.5);
795 int stereobuffer = mode->stereobuffer;
796 int samples = mode->samples;
797 int fullscreen = mode->fullscreen;
800 Sys_Error("VID_InitMode called when video is already initialised");
802 // if stencil is enabled, ask for alpha too
810 pfd.cStencilBits = 8;
819 pfd.cStencilBits = 0;
823 pfd.dwFlags |= PFD_STEREO;
827 *a++ = WGL_DRAW_TO_WINDOW_ARB;
829 *a++ = WGL_ACCELERATION_ARB;
830 *a++ = WGL_FULL_ACCELERATION_ARB;
831 *a++ = WGL_DOUBLE_BUFFER_ARB;
836 *a++ = WGL_RED_BITS_ARB;
838 *a++ = WGL_GREEN_BITS_ARB;
840 *a++ = WGL_BLUE_BITS_ARB;
842 *a++ = WGL_ALPHA_BITS_ARB;
844 *a++ = WGL_DEPTH_BITS_ARB;
846 *a++ = WGL_STENCIL_BITS_ARB;
851 *a++ = WGL_RED_BITS_ARB;
853 *a++ = WGL_GREEN_BITS_ARB;
855 *a++ = WGL_BLUE_BITS_ARB;
857 *a++ = WGL_DEPTH_BITS_ARB;
863 *a++ = WGL_STEREO_ARB;
869 *a++ = WGL_SAMPLE_BUFFERS_ARB;
871 *a++ = WGL_SAMPLES_ARB;
878 gldrivername = "opengl32.dll";
879 // 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
880 i = COM_CheckParm("-gl_driver");
881 if (i && i < com_argc - 1)
882 gldrivername = com_argv[i + 1];
883 if (!GL_OpenLibrary(gldrivername))
885 Con_Printf("Unable to load GL driver %s\n", gldrivername);
889 memset(&gdevmode, 0, sizeof(gdevmode));
891 vid_isfullscreen = false;
894 if(vid_desktopfullscreen.integer)
897 gdevmode = initialdevmode;
898 width = mode->width = gdevmode.dmPelsWidth;
899 height = mode->height = gdevmode.dmPelsHeight;
900 bpp = mode->bitsperpixel = gdevmode.dmBitsPerPel;
902 else if(vid_forcerefreshrate.integer)
905 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
906 gdevmode.dmBitsPerPel = bpp;
907 gdevmode.dmPelsWidth = width;
908 gdevmode.dmPelsHeight = height;
909 gdevmode.dmSize = sizeof (gdevmode);
912 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
913 gdevmode.dmDisplayFrequency = refreshrate;
919 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
922 foundgoodmode = false;
924 thismode.dmSize = sizeof(thismode);
925 thismode.dmDriverExtra = 0;
926 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
928 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
930 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
933 if(developer_extra.integer)
934 Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
935 if(thismode.dmBitsPerPel != (DWORD)bpp)
937 if(developer_extra.integer)
938 Con_DPrintf("wrong bpp\n");
941 if(thismode.dmPelsWidth != (DWORD)width)
943 if(developer_extra.integer)
944 Con_DPrintf("wrong width\n");
947 if(thismode.dmPelsHeight != (DWORD)height)
949 if(developer_extra.integer)
950 Con_DPrintf("wrong height\n");
956 // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
957 if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
959 if(developer_extra.integer)
960 Con_DPrintf("too high refresh rate\n");
963 else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
965 if(developer_extra.integer)
966 Con_DPrintf("doesn't beat previous best match (too low)\n");
972 // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
973 if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
975 if(developer_extra.integer)
976 Con_DPrintf("doesn't beat previous best match (too high)\n");
980 // otherwise, take anything
982 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
983 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
984 foundgoodmode = true;
987 if(developer_extra.integer)
988 Con_DPrintf("(out of range)\n");
991 if(developer_extra.integer)
992 Con_DPrintf("accepted\n");
999 Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1002 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1005 Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1009 vid_isfullscreen = true;
1010 WindowStyle = WS_POPUP;
1011 ExWindowStyle = WS_EX_TOPMOST;
1016 i = GetDeviceCaps(hdc, RASTERCAPS);
1017 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1018 ReleaseDC (NULL, hdc);
1022 Con_Print("Can't run in non-RGB mode\n");
1028 Con_Print("A higher desktop depth is required to run this video mode\n");
1032 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1036 AdjustWindowBounds(fullscreen, &width, &height, mode, WindowStyle, &rect);
1040 // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1041 for (windowpass = samples == 1;windowpass < 2;windowpass++)
1044 gl_platformextensions = "";
1046 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1049 Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %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), (void *)NULL, (void *)NULL, (void *)global_hInstance, (void *)NULL);
1054 baseDC = GetDC(mainwindow);
1056 if (!newpixelformat)
1057 newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1058 pixelformat = newpixelformat;
1062 Con_Printf("ChoosePixelFormat(%p, %p) failed\n", (void *)baseDC, (void *)&pfd);
1066 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1069 Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", (void *)baseDC, pixelformat, (void *)&pfd);
1073 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1076 Con_Print("wgl functions not found\n");
1080 baseRC = qwglCreateContext(baseDC);
1084 Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1087 if (!qwglMakeCurrent(baseDC, baseRC))
1090 Con_Printf("wglMakeCurrent(%p, %p) failed\n", (void *)baseDC, (void *)baseRC);
1094 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1097 Con_Print("glGetString not found\n");
1100 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1101 Con_Print("wglGetExtensionsStringARB not found\n");
1103 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1104 gl_platform = "WGL";
1105 gl_platformextensions = "";
1107 if (qwglGetExtensionsStringARB)
1108 gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1112 if (!gl_platformextensions)
1113 gl_platformextensions = "";
1115 // now some nice Windows pain:
1116 // we have created a window, we needed one to find out if there are
1117 // any multisample pixel formats available, the problem is that to
1118 // actually use one of those multisample formats we now have to
1119 // recreate the window (yes Microsoft OpenGL really is that bad)
1121 if (windowpass == 0)
1123 if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1125 // ok we got one - do it all over again with newpixelformat
1126 qwglMakeCurrent(NULL, NULL);
1127 qwglDeleteContext(baseRC);baseRC = 0;
1128 ReleaseDC(mainwindow, baseDC);baseDC = 0;
1129 // eat up any messages waiting for us
1130 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1132 TranslateMessage (&msg);
1133 DispatchMessage (&msg);
1140 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1143 ShowWindow (mainwindow, SW_SHOWDEFAULT);
1144 UpdateWindow (mainwindow);
1146 // now we try to make sure we get the focus on the mode switch, because
1147 // sometimes in some systems we don't. We grab the foreground, then
1148 // finish setting up, pump all our messages, and sleep for a little while
1149 // to let messages finish bouncing around the system, then we put
1150 // ourselves at the top of the z order, then grab the foreground again,
1151 // Who knows if it helps, but it probably doesn't hurt
1152 SetForegroundWindow (mainwindow);
1154 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1156 TranslateMessage (&msg);
1157 DispatchMessage (&msg);
1162 SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1164 SetForegroundWindow (mainwindow);
1166 // fix the leftover Alt from any Alt-Tab or the like that switched us away
1169 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1170 GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1174 //vid_menudrawfn = VID_MenuDraw;
1175 //vid_menukeyfn = VID_MenuKey;
1176 vid_usingmouse = false;
1177 vid_usinghidecursor = false;
1178 vid_usingvsync = false;
1179 vid_reallyhidden = vid_hidden = false;
1180 vid_initialized = true;
1184 if (qwglSwapIntervalEXT)
1186 vid_usevsync = vid_vsync.integer != 0;
1187 vid_usingvsync = vid_vsync.integer != 0;
1188 qwglSwapIntervalEXT (vid_usevsync);
1194 static void AdjustWindowBounds(int fullscreen, int *width, int *height, viddef_mode_t *mode, DWORD WindowStyle, RECT *rect)
1196 int CenterX, CenterY;
1200 rect->right = *width;
1201 rect->bottom = *height;
1202 AdjustWindowRectEx(rect, WindowStyle, false, 0);
1212 SystemParametersInfo(SPI_GETWORKAREA, NULL, &workArea, 0);
1213 int workWidth = workArea.right - workArea.left;
1214 int workHeight = workArea.bottom - workArea.top;
1216 // if height/width matches physical screen height/width, adjust it to available desktop size
1217 // and allow 2 pixels on top for the title bar so the window can be moved
1218 const int titleBarPixels = 2;
1219 if (*width == GetSystemMetrics(SM_CXSCREEN) && (*height == GetSystemMetrics(SM_CYSCREEN) || *height == workHeight - titleBarPixels))
1221 rect->right -= *width - workWidth;
1222 *width = mode->width = workWidth;
1223 rect->bottom -= *height - (workHeight - titleBarPixels);
1224 *height = mode->height = workHeight - titleBarPixels;
1226 CenterY = titleBarPixels;
1230 CenterX = max(0, (workWidth - *width) / 2);
1231 CenterY = max(0, (workHeight - *height) / 2);
1235 // x and y may be changed by WM_MOVE messages
1238 rect->left += CenterX;
1239 rect->right += CenterX;
1240 rect->top += CenterY;
1241 rect->bottom += CenterY;
1244 qboolean VID_InitMode(viddef_mode_t *mode)
1246 return VID_InitModeGL(mode);
1250 static void IN_Shutdown(void);
1251 void VID_Shutdown (void)
1254 if(vid_initialized == false)
1257 VID_EnableJoystick(false);
1258 VID_SetMouse(false, false, false);
1260 vid_initialized = false;
1261 isgl = gldll != NULL;
1266 gl_platformextensions = "";
1267 if (qwglMakeCurrent)
1268 qwglMakeCurrent(NULL, NULL);
1269 qwglMakeCurrent = NULL;
1270 if (baseRC && qwglDeleteContext)
1271 qwglDeleteContext(baseRC);
1272 qwglDeleteContext = NULL;
1273 // close the library before we get rid of the window
1275 if (baseDC && mainwindow)
1276 ReleaseDC(mainwindow, baseDC);
1278 AppActivate(false, false);
1280 DestroyWindow(mainwindow);
1282 if (vid_isfullscreen && isgl)
1283 ChangeDisplaySettings (NULL, CDS_FULLSCREEN);
1284 vid_isfullscreen = false;
1287 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1289 static qboolean restore_spi;
1290 static int originalmouseparms[3];
1292 if (!mouseinitialized)
1297 if (!vid_usingmouse)
1299 vid_usingmouse = true;
1300 cl_ignoremousemoves = 2;
1301 #ifdef SUPPORTDIRECTX
1302 if (dinput && g_pMouse)
1304 IDirectInputDevice_Acquire(g_pMouse);
1305 dinput_acquired = true;
1311 window_rect.left = window_x;
1312 window_rect.top = window_y;
1313 window_rect.right = window_x + vid.width;
1314 window_rect.bottom = window_y + vid.height;
1316 // change mouse settings to turn off acceleration
1317 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1318 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1320 int newmouseparms[3];
1321 newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1322 newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1323 newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1324 restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1327 restore_spi = false;
1328 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1330 SetCapture (mainwindow);
1331 ClipCursor (&window_rect);
1339 vid_usingmouse = false;
1340 cl_ignoremousemoves = 2;
1341 #ifdef SUPPORTDIRECTX
1342 if (dinput_acquired)
1344 IDirectInputDevice_Unacquire(g_pMouse);
1345 dinput_acquired = false;
1350 // restore system mouseparms if we changed them
1352 SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
1353 restore_spi = false;
1360 if (vid_usinghidecursor != hidecursor)
1362 vid_usinghidecursor = hidecursor;
1363 ShowCursor (!hidecursor);
1367 void VID_BuildJoyState(vid_joystate_t *joystate)
1369 VID_Shared_BuildJoyState_Begin(joystate);
1370 VID_Shared_BuildJoyState_Finish(joystate);
1373 void VID_EnableJoystick(qboolean enable)
1375 int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1376 qboolean success = false;
1377 int sharedcount = 0;
1378 sharedcount = VID_Shared_SetJoystick(index);
1379 if (index >= 0 && index < sharedcount)
1382 // update cvar containing count of XInput joysticks
1383 if (joy_detected.integer != sharedcount)
1384 Cvar_SetValueQuick(&joy_detected, sharedcount);
1386 if (joy_active.integer != (success ? 1 : 0))
1387 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1390 #ifdef SUPPORTDIRECTX
1396 static qboolean IN_InitDInput (void)
1399 DIPROPDWORD dipdw = {
1401 sizeof(DIPROPDWORD), // diph.dwSize
1402 sizeof(DIPROPHEADER), // diph.dwHeaderSize
1404 DIPH_DEVICE, // diph.dwHow
1406 DINPUT_BUFFERSIZE, // dwData
1411 hInstDI = LoadLibrary("dinput.dll");
1413 if (hInstDI == NULL)
1415 Con_Print("Couldn't load dinput.dll\n");
1420 if (!pDirectInputCreate)
1422 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
1424 if (!pDirectInputCreate)
1426 Con_Print("Couldn't get DI proc addr\n");
1431 // register with DirectInput and get an IDirectInput to play with.
1432 hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
1439 // obtain an interface to the system mouse device.
1441 hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
1443 hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
1448 Con_Print("Couldn't open DI mouse device\n");
1452 // set the data format to "mouse format".
1453 hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
1457 Con_Print("Couldn't set DI mouse format\n");
1461 // set the cooperativity level.
1462 hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
1463 DISCL_EXCLUSIVE | DISCL_FOREGROUND);
1467 Con_Print("Couldn't set DI coop level\n");
1472 // set the buffer size to DINPUT_BUFFERSIZE elements.
1473 // the buffer size is a DWORD property associated with the device
1474 hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
1478 Con_Print("Couldn't set DI buffersize\n");
1492 static void IN_StartupMouse (void)
1494 if (COM_CheckParm ("-nomouse"))
1497 mouseinitialized = true;
1499 #ifdef SUPPORTDIRECTX
1500 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse input
1501 if (COM_CheckParm ("-dinput"))
1502 dinput = IN_InitDInput ();
1505 Con_Print("DirectInput initialized\n");
1507 Con_Print("DirectInput not initialized\n");
1519 static void IN_MouseMove (void)
1523 GetCursorPos (¤t_pos);
1524 in_windowmouse_x = current_pos.x - window_x;
1525 in_windowmouse_y = current_pos.y - window_y;
1527 if (!vid_usingmouse)
1530 #ifdef SUPPORTDIRECTX
1531 if (dinput_acquired)
1534 DIDEVICEOBJECTDATA od;
1542 hr = IDirectInputDevice_GetDeviceData(g_pMouse,
1543 sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
1545 if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
1547 IDirectInputDevice_Acquire(g_pMouse);
1551 /* Unable to read data or no data available */
1552 if (FAILED(hr) || dwElements == 0)
1555 /* Look at the element to see what happened */
1557 if ((int)od.dwOfs == DIMOFS_X)
1558 in_mouse_x += (LONG) od.dwData;
1559 if ((int)od.dwOfs == DIMOFS_Y)
1560 in_mouse_y += (LONG) od.dwData;
1561 if ((int)od.dwOfs == DIMOFS_Z)
1563 if((LONG)od.dwData < 0)
1565 Key_Event(K_MWHEELDOWN, 0, true);
1566 Key_Event(K_MWHEELDOWN, 0, false);
1568 else if((LONG)od.dwData > 0)
1570 Key_Event(K_MWHEELUP, 0, true);
1571 Key_Event(K_MWHEELUP, 0, false);
1574 if ((int)od.dwOfs == DIMOFS_BUTTON0)
1575 mstate_di = (mstate_di & ~1) | ((od.dwData & 0x80) >> 7);
1576 if ((int)od.dwOfs == DIMOFS_BUTTON1)
1577 mstate_di = (mstate_di & ~2) | ((od.dwData & 0x80) >> 6);
1578 if ((int)od.dwOfs == DIMOFS_BUTTON2)
1579 mstate_di = (mstate_di & ~4) | ((od.dwData & 0x80) >> 5);
1580 if ((int)od.dwOfs == DIMOFS_BUTTON3)
1581 mstate_di = (mstate_di & ~8) | ((od.dwData & 0x80) >> 4);
1584 // perform button actions
1585 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
1586 if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
1587 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
1588 mouse_oldbuttonstate = mstate_di;
1593 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
1594 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
1596 // if the mouse has moved, force it to the center, so there's room to move
1597 if (in_mouse_x || in_mouse_y)
1598 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1610 vid_joystate_t joystate;
1611 if (vid_activewindow && !vid_reallyhidden)
1613 VID_EnableJoystick(true);
1614 VID_BuildJoyState(&joystate);
1615 VID_ApplyJoyState(&joystate);
1619 static void IN_Init(void)
1621 uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
1622 Cvar_RegisterVariable (&vid_forcerefreshrate);
1625 static void IN_Shutdown(void)
1627 #ifdef SUPPORTDIRECTX
1629 IDirectInputDevice_Release(g_pMouse);
1633 IDirectInput_Release(g_pdi);
1638 vid_mode_t *VID_GetDesktopMode(void)
1640 return &desktop_mode;
1643 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1649 thismode.dmSize = sizeof(thismode);
1650 thismode.dmDriverExtra = 0;
1652 for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1654 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1656 Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1661 modes[k].width = thismode.dmPelsWidth;
1662 modes[k].height = thismode.dmPelsHeight;
1663 modes[k].bpp = thismode.dmBitsPerPel;
1664 modes[k].refreshrate = thismode.dmDisplayFrequency;
1665 modes[k].pixelheight_num = 1;
1666 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)