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