]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_wgl.c
Always pass CDS_FULLSCREEN to ChangeDisplaySettings, fixes #1797.
[xonotic/darkplaces.git] / vid_wgl.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // vid_wgl.c -- NT GL vid component
21
22 #ifdef _MSC_VER
23 #pragma comment(lib, "comctl32.lib")
24 #endif
25
26 #ifdef SUPPORTDIRECTX
27 // Include DX libs
28 #ifdef _MSC_VER
29 #pragma comment(lib, "dinput8.lib")
30 #pragma comment(lib, "dxguid.lib")
31 #endif
32 #ifndef DIRECTINPUT_VERSION
33 #       define DIRECTINPUT_VERSION 0x0500  /* Version 5.0 */
34 #endif
35 #endif
36
37 #include "quakedef.h"
38 #include <windows.h>
39 #include <mmsystem.h>
40 #ifdef SUPPORTDIRECTX
41 #include <dsound.h>
42 #endif
43 #include "resource.h"
44 #include <commctrl.h>
45 #ifdef SUPPORTDIRECTX
46 #include <dinput.h>
47 #endif
48 #include "dpsoftrast.h"
49
50 #ifdef SUPPORTD3D
51 #include <d3d9.h>
52
53 cvar_t vid_dx9 = {CVAR_SAVE, "vid_dx9", "0", "use Microsoft Direct3D9(r) for rendering"};
54 cvar_t vid_dx9_hal = {CVAR_SAVE, "vid_dx9_hal", "1", "enables hardware rendering (1), otherwise software reference rasterizer (0 - very slow), note that 0 is necessary when using NVPerfHUD (which renders in hardware but requires this option to enable it)"};
55 cvar_t vid_dx9_softvertex = {CVAR_SAVE, "vid_dx9_softvertex", "0", "enables software vertex processing (for compatibility testing?  or if you have a very fast CPU), usually you want this off"};
56 cvar_t vid_dx9_triplebuffer = {CVAR_SAVE, "vid_dx9_triplebuffer", "0", "enables triple buffering when using vid_vsync in fullscreen, this options adds some latency and only helps when framerate is below 60 so you usually don't want it"};
57 //cvar_t vid_dx10 = {CVAR_SAVE, "vid_dx10", "1", "use Microsoft Direct3D10(r) for rendering"};
58 //cvar_t vid_dx11 = {CVAR_SAVE, "vid_dx11", "1", "use Microsoft Direct3D11(r) for rendering"};
59
60 D3DPRESENT_PARAMETERS vid_d3dpresentparameters;
61
62 // we declare this in vid_shared.c because it is required by dedicated server and all clients when SUPPORTD3D is defined
63 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
64
65 LPDIRECT3D9 vid_d3d9;
66 D3DCAPS9 vid_d3d9caps;
67 qboolean vid_d3ddevicelost;
68 #endif
69
70 extern HINSTANCE global_hInstance;
71
72 static HINSTANCE gldll;
73
74 #ifndef WM_MOUSEWHEEL
75 #define WM_MOUSEWHEEL                   0x020A
76 #endif
77
78 // Tell startup code that we have a client
79 int cl_available = true;
80
81 qboolean vid_supportrefreshrate = true;
82
83 static int (WINAPI *qwglChoosePixelFormat)(HDC, CONST PIXELFORMATDESCRIPTOR *);
84 static int (WINAPI *qwglDescribePixelFormat)(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
85 //static int (WINAPI *qwglGetPixelFormat)(HDC);
86 static BOOL (WINAPI *qwglSetPixelFormat)(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
87 static BOOL (WINAPI *qwglSwapBuffers)(HDC);
88 static HGLRC (WINAPI *qwglCreateContext)(HDC);
89 static BOOL (WINAPI *qwglDeleteContext)(HGLRC);
90 static HGLRC (WINAPI *qwglGetCurrentContext)(VOID);
91 static HDC (WINAPI *qwglGetCurrentDC)(VOID);
92 static PROC (WINAPI *qwglGetProcAddress)(LPCSTR);
93 static BOOL (WINAPI *qwglMakeCurrent)(HDC, HGLRC);
94 static BOOL (WINAPI *qwglSwapIntervalEXT)(int interval);
95 static const char *(WINAPI *qwglGetExtensionsStringARB)(HDC hdc);
96 static BOOL (WINAPI *qwglChoosePixelFormatARB)(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
97 static BOOL (WINAPI *qwglGetPixelFormatAttribivARB)(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
98
99 static dllfunction_t wglfuncs[] =
100 {
101         {"wglChoosePixelFormat", (void **) &qwglChoosePixelFormat},
102         {"wglDescribePixelFormat", (void **) &qwglDescribePixelFormat},
103 //      {"wglGetPixelFormat", (void **) &qwglGetPixelFormat},
104         {"wglSetPixelFormat", (void **) &qwglSetPixelFormat},
105         {"wglSwapBuffers", (void **) &qwglSwapBuffers},
106         {"wglCreateContext", (void **) &qwglCreateContext},
107         {"wglDeleteContext", (void **) &qwglDeleteContext},
108         {"wglGetProcAddress", (void **) &qwglGetProcAddress},
109         {"wglMakeCurrent", (void **) &qwglMakeCurrent},
110         {"wglGetCurrentContext", (void **) &qwglGetCurrentContext},
111         {"wglGetCurrentDC", (void **) &qwglGetCurrentDC},
112         {NULL, NULL}
113 };
114
115 static dllfunction_t wglswapintervalfuncs[] =
116 {
117         {"wglSwapIntervalEXT", (void **) &qwglSwapIntervalEXT},
118         {NULL, NULL}
119 };
120
121 static dllfunction_t wglpixelformatfuncs[] =
122 {
123         {"wglChoosePixelFormatARB", (void **) &qwglChoosePixelFormatARB},
124         {"wglGetPixelFormatAttribivARB", (void **) &qwglGetPixelFormatAttribivARB},
125         {NULL, NULL}
126 };
127
128 static DEVMODE gdevmode, initialdevmode;
129 static vid_mode_t desktop_mode;
130 static qboolean vid_initialized = false;
131 static qboolean vid_wassuspended = false;
132 static qboolean vid_usingmouse = false;
133 static qboolean vid_usinghidecursor = false;
134 static qboolean vid_usingvsync = false;
135 static qboolean vid_usevsync = false;
136 static HICON hIcon;
137
138 // used by cd_win.c and snd_win.c
139 HWND mainwindow;
140
141 static HDC       baseDC;
142 static HGLRC baseRC;
143
144 static HDC vid_softhdc;
145 static HGDIOBJ vid_softhdc_backup;
146 static BITMAPINFO vid_softbmi;
147 static HBITMAP vid_softdibhandle;
148
149 //HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
150
151 static qboolean vid_isfullscreen;
152
153 //void VID_MenuDraw (void);
154 //void VID_MenuKey (int key);
155
156 //LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
157 //void AppActivate(BOOL fActive, BOOL minimize);
158 //void ClearAllStates (void);
159 //void VID_UpdateWindowStatus (void);
160
161 //====================================
162
163 static int window_x, window_y;
164
165 static qboolean mouseinitialized;
166
167 #ifdef SUPPORTDIRECTX
168 static qboolean dinput;
169 #define DINPUT_BUFFERSIZE           16
170 #define iDirectInputCreate(a,b,c,d)     pDirectInputCreate(a,b,c,d)
171
172 static HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter);
173 #endif
174
175 // LordHavoc: thanks to backslash for this support for mouse buttons 4 and 5
176 /* backslash :: imouse explorer buttons */
177 /* These are #ifdefed out for non-Win2K in the February 2001 version of
178    MS's platform SDK, but we need them for compilation. . . */
179 #ifndef WM_XBUTTONDOWN
180    #define WM_XBUTTONDOWN      0x020B
181    #define WM_XBUTTONUP      0x020C
182 #endif
183 #ifndef MK_XBUTTON1
184    #define MK_XBUTTON1         0x0020
185    #define MK_XBUTTON2         0x0040
186 #endif
187 #ifndef MK_XBUTTON3
188 // LordHavoc: lets hope this allows more buttons in the future...
189    #define MK_XBUTTON3         0x0080
190    #define MK_XBUTTON4         0x0100
191    #define MK_XBUTTON5         0x0200
192    #define MK_XBUTTON6         0x0400
193    #define MK_XBUTTON7         0x0800
194 #endif
195 /* :: backslash */
196
197 // mouse variables
198 static int                      mouse_buttons;
199 static int                      mouse_oldbuttonstate;
200
201 static unsigned int uiWheelMessage;
202 #ifdef SUPPORTDIRECTX
203 static qboolean dinput_acquired;
204
205 static unsigned int             mstate_di;
206 #endif
207
208 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"};
209
210 #ifdef SUPPORTDIRECTX
211 static LPDIRECTINPUT            g_pdi;
212 static LPDIRECTINPUTDEVICE      g_pMouse;
213 static HINSTANCE hInstDI;
214 #endif
215
216 // forward-referenced functions
217 static void IN_StartupMouse (void);
218
219
220 //====================================
221
222 qboolean vid_reallyhidden = true;
223 #ifdef SUPPORTD3D
224 qboolean vid_begunscene = false;
225 #endif
226 void VID_Finish (void)
227 {
228 #ifdef SUPPORTD3D
229         HRESULT hr;
230 #endif
231         vid_hidden = vid_reallyhidden;
232
233         vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
234
235         if (!vid_hidden)
236         {
237                 switch(vid.renderpath)
238                 {
239                 case RENDERPATH_GL11:
240                 case RENDERPATH_GL13:
241                 case RENDERPATH_GL20:
242                 case RENDERPATH_GLES1:
243                 case RENDERPATH_GLES2:
244                         if (vid_usingvsync != vid_usevsync)
245                         {
246                                 vid_usingvsync = vid_usevsync;
247                                 qwglSwapIntervalEXT (vid_usevsync);
248                         }
249                         if (r_speeds.integer == 2 || gl_finish.integer)
250                                 GL_Finish();
251                         SwapBuffers(baseDC);
252                         break;
253                 case RENDERPATH_D3D9:
254 #ifdef SUPPORTD3D
255                         if (vid_begunscene)
256                         {
257                                 IDirect3DDevice9_EndScene(vid_d3d9dev);
258                                 vid_begunscene = false;
259                         }
260                         if (!vid_reallyhidden)
261                         {
262                                 if (!vid_d3ddevicelost)
263                                 {
264                                         vid_hidden = vid_reallyhidden;
265                                         hr = IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
266                                         if (hr == D3DERR_DEVICELOST)
267                                         {
268                                                 vid_d3ddevicelost = true;
269                                                 vid_hidden = true;
270                                                 Sleep(100);
271                                         }
272                                 }
273                                 else
274                                 {
275                                         hr = IDirect3DDevice9_TestCooperativeLevel(vid_d3d9dev);
276                                         switch(hr)
277                                         {
278                                         case D3DERR_DEVICELOST:
279                                                 vid_d3ddevicelost = true;
280                                                 vid_hidden = true;
281                                                 Sleep(100);
282                                                 break;
283                                         case D3DERR_DEVICENOTRESET:
284                                                 vid_d3ddevicelost = false;
285                                                 vid_hidden = vid_reallyhidden;
286                                                 R_Modules_DeviceLost();
287                                                 IDirect3DDevice9_Reset(vid_d3d9dev, &vid_d3dpresentparameters);
288                                                 R_Modules_DeviceRestored();
289                                                 break;
290                                         case D3D_OK:
291                                                 vid_hidden = vid_reallyhidden;
292                                                 IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
293                                                 break;
294                                         }
295                                 }
296                                 if (!vid_begunscene && !vid_hidden)
297                                 {
298                                         IDirect3DDevice9_BeginScene(vid_d3d9dev);
299                                         vid_begunscene = true;
300                                 }
301                         }
302 #endif
303                         break;
304                 case RENDERPATH_D3D10:
305                         break;
306                 case RENDERPATH_D3D11:
307                         break;
308                 case RENDERPATH_SOFT:
309                         DPSOFTRAST_Finish();
310 //                      baseDC = GetDC(mainwindow);
311                         BitBlt(baseDC, 0, 0, vid.width, vid.height, vid_softhdc, 0, 0, SRCCOPY);
312 //                      ReleaseDC(mainwindow, baseDC);
313 //                      baseDC = NULL;
314                         break;
315                 }
316         }
317
318         // make sure a context switch can happen every frame - Logitech drivers
319         // input drivers sometimes eat cpu time every 3 seconds or lag badly
320         // without this help
321         Sleep(0);
322
323         VID_UpdateGamma(false, 256);
324 }
325
326 //==========================================================================
327
328
329
330
331 static unsigned char scantokey[128] =
332 {
333 //  0           1       2    3     4     5       6       7      8         9      A          B           C       D           E           F
334         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'       ,'0'        ,'-'   ,'='         ,K_BACKSPACE,9    ,//0
335         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['       ,']'        ,13    ,K_CTRL      ,'a'        ,'s'  ,//1
336         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT   ,'\\'       ,'z'   ,'x'         ,'c'        ,'v'  ,//2
337         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0         ,K_F1       ,K_F2  ,K_F3        ,K_F4       ,K_F5 ,//3
338         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
339         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//5
340         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0    ,//6
341         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0         ,0          ,0     ,0           ,0          ,0     //7
342 };
343
344
345 /*
346 =======
347 MapKey
348
349 Map from windows to quake keynums
350 =======
351 */
352 static int MapKey (int key, int virtualkey)
353 {
354         int result;
355         int modified = (key >> 16) & 255;
356         qboolean is_extended = false;
357
358         if (modified < 128 && scantokey[modified])
359                 result = scantokey[modified];
360         else
361         {
362                 result = 0;
363                 Con_DPrintf("key 0x%02x (0x%8x, 0x%8x) has no translation\n", modified, key, virtualkey);
364         }
365
366         if (key & (1 << 24))
367                 is_extended = true;
368
369         if ( !is_extended )
370         {
371                 switch ( result )
372                 {
373                 case K_HOME:
374                         return K_KP_HOME;
375                 case K_UPARROW:
376                         return K_KP_UPARROW;
377                 case K_PGUP:
378                         return K_KP_PGUP;
379                 case K_LEFTARROW:
380                         return K_KP_LEFTARROW;
381                 case K_RIGHTARROW:
382                         return K_KP_RIGHTARROW;
383                 case K_END:
384                         return K_KP_END;
385                 case K_DOWNARROW:
386                         return K_KP_DOWNARROW;
387                 case K_PGDN:
388                         return K_KP_PGDN;
389                 case K_INS:
390                         return K_KP_INS;
391                 case K_DEL:
392                         return K_KP_DEL;
393                 default:
394                         return result;
395                 }
396         }
397         else
398         {
399                 switch ( result )
400                 {
401                 case 0x0D:
402                         return K_KP_ENTER;
403                 case 0x2F:
404                         return K_KP_SLASH;
405                 case 0xAF:
406                         return K_KP_PLUS;
407                 }
408                 return result;
409         }
410 }
411
412 /*
413 ===================================================================
414
415 MAIN WINDOW
416
417 ===================================================================
418 */
419
420 /*
421 ================
422 ClearAllStates
423 ================
424 */
425 static void ClearAllStates (void)
426 {
427         Key_ClearStates ();
428         if (vid_usingmouse)
429                 mouse_oldbuttonstate = 0;
430 }
431
432 void AppActivate(BOOL fActive, BOOL minimize)
433 /****************************************************************************
434 *
435 * Function:     AppActivate
436 * Parameters:   fActive - True if app is activating
437 *
438 * Description:  If the application is activating, then swap the system
439 *               into SYSPAL_NOSTATIC mode so that our palettes will display
440 *               correctly.
441 *
442 ****************************************************************************/
443 {
444         static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
445
446         vid_activewindow = fActive != FALSE;
447         vid_reallyhidden = minimize != FALSE;
448
449         // enable/disable sound on focus gain/loss
450         if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
451         {
452                 if (!sound_active)
453                 {
454                         S_UnblockSound ();
455                         sound_active = true;
456                 }
457         }
458         else
459         {
460                 if (sound_active)
461                 {
462                         S_BlockSound ();
463                         sound_active = false;
464                 }
465         }
466
467         if (fActive)
468         {
469                 if (vid_isfullscreen)
470                 {
471                         if (vid_wassuspended)
472                         {
473                                 vid_wassuspended = false;
474                                 if (gldll)
475                                 {
476                                         ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
477                                         ShowWindow(mainwindow, SW_SHOWNORMAL);
478                                 }
479                         }
480
481                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
482                         if (gldll)
483                                 MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
484                 }
485         }
486
487         if (!fActive)
488         {
489                 VID_SetMouse(false, false, false);
490                 if (vid_isfullscreen)
491                 {
492                         if (gldll)
493                                 ChangeDisplaySettings (NULL, CDS_FULLSCREEN);
494                         vid_wassuspended = true;
495                 }
496                 VID_RestoreSystemGamma();
497         }
498 }
499
500 //TODO: move it around in vid_wgl.c since I dont think this is the right position
501 void Sys_SendKeyEvents (void)
502 {
503         MSG msg;
504
505         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
506         {
507                 if (!GetMessage (&msg, NULL, 0, 0))
508                         Sys_Quit (1);
509
510                 TranslateMessage (&msg);
511                 DispatchMessage (&msg);
512         }
513 }
514
515 #ifdef CONFIG_CD
516 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
517 #endif
518
519 static keynum_t buttonremap[16] =
520 {
521         K_MOUSE1,
522         K_MOUSE2,
523         K_MOUSE3,
524         K_MOUSE4,
525         K_MOUSE5,
526         K_MOUSE6,
527         K_MOUSE7,
528         K_MOUSE8,
529         K_MOUSE9,
530         K_MOUSE10,
531         K_MOUSE11,
532         K_MOUSE12,
533         K_MOUSE13,
534         K_MOUSE14,
535         K_MOUSE15,
536         K_MOUSE16,
537 };
538
539 /* main window procedure */
540 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
541 {
542         LONG    lRet = 1;
543         int             fActive, fMinimized, temp;
544         unsigned char state[256];
545         unsigned char asciichar[4];
546         int             vkey;
547         int             charlength;
548         qboolean down = false;
549
550         if ( uMsg == uiWheelMessage )
551                 uMsg = WM_MOUSEWHEEL;
552
553         switch (uMsg)
554         {
555                 case WM_KILLFOCUS:
556                         if (vid_isfullscreen)
557                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
558                         break;
559
560                 case WM_CREATE:
561                         break;
562
563                 case WM_MOVE:
564                         window_x = (int) LOWORD(lParam);
565                         window_y = (int) HIWORD(lParam);
566                         VID_SetMouse(false, false, false);
567                         break;
568
569                 case WM_KEYDOWN:
570                 case WM_SYSKEYDOWN:
571                         down = true;
572                 case WM_KEYUP:
573                 case WM_SYSKEYUP:
574                         vkey = MapKey(lParam, wParam);
575                         GetKeyboardState (state);
576                         // alt/ctrl/shift tend to produce funky ToAscii values,
577                         // and if it's not a single character we don't know care about it
578                         charlength = ToAscii (wParam, lParam >> 16, state, (LPWORD)asciichar, 0);
579                         if (vkey == K_ALT || vkey == K_CTRL || vkey == K_SHIFT || charlength == 0)
580                                 asciichar[0] = 0;
581                         else if( charlength == 2 ) {
582                                 asciichar[0] = asciichar[1];
583                         }
584                         if (!VID_JoyBlockEmulatedKeys(vkey))
585                                 Key_Event (vkey, asciichar[0], down);
586                         break;
587
588                 case WM_SYSCHAR:
589                 // keep Alt-Space from happening
590                         break;
591
592                 case WM_SYSCOMMAND:
593                         // prevent screensaver from occuring while the active window
594                         // note: password-locked screensavers on Vista still work
595                         if (vid_activewindow && ((wParam & 0xFFF0) == SC_SCREENSAVE || (wParam & 0xFFF0) == SC_MONITORPOWER))
596                                 lRet = 0;
597                         else
598                                 lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
599                         break;
600
601         // this is complicated because Win32 seems to pack multiple mouse events into
602         // one update sometimes, so we always check all states and look for events
603                 case WM_LBUTTONDOWN:
604                 case WM_LBUTTONUP:
605                 case WM_RBUTTONDOWN:
606                 case WM_RBUTTONUP:
607                 case WM_MBUTTONDOWN:
608                 case WM_MBUTTONUP:
609                 case WM_XBUTTONDOWN:   // backslash :: imouse explorer buttons
610                 case WM_XBUTTONUP:      // backslash :: imouse explorer buttons
611                 case WM_MOUSEMOVE:
612                         temp = 0;
613
614                         if (wParam & MK_LBUTTON)
615                                 temp |= 1;
616
617                         if (wParam & MK_RBUTTON)
618                                 temp |= 2;
619
620                         if (wParam & MK_MBUTTON)
621                                 temp |= 4;
622
623                         /* backslash :: imouse explorer buttons */
624                         if (wParam & MK_XBUTTON1)
625                                 temp |= 8;
626
627                         if (wParam & MK_XBUTTON2)
628                                 temp |= 16;
629                         /* :: backslash */
630
631                         // LordHavoc: lets hope this allows more buttons in the future...
632                         if (wParam & MK_XBUTTON3)
633                                 temp |= 32;
634                         if (wParam & MK_XBUTTON4)
635                                 temp |= 64;
636                         if (wParam & MK_XBUTTON5)
637                                 temp |= 128;
638                         if (wParam & MK_XBUTTON6)
639                                 temp |= 256;
640                         if (wParam & MK_XBUTTON7)
641                                 temp |= 512;
642
643 #ifdef SUPPORTDIRECTX
644                         if (!dinput_acquired)
645 #endif
646                         {
647                                 // perform button actions
648                                 int i;
649                                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
650                                         if ((temp ^ mouse_oldbuttonstate) & (1<<i))
651                                                 Key_Event (buttonremap[i], 0, (temp & (1<<i)) != 0);
652                                 mouse_oldbuttonstate = temp;
653                         }
654
655                         break;
656
657                 // JACK: This is the mouse wheel with the Intellimouse
658                 // Its delta is either positive or neg, and we generate the proper
659                 // Event.
660                 case WM_MOUSEWHEEL:
661                         if ((short) HIWORD(wParam) > 0) {
662                                 Key_Event(K_MWHEELUP, 0, true);
663                                 Key_Event(K_MWHEELUP, 0, false);
664                         } else {
665                                 Key_Event(K_MWHEELDOWN, 0, true);
666                                 Key_Event(K_MWHEELDOWN, 0, false);
667                         }
668                         break;
669
670                 case WM_SIZE:
671                         break;
672
673                 case WM_CLOSE:
674                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
675                                 Sys_Quit (0);
676
677                         break;
678
679                 case WM_ACTIVATE:
680                         fActive = LOWORD(wParam);
681                         fMinimized = (BOOL) HIWORD(wParam);
682                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
683
684                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
685                         ClearAllStates ();
686
687                         break;
688
689                 //case WM_DESTROY:
690                 //      PostQuitMessage (0);
691                 //      break;
692
693                 case MM_MCINOTIFY:
694 #ifdef CONFIG_CD
695                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
696 #endif
697                         break;
698
699                 default:
700                         /* pass all unhandled messages to DefWindowProc */
701                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
702                 break;
703         }
704
705         /* return 1 if handled message, 0 if not */
706         return lRet;
707 }
708
709 int VID_SetGamma(unsigned short *ramps, int rampsize)
710 {
711         if (qwglMakeCurrent)
712         {
713                 HDC hdc = GetDC (NULL);
714                 int i = SetDeviceGammaRamp(hdc, ramps);
715                 ReleaseDC (NULL, hdc);
716                 return i; // return success or failure
717         }
718         else
719                 return 0;
720 }
721
722 int VID_GetGamma(unsigned short *ramps, int rampsize)
723 {
724         if (qwglMakeCurrent)
725         {
726                 HDC hdc = GetDC (NULL);
727                 int i = GetDeviceGammaRamp(hdc, ramps);
728                 ReleaseDC (NULL, hdc);
729                 return i; // return success or failure
730         }
731         else
732                 return 0;
733 }
734
735 static void GL_CloseLibrary(void)
736 {
737         if (gldll)
738         {
739                 FreeLibrary(gldll);
740                 gldll = 0;
741                 gl_driver[0] = 0;
742                 qwglGetProcAddress = NULL;
743                 gl_extensions = "";
744                 gl_platform = "";
745                 gl_platformextensions = "";
746         }
747 }
748
749 static int GL_OpenLibrary(const char *name)
750 {
751         Con_Printf("Loading OpenGL driver %s\n", name);
752         GL_CloseLibrary();
753         if (!(gldll = LoadLibrary(name)))
754         {
755                 Con_Printf("Unable to LoadLibrary %s\n", name);
756                 return false;
757         }
758         strlcpy(gl_driver, name, sizeof(gl_driver));
759         return true;
760 }
761
762 void *GL_GetProcAddress(const char *name)
763 {
764         if (gldll)
765         {
766                 void *p = NULL;
767                 if (qwglGetProcAddress != NULL)
768                         p = (void *) qwglGetProcAddress(name);
769                 if (p == NULL)
770                         p = (void *) GetProcAddress(gldll, name);
771                 return p;
772         }
773         else
774                 return NULL;
775 }
776
777 #ifndef WGL_ARB_pixel_format
778 #define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
779 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
780 #define WGL_DRAW_TO_BITMAP_ARB         0x2002
781 #define WGL_ACCELERATION_ARB           0x2003
782 #define WGL_NEED_PALETTE_ARB           0x2004
783 #define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
784 #define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
785 #define WGL_SWAP_METHOD_ARB            0x2007
786 #define WGL_NUMBER_OVERLAYS_ARB        0x2008
787 #define WGL_NUMBER_UNDERLAYS_ARB       0x2009
788 #define WGL_TRANSPARENT_ARB            0x200A
789 #define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
790 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
791 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
792 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
793 #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
794 #define WGL_SHARE_DEPTH_ARB            0x200C
795 #define WGL_SHARE_STENCIL_ARB          0x200D
796 #define WGL_SHARE_ACCUM_ARB            0x200E
797 #define WGL_SUPPORT_GDI_ARB            0x200F
798 #define WGL_SUPPORT_OPENGL_ARB         0x2010
799 #define WGL_DOUBLE_BUFFER_ARB          0x2011
800 #define WGL_STEREO_ARB                 0x2012
801 #define WGL_PIXEL_TYPE_ARB             0x2013
802 #define WGL_COLOR_BITS_ARB             0x2014
803 #define WGL_RED_BITS_ARB               0x2015
804 #define WGL_RED_SHIFT_ARB              0x2016
805 #define WGL_GREEN_BITS_ARB             0x2017
806 #define WGL_GREEN_SHIFT_ARB            0x2018
807 #define WGL_BLUE_BITS_ARB              0x2019
808 #define WGL_BLUE_SHIFT_ARB             0x201A
809 #define WGL_ALPHA_BITS_ARB             0x201B
810 #define WGL_ALPHA_SHIFT_ARB            0x201C
811 #define WGL_ACCUM_BITS_ARB             0x201D
812 #define WGL_ACCUM_RED_BITS_ARB         0x201E
813 #define WGL_ACCUM_GREEN_BITS_ARB       0x201F
814 #define WGL_ACCUM_BLUE_BITS_ARB        0x2020
815 #define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
816 #define WGL_DEPTH_BITS_ARB             0x2022
817 #define WGL_STENCIL_BITS_ARB           0x2023
818 #define WGL_AUX_BUFFERS_ARB            0x2024
819 #define WGL_NO_ACCELERATION_ARB        0x2025
820 #define WGL_GENERIC_ACCELERATION_ARB   0x2026
821 #define WGL_FULL_ACCELERATION_ARB      0x2027
822 #define WGL_SWAP_EXCHANGE_ARB          0x2028
823 #define WGL_SWAP_COPY_ARB              0x2029
824 #define WGL_SWAP_UNDEFINED_ARB         0x202A
825 #define WGL_TYPE_RGBA_ARB              0x202B
826 #define WGL_TYPE_COLORINDEX_ARB        0x202C
827 #endif
828
829 #ifndef WGL_ARB_multisample
830 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
831 #define WGL_SAMPLES_ARB                0x2042
832 #endif
833
834
835 static void IN_Init(void);
836 void VID_Init(void)
837 {
838         WNDCLASS wc;
839
840 #ifdef SUPPORTD3D
841         Cvar_RegisterVariable(&vid_dx9);
842         Cvar_RegisterVariable(&vid_dx9_hal);
843         Cvar_RegisterVariable(&vid_dx9_softvertex);
844         Cvar_RegisterVariable(&vid_dx9_triplebuffer);
845 //      Cvar_RegisterVariable(&vid_dx10);
846 //      Cvar_RegisterVariable(&vid_dx11);
847 #endif
848
849         InitCommonControls();
850         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
851
852         // Register the frame class
853         wc.style         = 0;
854         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
855         wc.cbClsExtra    = 0;
856         wc.cbWndExtra    = 0;
857         wc.hInstance     = global_hInstance;
858         wc.hIcon         = hIcon;
859         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
860         wc.hbrBackground = NULL;
861         wc.lpszMenuName  = 0;
862         wc.lpszClassName = "DarkPlacesWindowClass";
863
864         if (!RegisterClass (&wc))
865                 Con_Printf ("Couldn't register window class\n");
866
867         memset(&initialdevmode, 0, sizeof(initialdevmode));
868         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &initialdevmode);
869
870         desktop_mode.width = initialdevmode.dmPelsWidth;
871         desktop_mode.height = initialdevmode.dmPelsHeight;
872         desktop_mode.bpp = initialdevmode.dmBitsPerPel;
873         desktop_mode.refreshrate = initialdevmode.dmDisplayFrequency;
874         desktop_mode.pixelheight_num = 1;
875         desktop_mode.pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
876
877         IN_Init();
878 }
879
880 qboolean VID_InitModeGL(viddef_mode_t *mode)
881 {
882         int i;
883         HDC hdc;
884         RECT rect;
885         MSG msg;
886         PIXELFORMATDESCRIPTOR pfd =
887         {
888                 sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
889                 1,                              // version number
890                 PFD_DRAW_TO_WINDOW              // support window
891                 |  PFD_SUPPORT_OPENGL   // support OpenGL
892                 |  PFD_DOUBLEBUFFER ,   // double buffered
893                 PFD_TYPE_RGBA,                  // RGBA type
894                 24,                             // 24-bit color depth
895                 0, 0, 0, 0, 0, 0,               // color bits ignored
896                 0,                              // no alpha buffer
897                 0,                              // shift bit ignored
898                 0,                              // no accumulation buffer
899                 0, 0, 0, 0,                     // accum bits ignored
900                 32,                             // 32-bit z-buffer
901                 0,                              // no stencil buffer
902                 0,                              // no auxiliary buffer
903                 PFD_MAIN_PLANE,                 // main layer
904                 0,                              // reserved
905                 0, 0, 0                         // layer masks ignored
906         };
907         int windowpass;
908         int pixelformat, newpixelformat;
909         UINT numpixelformats;
910         DWORD WindowStyle, ExWindowStyle;
911         int CenterX, CenterY;
912         const char *gldrivername;
913         int depth;
914         DEVMODE thismode;
915         qboolean foundmode, foundgoodmode;
916         int *a;
917         float *af;
918         int attribs[128];
919         float attribsf[16];
920         int bpp = mode->bitsperpixel;
921         int width = mode->width;
922         int height = mode->height;
923         int refreshrate = (int)floor(mode->refreshrate+0.5);
924         int stereobuffer = mode->stereobuffer;
925         int samples = mode->samples;
926         int fullscreen = mode->fullscreen;
927
928         if (vid_initialized)
929                 Sys_Error("VID_InitMode called when video is already initialised");
930
931         // if stencil is enabled, ask for alpha too
932         if (bpp >= 32)
933         {
934                 pfd.cRedBits = 8;
935                 pfd.cGreenBits = 8;
936                 pfd.cBlueBits = 8;
937                 pfd.cAlphaBits = 8;
938                 pfd.cDepthBits = 24;
939                 pfd.cStencilBits = 8;
940         }
941         else
942         {
943                 pfd.cRedBits = 5;
944                 pfd.cGreenBits = 5;
945                 pfd.cBlueBits = 5;
946                 pfd.cAlphaBits = 0;
947                 pfd.cDepthBits = 16;
948                 pfd.cStencilBits = 0;
949         }
950
951         if (stereobuffer)
952                 pfd.dwFlags |= PFD_STEREO;
953
954         a = attribs;
955         af = attribsf;
956         *a++ = WGL_DRAW_TO_WINDOW_ARB;
957         *a++ = GL_TRUE;
958         *a++ = WGL_ACCELERATION_ARB;
959         *a++ = WGL_FULL_ACCELERATION_ARB;
960         *a++ = WGL_DOUBLE_BUFFER_ARB;
961         *a++ = true;
962
963         if (bpp >= 32)
964         {
965                 *a++ = WGL_RED_BITS_ARB;
966                 *a++ = 8;
967                 *a++ = WGL_GREEN_BITS_ARB;
968                 *a++ = 8;
969                 *a++ = WGL_BLUE_BITS_ARB;
970                 *a++ = 8;
971                 *a++ = WGL_ALPHA_BITS_ARB;
972                 *a++ = 8;
973                 *a++ = WGL_DEPTH_BITS_ARB;
974                 *a++ = 24;
975                 *a++ = WGL_STENCIL_BITS_ARB;
976                 *a++ = 8;
977         }
978         else
979         {
980                 *a++ = WGL_RED_BITS_ARB;
981                 *a++ = 1;
982                 *a++ = WGL_GREEN_BITS_ARB;
983                 *a++ = 1;
984                 *a++ = WGL_BLUE_BITS_ARB;
985                 *a++ = 1;
986                 *a++ = WGL_DEPTH_BITS_ARB;
987                 *a++ = 16;
988         }
989
990         if (stereobuffer)
991         {
992                 *a++ = WGL_STEREO_ARB;
993                 *a++ = GL_TRUE;
994         }
995
996         if (samples > 1)
997         {
998                 *a++ = WGL_SAMPLE_BUFFERS_ARB;
999                 *a++ = 1;
1000                 *a++ = WGL_SAMPLES_ARB;
1001                 *a++ = samples;
1002         }
1003
1004         *a = 0;
1005         *af = 0;
1006
1007         gldrivername = "opengl32.dll";
1008 // 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
1009         i = COM_CheckParm("-gl_driver");
1010         if (i && i < com_argc - 1)
1011                 gldrivername = com_argv[i + 1];
1012         if (!GL_OpenLibrary(gldrivername))
1013         {
1014                 Con_Printf("Unable to load GL driver %s\n", gldrivername);
1015                 return false;
1016         }
1017
1018         memset(&gdevmode, 0, sizeof(gdevmode));
1019
1020         vid_isfullscreen = false;
1021         if (fullscreen)
1022         {
1023                 if(vid_desktopfullscreen.integer)
1024                 {
1025                         foundmode = true;
1026                         gdevmode = initialdevmode;
1027                         width = mode->width = gdevmode.dmPelsWidth;
1028                         height = mode->height = gdevmode.dmPelsHeight;
1029                         bpp = mode->bitsperpixel = gdevmode.dmBitsPerPel;
1030                 }
1031                 else if(vid_forcerefreshrate.integer)
1032                 {
1033                         foundmode = true;
1034                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1035                         gdevmode.dmBitsPerPel = bpp;
1036                         gdevmode.dmPelsWidth = width;
1037                         gdevmode.dmPelsHeight = height;
1038                         gdevmode.dmSize = sizeof (gdevmode);
1039                         if(refreshrate)
1040                         {
1041                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1042                                 gdevmode.dmDisplayFrequency = refreshrate;
1043                         }
1044                 }
1045                 else
1046                 {
1047                         if(refreshrate == 0)
1048                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1049
1050                         foundmode = false;
1051                         foundgoodmode = false;
1052
1053                         thismode.dmSize = sizeof(thismode);
1054                         thismode.dmDriverExtra = 0;
1055                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1056                         {
1057                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1058                                 {
1059                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1060                                         continue;
1061                                 }
1062                                 if(developer_extra.integer)
1063                                         Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1064                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
1065                                 {
1066                                         if(developer_extra.integer)
1067                                                 Con_DPrintf("wrong bpp\n");
1068                                         continue;
1069                                 }
1070                                 if(thismode.dmPelsWidth != (DWORD)width)
1071                                 {
1072                                         if(developer_extra.integer)
1073                                                 Con_DPrintf("wrong width\n");
1074                                         continue;
1075                                 }
1076                                 if(thismode.dmPelsHeight != (DWORD)height)
1077                                 {
1078                                         if(developer_extra.integer)
1079                                                 Con_DPrintf("wrong height\n");
1080                                         continue;
1081                                 }
1082
1083                                 if(foundgoodmode)
1084                                 {
1085                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1086                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1087                                         {
1088                                                 if(developer_extra.integer)
1089                                                         Con_DPrintf("too high refresh rate\n");
1090                                                 continue;
1091                                         }
1092                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1093                                         {
1094                                                 if(developer_extra.integer)
1095                                                         Con_DPrintf("doesn't beat previous best match (too low)\n");
1096                                                 continue;
1097                                         }
1098                                 }
1099                                 else if(foundmode)
1100                                 {
1101                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1102                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1103                                         {
1104                                                 if(developer_extra.integer)
1105                                                         Con_DPrintf("doesn't beat previous best match (too high)\n");
1106                                                 continue;
1107                                         }
1108                                 }
1109                                 // otherwise, take anything
1110
1111                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1112                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1113                                         foundgoodmode = true;
1114                                 else
1115                                 {
1116                                         if(developer_extra.integer)
1117                                                 Con_DPrintf("(out of range)\n");
1118                                 }
1119                                 foundmode = true;
1120                                 if(developer_extra.integer)
1121                                         Con_DPrintf("accepted\n");
1122                         }
1123                 }
1124
1125                 if (!foundmode)
1126                 {
1127                         VID_Shutdown();
1128                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1129                         return false;
1130                 }
1131                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1132                 {
1133                         VID_Shutdown();
1134                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1135                         return false;
1136                 }
1137
1138                 vid_isfullscreen = true;
1139                 WindowStyle = WS_POPUP;
1140                 ExWindowStyle = WS_EX_TOPMOST;
1141         }
1142         else
1143         {
1144                 hdc = GetDC (NULL);
1145                 i = GetDeviceCaps(hdc, RASTERCAPS);
1146                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1147                 ReleaseDC (NULL, hdc);
1148                 if (i & RC_PALETTE)
1149                 {
1150                         VID_Shutdown();
1151                         Con_Print("Can't run in non-RGB mode\n");
1152                         return false;
1153                 }
1154                 if (bpp > depth)
1155                 {
1156                         VID_Shutdown();
1157                         Con_Print("A higher desktop depth is required to run this video mode\n");
1158                         return false;
1159                 }
1160
1161                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1162                 ExWindowStyle = 0;
1163         }
1164
1165         rect.top = 0;
1166         rect.left = 0;
1167         rect.right = width;
1168         rect.bottom = height;
1169         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1170
1171         if (fullscreen)
1172         {
1173                 CenterX = 0;
1174                 CenterY = 0;
1175         }
1176         else
1177         {
1178                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1179                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1180         }
1181         CenterX = max(0, CenterX);
1182         CenterY = max(0, CenterY);
1183
1184         // x and y may be changed by WM_MOVE messages
1185         window_x = CenterX;
1186         window_y = CenterY;
1187         rect.left += CenterX;
1188         rect.right += CenterX;
1189         rect.top += CenterY;
1190         rect.bottom += CenterY;
1191
1192         pixelformat = 0;
1193         newpixelformat = 0;
1194         // start out at the final windowpass if samples is 1 as it's the only feature we need extended pixel formats for
1195         for (windowpass = samples == 1;windowpass < 2;windowpass++)
1196         {
1197                 gl_extensions = "";
1198                 gl_platformextensions = "";
1199
1200                 mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1201                 if (!mainwindow)
1202                 {
1203                         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);
1204                         VID_Shutdown();
1205                         return false;
1206                 }
1207
1208                 baseDC = GetDC(mainwindow);
1209
1210                 if (!newpixelformat)
1211                         newpixelformat = ChoosePixelFormat(baseDC, &pfd);
1212                 pixelformat = newpixelformat;
1213                 if (!pixelformat)
1214                 {
1215                         VID_Shutdown();
1216                         Con_Printf("ChoosePixelFormat(%p, %p) failed\n", (void *)baseDC, (void *)&pfd);
1217                         return false;
1218                 }
1219
1220                 if (SetPixelFormat(baseDC, pixelformat, &pfd) == false)
1221                 {
1222                         VID_Shutdown();
1223                         Con_Printf("SetPixelFormat(%p, %d, %p) failed\n", (void *)baseDC, pixelformat, (void *)&pfd);
1224                         return false;
1225                 }
1226
1227                 if (!GL_CheckExtension("wgl", wglfuncs, NULL, false))
1228                 {
1229                         VID_Shutdown();
1230                         Con_Print("wgl functions not found\n");
1231                         return false;
1232                 }
1233
1234                 baseRC = qwglCreateContext(baseDC);
1235                 if (!baseRC)
1236                 {
1237                         VID_Shutdown();
1238                         Con_Print("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.\n");
1239                         return false;
1240                 }
1241                 if (!qwglMakeCurrent(baseDC, baseRC))
1242                 {
1243                         VID_Shutdown();
1244                         Con_Printf("wglMakeCurrent(%p, %p) failed\n", (void *)baseDC, (void *)baseRC);
1245                         return false;
1246                 }
1247
1248                 if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
1249                 {
1250                         VID_Shutdown();
1251                         Con_Print("glGetString not found\n");
1252                         return false;
1253                 }
1254                 if ((qwglGetExtensionsStringARB = (const char *(WINAPI *)(HDC hdc))GL_GetProcAddress("wglGetExtensionsStringARB")) == NULL)
1255                         Con_Print("wglGetExtensionsStringARB not found\n");
1256
1257                 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
1258                 gl_platform = "WGL";
1259                 gl_platformextensions = "";
1260
1261                 if (qwglGetExtensionsStringARB)
1262                         gl_platformextensions = (const char *)qwglGetExtensionsStringARB(baseDC);
1263
1264                 if (!gl_extensions)
1265                         gl_extensions = "";
1266                 if (!gl_platformextensions)
1267                         gl_platformextensions = "";
1268
1269                 // now some nice Windows pain:
1270                 // we have created a window, we needed one to find out if there are
1271                 // any multisample pixel formats available, the problem is that to
1272                 // actually use one of those multisample formats we now have to
1273                 // recreate the window (yes Microsoft OpenGL really is that bad)
1274
1275                 if (windowpass == 0)
1276                 {
1277                         if (!GL_CheckExtension("WGL_ARB_pixel_format", wglpixelformatfuncs, "-noarbpixelformat", false) || !qwglChoosePixelFormatARB(baseDC, attribs, attribsf, 1, &newpixelformat, &numpixelformats) || !newpixelformat)
1278                                 break;
1279                         // ok we got one - do it all over again with newpixelformat
1280                         qwglMakeCurrent(NULL, NULL);
1281                         qwglDeleteContext(baseRC);baseRC = 0;
1282                         ReleaseDC(mainwindow, baseDC);baseDC = 0;
1283                         // eat up any messages waiting for us
1284                         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1285                         {
1286                                 TranslateMessage (&msg);
1287                                 DispatchMessage (&msg);
1288                         }
1289                 }
1290         }
1291
1292         /*
1293         if (!fullscreen)
1294                 SetWindowPos (mainwindow, NULL, CenterX, CenterY, 0, 0,SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
1295         */
1296
1297         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1298         UpdateWindow (mainwindow);
1299
1300         // now we try to make sure we get the focus on the mode switch, because
1301         // sometimes in some systems we don't.  We grab the foreground, then
1302         // finish setting up, pump all our messages, and sleep for a little while
1303         // to let messages finish bouncing around the system, then we put
1304         // ourselves at the top of the z order, then grab the foreground again,
1305         // Who knows if it helps, but it probably doesn't hurt
1306         SetForegroundWindow (mainwindow);
1307
1308         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1309         {
1310                 TranslateMessage (&msg);
1311                 DispatchMessage (&msg);
1312         }
1313
1314         Sleep (100);
1315
1316         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1317
1318         SetForegroundWindow (mainwindow);
1319
1320         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1321         ClearAllStates ();
1322
1323 // COMMANDLINEOPTION: Windows WGL: -novideosync disables WGL_EXT_swap_control
1324         GL_CheckExtension("WGL_EXT_swap_control", wglswapintervalfuncs, "-novideosync", false);
1325
1326         GL_Init ();
1327
1328         //vid_menudrawfn = VID_MenuDraw;
1329         //vid_menukeyfn = VID_MenuKey;
1330         vid_usingmouse = false;
1331         vid_usinghidecursor = false;
1332         vid_usingvsync = false;
1333         vid_reallyhidden = vid_hidden = false;
1334         vid_initialized = true;
1335
1336         IN_StartupMouse ();
1337
1338         if (qwglSwapIntervalEXT)
1339         {
1340                 vid_usevsync = vid_vsync.integer != 0;
1341                 vid_usingvsync = vid_vsync.integer != 0;
1342                 qwglSwapIntervalEXT (vid_usevsync);
1343         }
1344
1345         return true;
1346 }
1347
1348 #ifdef SUPPORTD3D
1349 static D3DADAPTER_IDENTIFIER9 d3d9adapteridentifier;
1350
1351 extern cvar_t gl_info_extensions;
1352 extern cvar_t gl_info_vendor;
1353 extern cvar_t gl_info_renderer;
1354 extern cvar_t gl_info_version;
1355 extern cvar_t gl_info_platform;
1356 extern cvar_t gl_info_driver;
1357 qboolean VID_InitModeDX(viddef_mode_t *mode, int version)
1358 {
1359         int deviceindex;
1360         RECT rect;
1361         MSG msg;
1362         DWORD WindowStyle, ExWindowStyle;
1363         int CenterX, CenterY;
1364         int bpp = mode->bitsperpixel;
1365         int width = mode->width;
1366         int height = mode->height;
1367         int refreshrate = (int)floor(mode->refreshrate+0.5);
1368 //      int stereobuffer = mode->stereobuffer;
1369         int samples = mode->samples;
1370         int fullscreen = mode->fullscreen;
1371         int numdevices;
1372
1373         if (vid_initialized)
1374                 Sys_Error("VID_InitMode called when video is already initialised");
1375
1376         vid_isfullscreen = fullscreen != 0;
1377         if (fullscreen)
1378         {
1379                 WindowStyle = WS_POPUP;
1380                 ExWindowStyle = WS_EX_TOPMOST;
1381         }
1382         else
1383         {
1384                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1385                 ExWindowStyle = 0;
1386         }
1387
1388         rect.top = 0;
1389         rect.left = 0;
1390         rect.right = width;
1391         rect.bottom = height;
1392         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1393
1394         if (fullscreen)
1395         {
1396                 CenterX = 0;
1397                 CenterY = 0;
1398         }
1399         else
1400         {
1401                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1402                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1403         }
1404         CenterX = max(0, CenterX);
1405         CenterY = max(0, CenterY);
1406
1407         // x and y may be changed by WM_MOVE messages
1408         window_x = CenterX;
1409         window_y = CenterY;
1410         rect.left += CenterX;
1411         rect.right += CenterX;
1412         rect.top += CenterY;
1413         rect.bottom += CenterY;
1414
1415         gl_extensions = "";
1416         gl_platformextensions = "";
1417
1418         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1419         if (!mainwindow)
1420         {
1421                 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, global_hInstance, (void *)NULL);
1422                 VID_Shutdown();
1423                 return false;
1424         }
1425
1426         baseDC = GetDC(mainwindow);
1427
1428         vid_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
1429         if (!vid_d3d9)
1430                 Sys_Error("VID_InitMode: Direct3DCreate9 failed");
1431
1432         numdevices = IDirect3D9_GetAdapterCount(vid_d3d9);
1433         vid_d3d9dev = NULL;
1434         memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1435         for (deviceindex = 0;deviceindex < numdevices && !vid_d3d9dev;deviceindex++)
1436         {
1437                 memset(&vid_d3dpresentparameters, 0, sizeof(vid_d3dpresentparameters));
1438 //              vid_d3dpresentparameters.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
1439                 vid_d3dpresentparameters.Flags = 0;
1440                 vid_d3dpresentparameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
1441                 vid_d3dpresentparameters.hDeviceWindow = mainwindow;
1442                 vid_d3dpresentparameters.BackBufferWidth = width;
1443                 vid_d3dpresentparameters.BackBufferHeight = height;
1444                 vid_d3dpresentparameters.MultiSampleType = samples > 1 ? (D3DMULTISAMPLE_TYPE)samples : D3DMULTISAMPLE_NONE;
1445                 vid_d3dpresentparameters.BackBufferCount = fullscreen ? (vid_dx9_triplebuffer.integer ? 3 : 2) : 1;
1446                 vid_d3dpresentparameters.FullScreen_RefreshRateInHz = fullscreen ? refreshrate : 0;
1447                 vid_d3dpresentparameters.Windowed = !fullscreen;
1448                 vid_d3dpresentparameters.EnableAutoDepthStencil = true;
1449                 vid_d3dpresentparameters.AutoDepthStencilFormat = bpp > 16 ? D3DFMT_D24S8 : D3DFMT_D16;
1450                 vid_d3dpresentparameters.BackBufferFormat = fullscreen?D3DFMT_X8R8G8B8:D3DFMT_UNKNOWN;
1451                 vid_d3dpresentparameters.PresentationInterval = vid_vsync.integer ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
1452
1453                 memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
1454                 IDirect3D9_GetAdapterIdentifier(vid_d3d9, deviceindex, 0, &d3d9adapteridentifier);
1455
1456                 IDirect3D9_CreateDevice(vid_d3d9, deviceindex, vid_dx9_hal.integer ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF, mainwindow, vid_dx9_softvertex.integer ? D3DCREATE_SOFTWARE_VERTEXPROCESSING : D3DCREATE_HARDWARE_VERTEXPROCESSING, &vid_d3dpresentparameters, &vid_d3d9dev);
1457         }
1458
1459         if (!vid_d3d9dev)
1460         {
1461                 VID_Shutdown();
1462                 return false;
1463         }
1464
1465         IDirect3DDevice9_GetDeviceCaps(vid_d3d9dev, &vid_d3d9caps);
1466
1467         Con_Printf("Using D3D9 device: %s\n", d3d9adapteridentifier.Description);
1468         gl_extensions = "";
1469         gl_platform = "D3D9";
1470         gl_platformextensions = "";
1471
1472         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1473         UpdateWindow (mainwindow);
1474
1475         // now we try to make sure we get the focus on the mode switch, because
1476         // sometimes in some systems we don't.  We grab the foreground, then
1477         // finish setting up, pump all our messages, and sleep for a little while
1478         // to let messages finish bouncing around the system, then we put
1479         // ourselves at the top of the z order, then grab the foreground again,
1480         // Who knows if it helps, but it probably doesn't hurt
1481         SetForegroundWindow (mainwindow);
1482
1483         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1484         {
1485                 TranslateMessage (&msg);
1486                 DispatchMessage (&msg);
1487         }
1488
1489         Sleep (100);
1490
1491         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1492
1493         SetForegroundWindow (mainwindow);
1494
1495         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1496         ClearAllStates ();
1497
1498         gl_renderer = d3d9adapteridentifier.Description;
1499         gl_vendor = d3d9adapteridentifier.Driver;
1500         gl_version = "";
1501         gl_extensions = "";
1502
1503         Con_Printf("D3D9 adapter info:\n");
1504         Con_Printf("Description: %s\n", d3d9adapteridentifier.Description);
1505         Con_Printf("DeviceId: %x\n", (unsigned int)d3d9adapteridentifier.DeviceId);
1506         Con_Printf("DeviceName: %p\n", d3d9adapteridentifier.DeviceName);
1507         Con_Printf("Driver: %s\n", d3d9adapteridentifier.Driver);
1508         Con_Printf("DriverVersion: %08x%08x\n", (unsigned int)d3d9adapteridentifier.DriverVersion.u.HighPart, (unsigned int)d3d9adapteridentifier.DriverVersion.u.LowPart);
1509         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
1510         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
1511
1512         // clear the extension flags
1513         memset(&vid.support, 0, sizeof(vid.support));
1514         Cvar_SetQuick(&gl_info_extensions, "");
1515
1516         // D3D9 requires BGRA
1517         vid.forcetextype = TEXTYPE_BGRA;
1518
1519         vid.forcevbo = false;
1520         vid.support.arb_depth_texture = true;
1521         vid.support.arb_draw_buffers = vid_d3d9caps.NumSimultaneousRTs > 1;
1522         vid.support.arb_occlusion_query = true; // can't find a cap for this
1523         vid.support.arb_shadow = true;
1524         vid.support.arb_texture_compression = true;
1525         vid.support.arb_texture_cube_map = true;
1526         vid.support.arb_texture_non_power_of_two = (vid_d3d9caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
1527         vid.support.arb_vertex_buffer_object = true;
1528         vid.support.ext_blend_subtract = true;
1529         vid.support.ext_draw_range_elements = true;
1530         vid.support.ext_framebuffer_object = true;
1531
1532         vid.support.ext_texture_3d = true;
1533         vid.support.ext_texture_compression_s3tc = true;
1534         vid.support.ext_texture_filter_anisotropic = true;
1535         vid.support.ati_separate_stencil = (vid_d3d9caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) != 0;
1536         vid.support.ext_texture_srgb = false; // FIXME use D3DSAMP_SRGBTEXTURE if CheckDeviceFormat agrees
1537
1538         vid.maxtexturesize_2d = min(vid_d3d9caps.MaxTextureWidth, vid_d3d9caps.MaxTextureHeight);
1539         vid.maxtexturesize_3d = vid_d3d9caps.MaxVolumeExtent;
1540         vid.maxtexturesize_cubemap = vid.maxtexturesize_2d;
1541         vid.texunits = 4;
1542         vid.teximageunits = vid_d3d9caps.MaxSimultaneousTextures;
1543         vid.texarrayunits = 8; // can't find a caps field for this?
1544         vid.max_anisotropy = vid_d3d9caps.MaxAnisotropy;
1545         vid.maxdrawbuffers = vid_d3d9caps.NumSimultaneousRTs;
1546
1547         vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
1548         vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
1549         vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
1550         Con_DPrintf("Using D3D9.0 rendering path - %i texture matrix, %i texture images, %i texcoords, shadowmapping supported%s\n", vid.texunits, vid.teximageunits, vid.texarrayunits, vid.maxdrawbuffers > 1 ? ", MRT detected (allows prepass deferred lighting)" : "");
1551         vid.renderpath = RENDERPATH_D3D9;
1552         vid.sRGBcapable2D = false;
1553         vid.sRGBcapable3D = true;
1554         vid.useinterleavedarrays = true;
1555
1556         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1557         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1558         Cvar_SetQuick(&gl_info_version, gl_version);
1559         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1560         Cvar_SetQuick(&gl_info_driver, gl_driver);
1561
1562         // LordHavoc: report supported extensions
1563         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1564
1565         // clear to black (loading plaque will be seen over this)
1566         IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
1567         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1568         IDirect3DDevice9_EndScene(vid_d3d9dev);
1569         IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
1570         // because the only time we end/begin scene is in VID_Finish, we'd better start a scene now...
1571         IDirect3DDevice9_BeginScene(vid_d3d9dev);
1572         vid_begunscene = true;
1573
1574         //vid_menudrawfn = VID_MenuDraw;
1575         //vid_menukeyfn = VID_MenuKey;
1576         vid_usingmouse = false;
1577         vid_usinghidecursor = false;
1578         vid_usingvsync = false;
1579         vid_hidden = vid_reallyhidden = false;
1580         vid_initialized = true;
1581
1582         IN_StartupMouse ();
1583
1584         return true;
1585 }
1586 #endif
1587
1588 qboolean VID_InitModeSOFT(viddef_mode_t *mode)
1589 {
1590         int i;
1591         HDC hdc;
1592         RECT rect;
1593         MSG msg;
1594         int pixelformat, newpixelformat;
1595         DWORD WindowStyle, ExWindowStyle;
1596         int CenterX, CenterY;
1597         int depth;
1598         DEVMODE thismode;
1599         qboolean foundmode, foundgoodmode;
1600         int bpp = mode->bitsperpixel;
1601         int width = mode->width;
1602         int height = mode->height;
1603         int refreshrate = (int)floor(mode->refreshrate+0.5);
1604         int fullscreen = mode->fullscreen;
1605
1606         if (vid_initialized)
1607                 Sys_Error("VID_InitMode called when video is already initialised");
1608
1609         memset(&gdevmode, 0, sizeof(gdevmode));
1610
1611         vid_isfullscreen = false;
1612         if (fullscreen)
1613         {
1614                 if(vid_forcerefreshrate.integer)
1615                 {
1616                         foundmode = true;
1617                         gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1618                         gdevmode.dmBitsPerPel = bpp;
1619                         gdevmode.dmPelsWidth = width;
1620                         gdevmode.dmPelsHeight = height;
1621                         gdevmode.dmSize = sizeof (gdevmode);
1622                         if(refreshrate)
1623                         {
1624                                 gdevmode.dmFields |= DM_DISPLAYFREQUENCY;
1625                                 gdevmode.dmDisplayFrequency = refreshrate;
1626                         }
1627                 }
1628                 else
1629                 {
1630                         if(refreshrate == 0)
1631                                 refreshrate = initialdevmode.dmDisplayFrequency; // default vid_refreshrate to the rate of the desktop
1632
1633                         foundmode = false;
1634                         foundgoodmode = false;
1635
1636                         thismode.dmSize = sizeof(thismode);
1637                         thismode.dmDriverExtra = 0;
1638                         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
1639                         {
1640                                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
1641                                 {
1642                                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
1643                                         continue;
1644                                 }
1645                                 if(developer_extra.integer)
1646                                         Con_DPrintf("Found mode %dx%dx%dbpp %dHz... ", (int)thismode.dmPelsWidth, (int)thismode.dmPelsHeight, (int)thismode.dmBitsPerPel, (int)thismode.dmDisplayFrequency);
1647                                 if(thismode.dmBitsPerPel != (DWORD)bpp)
1648                                 {
1649                                         if(developer_extra.integer)
1650                                                 Con_DPrintf("wrong bpp\n");
1651                                         continue;
1652                                 }
1653                                 if(thismode.dmPelsWidth != (DWORD)width)
1654                                 {
1655                                         if(developer_extra.integer)
1656                                                 Con_DPrintf("wrong width\n");
1657                                         continue;
1658                                 }
1659                                 if(thismode.dmPelsHeight != (DWORD)height)
1660                                 {
1661                                         if(developer_extra.integer)
1662                                                 Con_DPrintf("wrong height\n");
1663                                         continue;
1664                                 }
1665
1666                                 if(foundgoodmode)
1667                                 {
1668                                         // if we have a good mode, make sure this mode is better than the previous one, and allowed by the refreshrate
1669                                         if(thismode.dmDisplayFrequency > (DWORD)refreshrate)
1670                                         {
1671                                                 if(developer_extra.integer)
1672                                                         Con_DPrintf("too high refresh rate\n");
1673                                                 continue;
1674                                         }
1675                                         else if(thismode.dmDisplayFrequency <= gdevmode.dmDisplayFrequency)
1676                                         {
1677                                                 if(developer_extra.integer)
1678                                                         Con_DPrintf("doesn't beat previous best match (too low)\n");
1679                                                 continue;
1680                                         }
1681                                 }
1682                                 else if(foundmode)
1683                                 {
1684                                         // we do have one, but it isn't good... make sure it has a lower frequency than the previous one
1685                                         if(thismode.dmDisplayFrequency >= gdevmode.dmDisplayFrequency)
1686                                         {
1687                                                 if(developer_extra.integer)
1688                                                         Con_DPrintf("doesn't beat previous best match (too high)\n");
1689                                                 continue;
1690                                         }
1691                                 }
1692                                 // otherwise, take anything
1693
1694                                 memcpy(&gdevmode, &thismode, sizeof(gdevmode));
1695                                 if(thismode.dmDisplayFrequency <= (DWORD)refreshrate)
1696                                         foundgoodmode = true;
1697                                 else
1698                                 {
1699                                         if(developer_extra.integer)
1700                                                 Con_DPrintf("(out of range)\n");
1701                                 }
1702                                 foundmode = true;
1703                                 if(developer_extra.integer)
1704                                         Con_DPrintf("accepted\n");
1705                         }
1706                 }
1707
1708                 if (!foundmode)
1709                 {
1710                         VID_Shutdown();
1711                         Con_Printf("Unable to find the requested mode %dx%dx%dbpp\n", width, height, bpp);
1712                         return false;
1713                 }
1714                 else if(ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
1715                 {
1716                         VID_Shutdown();
1717                         Con_Printf("Unable to change to requested mode %dx%dx%dbpp\n", width, height, bpp);
1718                         return false;
1719                 }
1720
1721                 vid_isfullscreen = true;
1722                 WindowStyle = WS_POPUP;
1723                 ExWindowStyle = WS_EX_TOPMOST;
1724         }
1725         else
1726         {
1727                 hdc = GetDC (NULL);
1728                 i = GetDeviceCaps(hdc, RASTERCAPS);
1729                 depth = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
1730                 ReleaseDC (NULL, hdc);
1731                 if (i & RC_PALETTE)
1732                 {
1733                         VID_Shutdown();
1734                         Con_Print("Can't run in non-RGB mode\n");
1735                         return false;
1736                 }
1737                 if (bpp > depth)
1738                 {
1739                         VID_Shutdown();
1740                         Con_Print("A higher desktop depth is required to run this video mode\n");
1741                         return false;
1742                 }
1743
1744                 WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
1745                 ExWindowStyle = 0;
1746         }
1747
1748         rect.top = 0;
1749         rect.left = 0;
1750         rect.right = width;
1751         rect.bottom = height;
1752         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
1753
1754         if (fullscreen)
1755         {
1756                 CenterX = 0;
1757                 CenterY = 0;
1758         }
1759         else
1760         {
1761                 CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
1762                 CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
1763         }
1764         CenterX = max(0, CenterX);
1765         CenterY = max(0, CenterY);
1766
1767         // x and y may be changed by WM_MOVE messages
1768         window_x = CenterX;
1769         window_y = CenterY;
1770         rect.left += CenterX;
1771         rect.right += CenterX;
1772         rect.top += CenterY;
1773         rect.bottom += CenterY;
1774
1775         pixelformat = 0;
1776         newpixelformat = 0;
1777         gl_extensions = "";
1778         gl_platformextensions = "";
1779
1780         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
1781         if (!mainwindow)
1782         {
1783                 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);
1784                 VID_Shutdown();
1785                 return false;
1786         }
1787
1788         baseDC = GetDC(mainwindow);
1789         vid.softpixels = NULL;
1790         memset(&vid_softbmi, 0, sizeof(vid_softbmi));
1791         vid_softbmi.bmiHeader.biSize = sizeof(vid_softbmi.bmiHeader);
1792         vid_softbmi.bmiHeader.biWidth = width;
1793         vid_softbmi.bmiHeader.biHeight = -height; // negative to make a top-down bitmap
1794         vid_softbmi.bmiHeader.biPlanes = 1;
1795         vid_softbmi.bmiHeader.biBitCount = 32;
1796         vid_softbmi.bmiHeader.biCompression = BI_RGB;
1797         vid_softbmi.bmiHeader.biSizeImage = width*height*4;
1798         vid_softbmi.bmiHeader.biClrUsed = 256;
1799         vid_softbmi.bmiHeader.biClrImportant = 256;
1800         vid_softdibhandle = CreateDIBSection(baseDC, &vid_softbmi, DIB_RGB_COLORS, (void **)&vid.softpixels, NULL, 0);
1801         if (!vid_softdibhandle)
1802         {
1803                 Con_Printf("CreateDIBSection failed\n");
1804                 VID_Shutdown();
1805                 return false;
1806         }
1807
1808         vid_softhdc = CreateCompatibleDC(baseDC);
1809         vid_softhdc_backup = SelectObject(vid_softhdc, vid_softdibhandle);
1810         if (!vid_softhdc_backup)
1811         {
1812                 Con_Printf("SelectObject failed\n");
1813                 VID_Shutdown();
1814                 return false;
1815         }
1816 //      ReleaseDC(mainwindow, baseDC);
1817 //      baseDC = NULL;
1818
1819         vid.softdepthpixels = (unsigned int *)calloc(1, mode->width * mode->height * 4);
1820         if (DPSOFTRAST_Init(mode->width, mode->height, vid_soft_threads.integer, vid_soft_interlace.integer, (unsigned int *)vid.softpixels, (unsigned int *)vid.softdepthpixels) < 0)
1821         {
1822                 Con_Printf("Failed to initialize software rasterizer\n");
1823                 VID_Shutdown();
1824                 return false;
1825         }
1826
1827         VID_Soft_SharedSetup();
1828
1829         ShowWindow (mainwindow, SW_SHOWDEFAULT);
1830         UpdateWindow (mainwindow);
1831
1832         // now we try to make sure we get the focus on the mode switch, because
1833         // sometimes in some systems we don't.  We grab the foreground, then
1834         // finish setting up, pump all our messages, and sleep for a little while
1835         // to let messages finish bouncing around the system, then we put
1836         // ourselves at the top of the z order, then grab the foreground again,
1837         // Who knows if it helps, but it probably doesn't hurt
1838         SetForegroundWindow (mainwindow);
1839
1840         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
1841         {
1842                 TranslateMessage (&msg);
1843                 DispatchMessage (&msg);
1844         }
1845
1846         Sleep (100);
1847
1848         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
1849
1850         SetForegroundWindow (mainwindow);
1851
1852         // fix the leftover Alt from any Alt-Tab or the like that switched us away
1853         ClearAllStates ();
1854
1855         //vid_menudrawfn = VID_MenuDraw;
1856         //vid_menukeyfn = VID_MenuKey;
1857         vid_usingmouse = false;
1858         vid_usinghidecursor = false;
1859         vid_usingvsync = false;
1860         vid_reallyhidden = vid_hidden = false;
1861         vid_initialized = true;
1862
1863         IN_StartupMouse ();
1864
1865         return true;
1866 }
1867
1868 qboolean VID_InitMode(viddef_mode_t *mode)
1869 {
1870 #ifdef SSE_POSSIBLE
1871         if (vid_soft.integer)
1872                 return VID_InitModeSOFT(mode);
1873 #endif
1874 #ifdef SUPPORTD3D
1875 //      if (vid_dx11.integer)
1876 //              return VID_InitModeDX(mode, 11);
1877 //      if (vid_dx10.integer)
1878 //              return VID_InitModeDX(mode, 10);
1879         if (vid_dx9.integer)
1880                 return VID_InitModeDX(mode, 9);
1881 #endif
1882         return VID_InitModeGL(mode);
1883 }
1884
1885
1886 static void IN_Shutdown(void);
1887 void VID_Shutdown (void)
1888 {
1889         qboolean isgl;
1890         if(vid_initialized == false)
1891                 return;
1892
1893         VID_EnableJoystick(false);
1894         VID_SetMouse(false, false, false);
1895         VID_RestoreSystemGamma();
1896
1897         vid_initialized = false;
1898         isgl = gldll != NULL;
1899         IN_Shutdown();
1900         gl_driver[0] = 0;
1901         gl_extensions = "";
1902         gl_platform = "";
1903         gl_platformextensions = "";
1904         if (vid_softhdc)
1905         {
1906                 SelectObject(vid_softhdc, vid_softhdc_backup);
1907                 ReleaseDC(mainwindow, vid_softhdc);
1908         }
1909         vid_softhdc = NULL;
1910         vid_softhdc_backup = NULL;
1911         if (vid_softdibhandle)
1912                 DeleteObject(vid_softdibhandle);
1913         vid_softdibhandle = NULL;
1914         vid.softpixels = NULL;
1915         if (vid.softdepthpixels)
1916                 free(vid.softdepthpixels);
1917         vid.softdepthpixels = NULL;
1918 #ifdef SUPPORTD3D
1919         if (vid_d3d9dev)
1920         {
1921                 if (vid_begunscene)
1922                         IDirect3DDevice9_EndScene(vid_d3d9dev);
1923                 vid_begunscene = false;
1924 //              Cmd_ExecuteString("r_texturestats", src_command, true);
1925 //              Cmd_ExecuteString("memlist", src_command, true);
1926                 IDirect3DDevice9_Release(vid_d3d9dev);
1927         }
1928         vid_d3d9dev = NULL;
1929         if (vid_d3d9)
1930                 IDirect3D9_Release(vid_d3d9);
1931         vid_d3d9 = NULL;
1932 #endif
1933         if (qwglMakeCurrent)
1934                 qwglMakeCurrent(NULL, NULL);
1935         qwglMakeCurrent = NULL;
1936         if (baseRC && qwglDeleteContext)
1937                 qwglDeleteContext(baseRC);
1938         qwglDeleteContext = NULL;
1939         // close the library before we get rid of the window
1940         GL_CloseLibrary();
1941         if (baseDC && mainwindow)
1942                 ReleaseDC(mainwindow, baseDC);
1943         baseDC = NULL;
1944         AppActivate(false, false);
1945         if (mainwindow)
1946                 DestroyWindow(mainwindow);
1947         mainwindow = 0;
1948         if (vid_isfullscreen && isgl)
1949                 ChangeDisplaySettings (NULL, CDS_FULLSCREEN);
1950         vid_isfullscreen = false;
1951 }
1952
1953 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean hidecursor)
1954 {
1955         static qboolean restore_spi;
1956         static int originalmouseparms[3];
1957
1958         if (!mouseinitialized)
1959                 return;
1960
1961         if (relative)
1962         {
1963                 if (!vid_usingmouse)
1964                 {
1965                         vid_usingmouse = true;
1966                         cl_ignoremousemoves = 2;
1967 #ifdef SUPPORTDIRECTX
1968                         if (dinput && g_pMouse)
1969                         {
1970                                 IDirectInputDevice_Acquire(g_pMouse);
1971                                 dinput_acquired = true;
1972                         }
1973                         else
1974 #endif
1975                         {
1976                                 RECT window_rect;
1977                                 window_rect.left = window_x;
1978                                 window_rect.top = window_y;
1979                                 window_rect.right = window_x + vid.width;
1980                                 window_rect.bottom = window_y + vid.height;
1981
1982                                 // change mouse settings to turn off acceleration
1983 // COMMANDLINEOPTION: Windows GDI Input: -noforcemparms disables setting of mouse parameters (not used with -dinput, windows only)
1984                                 if (!COM_CheckParm ("-noforcemparms") && SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0))
1985                                 {
1986                                         int newmouseparms[3];
1987                                         newmouseparms[0] = 0; // threshold to double movement (only if accel level is >= 1)
1988                                         newmouseparms[1] = 0; // threshold to quadruple movement (only if accel level is >= 2)
1989                                         newmouseparms[2] = 0; // maximum level of acceleration (0 = off)
1990                                         restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0) != FALSE;
1991                                 }
1992                                 else
1993                                         restore_spi = false;
1994                                 SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
1995
1996                                 SetCapture (mainwindow);
1997                                 ClipCursor (&window_rect);
1998                         }
1999                 }
2000         }
2001         else
2002         {
2003                 if (vid_usingmouse)
2004                 {
2005                         vid_usingmouse = false;
2006                         cl_ignoremousemoves = 2;
2007 #ifdef SUPPORTDIRECTX
2008                         if (dinput_acquired)
2009                         {
2010                                 IDirectInputDevice_Unacquire(g_pMouse);
2011                                 dinput_acquired = false;
2012                         }
2013                         else
2014 #endif
2015                         {
2016                                 // restore system mouseparms if we changed them
2017                                 if (restore_spi)
2018                                         SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
2019                                 restore_spi = false;
2020                                 ClipCursor (NULL);
2021                                 ReleaseCapture ();
2022                         }
2023                 }
2024         }
2025
2026         if (vid_usinghidecursor != hidecursor)
2027         {
2028                 vid_usinghidecursor = hidecursor;
2029                 ShowCursor (!hidecursor);
2030         }
2031 }
2032
2033 void VID_BuildJoyState(vid_joystate_t *joystate)
2034 {
2035         VID_Shared_BuildJoyState_Begin(joystate);
2036         VID_Shared_BuildJoyState_Finish(joystate);
2037 }
2038
2039 void VID_EnableJoystick(qboolean enable)
2040 {
2041         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
2042         qboolean success = false;
2043         int sharedcount = 0;
2044         sharedcount = VID_Shared_SetJoystick(index);
2045         if (index >= 0 && index < sharedcount)
2046                 success = true;
2047
2048         // update cvar containing count of XInput joysticks
2049         if (joy_detected.integer != sharedcount)
2050                 Cvar_SetValueQuick(&joy_detected, sharedcount);
2051
2052         if (joy_active.integer != (success ? 1 : 0))
2053                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
2054 }
2055
2056 #ifdef SUPPORTDIRECTX
2057 /*
2058 ===========
2059 IN_InitDInput
2060 ===========
2061 */
2062 static qboolean IN_InitDInput (void)
2063 {
2064     HRESULT             hr;
2065         DIPROPDWORD     dipdw = {
2066                 {
2067                         sizeof(DIPROPDWORD),        // diph.dwSize
2068                         sizeof(DIPROPHEADER),       // diph.dwHeaderSize
2069                         0,                          // diph.dwObj
2070                         DIPH_DEVICE,                // diph.dwHow
2071                 },
2072                 DINPUT_BUFFERSIZE,              // dwData
2073         };
2074
2075         if (!hInstDI)
2076         {
2077                 hInstDI = LoadLibrary("dinput.dll");
2078
2079                 if (hInstDI == NULL)
2080                 {
2081                         Con_Print("Couldn't load dinput.dll\n");
2082                         return false;
2083                 }
2084         }
2085
2086         if (!pDirectInputCreate)
2087         {
2088                 pDirectInputCreate = (HRESULT (__stdcall *)(HINSTANCE,DWORD,LPDIRECTINPUT *,LPUNKNOWN))GetProcAddress(hInstDI,"DirectInputCreateA");
2089
2090                 if (!pDirectInputCreate)
2091                 {
2092                         Con_Print("Couldn't get DI proc addr\n");
2093                         return false;
2094                 }
2095         }
2096
2097 // register with DirectInput and get an IDirectInput to play with.
2098         hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL);
2099
2100         if (FAILED(hr))
2101         {
2102                 return false;
2103         }
2104
2105 // obtain an interface to the system mouse device.
2106 #ifdef __cplusplus
2107         hr = IDirectInput_CreateDevice(g_pdi, GUID_SysMouse, &g_pMouse, NULL);
2108 #else
2109         hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL);
2110 #endif
2111
2112         if (FAILED(hr))
2113         {
2114                 Con_Print("Couldn't open DI mouse device\n");
2115                 return false;
2116         }
2117
2118 // set the data format to "mouse format".
2119         hr = IDirectInputDevice_SetDataFormat(g_pMouse, &c_dfDIMouse);
2120
2121         if (FAILED(hr))
2122         {
2123                 Con_Print("Couldn't set DI mouse format\n");
2124                 return false;
2125         }
2126
2127 // set the cooperativity level.
2128         hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow,
2129                         DISCL_EXCLUSIVE | DISCL_FOREGROUND);
2130
2131         if (FAILED(hr))
2132         {
2133                 Con_Print("Couldn't set DI coop level\n");
2134                 return false;
2135         }
2136
2137
2138 // set the buffer size to DINPUT_BUFFERSIZE elements.
2139 // the buffer size is a DWORD property associated with the device
2140         hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph);
2141
2142         if (FAILED(hr))
2143         {
2144                 Con_Print("Couldn't set DI buffersize\n");
2145                 return false;
2146         }
2147
2148         return true;
2149 }
2150 #endif
2151
2152
2153 /*
2154 ===========
2155 IN_StartupMouse
2156 ===========
2157 */
2158 static void IN_StartupMouse (void)
2159 {
2160         if (COM_CheckParm ("-nomouse"))
2161                 return;
2162
2163         mouseinitialized = true;
2164
2165 #ifdef SUPPORTDIRECTX
2166 // COMMANDLINEOPTION: Windows Input: -dinput enables DirectInput for mouse input
2167         if (COM_CheckParm ("-dinput"))
2168                 dinput = IN_InitDInput ();
2169
2170         if (dinput)
2171                 Con_Print("DirectInput initialized\n");
2172         else
2173                 Con_Print("DirectInput not initialized\n");
2174 #endif
2175
2176         mouse_buttons = 10;
2177 }
2178
2179
2180 /*
2181 ===========
2182 IN_MouseMove
2183 ===========
2184 */
2185 static void IN_MouseMove (void)
2186 {
2187         POINT current_pos;
2188
2189         GetCursorPos (&current_pos);
2190         in_windowmouse_x = current_pos.x - window_x;
2191         in_windowmouse_y = current_pos.y - window_y;
2192
2193         if (!vid_usingmouse)
2194                 return;
2195
2196 #ifdef SUPPORTDIRECTX
2197         if (dinput_acquired)
2198         {
2199                 int i;
2200                 DIDEVICEOBJECTDATA      od;
2201                 DWORD                           dwElements;
2202                 HRESULT                         hr;
2203
2204                 for (;;)
2205                 {
2206                         dwElements = 1;
2207
2208                         hr = IDirectInputDevice_GetDeviceData(g_pMouse,
2209                                         sizeof(DIDEVICEOBJECTDATA), &od, &dwElements, 0);
2210
2211                         if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
2212                         {
2213                                 IDirectInputDevice_Acquire(g_pMouse);
2214                                 break;
2215                         }
2216
2217                         /* Unable to read data or no data available */
2218                         if (FAILED(hr) || dwElements == 0)
2219                                 break;
2220
2221                         /* Look at the element to see what happened */
2222
2223                         if ((int)od.dwOfs == DIMOFS_X)
2224                                 in_mouse_x += (LONG) od.dwData;
2225                         if ((int)od.dwOfs == DIMOFS_Y)
2226                                 in_mouse_y += (LONG) od.dwData;
2227                         if ((int)od.dwOfs == DIMOFS_Z)
2228                         {
2229                                 if((LONG)od.dwData < 0)
2230                                 {
2231                                         Key_Event(K_MWHEELDOWN, 0, true);
2232                                         Key_Event(K_MWHEELDOWN, 0, false);
2233                                 }
2234                                 else if((LONG)od.dwData > 0)
2235                                 {
2236                                         Key_Event(K_MWHEELUP, 0, true);
2237                                         Key_Event(K_MWHEELUP, 0, false);
2238                                 }
2239                         }
2240                         if ((int)od.dwOfs == DIMOFS_BUTTON0)
2241                                 mstate_di = (mstate_di & ~1) | ((od.dwData & 0x80) >> 7);
2242                         if ((int)od.dwOfs == DIMOFS_BUTTON1)
2243                                 mstate_di = (mstate_di & ~2) | ((od.dwData & 0x80) >> 6);
2244                         if ((int)od.dwOfs == DIMOFS_BUTTON2)
2245                                 mstate_di = (mstate_di & ~4) | ((od.dwData & 0x80) >> 5);
2246                         if ((int)od.dwOfs == DIMOFS_BUTTON3)
2247                                 mstate_di = (mstate_di & ~8) | ((od.dwData & 0x80) >> 4);
2248                 }
2249
2250                 // perform button actions
2251                 for (i=0 ; i<mouse_buttons && i < 16 ; i++)
2252                         if ((mstate_di ^ mouse_oldbuttonstate) & (1<<i))
2253                                 Key_Event (buttonremap[i], 0, (mstate_di & (1<<i)) != 0);
2254                 mouse_oldbuttonstate = mstate_di;
2255         }
2256         else
2257 #endif
2258         {
2259                 in_mouse_x += in_windowmouse_x - (int)(vid.width / 2);
2260                 in_mouse_y += in_windowmouse_y - (int)(vid.height / 2);
2261
2262                 // if the mouse has moved, force it to the center, so there's room to move
2263                 if (in_mouse_x || in_mouse_y)
2264                         SetCursorPos ((window_x + vid.width / 2), (window_y + vid.height / 2));
2265         }
2266 }
2267
2268
2269 /*
2270 ===========
2271 IN_Move
2272 ===========
2273 */
2274 void IN_Move (void)
2275 {
2276         vid_joystate_t joystate;
2277         if (vid_activewindow && !vid_reallyhidden)
2278                 IN_MouseMove ();
2279         VID_EnableJoystick(true);
2280         VID_BuildJoyState(&joystate);
2281         VID_ApplyJoyState(&joystate);
2282 }
2283
2284
2285 static void IN_Init(void)
2286 {
2287         uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" );
2288         Cvar_RegisterVariable (&vid_forcerefreshrate);
2289 }
2290
2291 static void IN_Shutdown(void)
2292 {
2293 #ifdef SUPPORTDIRECTX
2294         if (g_pMouse)
2295                 IDirectInputDevice_Release(g_pMouse);
2296         g_pMouse = NULL;
2297
2298         if (g_pdi)
2299                 IDirectInput_Release(g_pdi);
2300         g_pdi = NULL;
2301 #endif
2302 }
2303
2304 vid_mode_t *VID_GetDesktopMode(void)
2305 {
2306         return &desktop_mode;
2307 }
2308
2309 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
2310 {
2311         int i;
2312         size_t k;
2313         DEVMODE thismode;
2314
2315         thismode.dmSize = sizeof(thismode);
2316         thismode.dmDriverExtra = 0;
2317         k = 0;
2318         for(i = 0; EnumDisplaySettings(NULL, i, &thismode); ++i)
2319         {
2320                 if(~thismode.dmFields & (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY))
2321                 {
2322                         Con_DPrintf("enumerating modes yielded a bogus item... please debug this\n");
2323                         continue;
2324                 }
2325                 if(k >= maxcount)
2326                         break;
2327                 modes[k].width = thismode.dmPelsWidth;
2328                 modes[k].height = thismode.dmPelsHeight;
2329                 modes[k].bpp = thismode.dmBitsPerPel;
2330                 modes[k].refreshrate = thismode.dmDisplayFrequency;
2331                 modes[k].pixelheight_num = 1;
2332                 modes[k].pixelheight_denom = 1; // Win32 apparently does not provide this (FIXME)
2333                 ++k;
2334         }
2335         return k;
2336 }