moved Sys_Printf and related code/data to sys_shared.c (new), removed all uses of...
[divverent/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 // gl_vidnt.c -- NT GL vid component
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "resource.h"
25 #include <commctrl.h>
26
27 #define MAX_MODE_LIST   30
28 #define VID_ROW_SIZE    3
29 #define MAXWIDTH                10000
30 #define MAXHEIGHT               10000
31
32 #define MODE_WINDOWED                   0
33 #define NO_MODE                                 (MODE_WINDOWED - 1)
34 #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 1)
35
36 typedef struct {
37         modestate_t     type;
38         int                     width;
39         int                     height;
40         int                     modenum;
41         int                     dib;
42         int                     fullscreen;
43         int                     bpp;
44         int                     halfscreen;
45         char            modedesc[17];
46 } vmode_t;
47
48 typedef struct {
49         int                     width;
50         int                     height;
51 } lmode_t;
52
53 lmode_t lowresmodes[] = {
54         {320, 200},
55         {320, 240},
56         {400, 300},
57         {512, 384},
58 };
59
60 const char *gl_vendor;
61 const char *gl_renderer;
62 const char *gl_version;
63 const char *gl_extensions;
64
65 qboolean                scr_skipupdate;
66
67 static vmode_t  modelist[MAX_MODE_LIST];
68 static int              nummodes;
69 static vmode_t  *pcurrentmode;
70 static vmode_t  badmode;
71
72 static DEVMODE  gdevmode;
73 static qboolean vid_initialized = false;
74 static qboolean windowed, leavecurrentmode;
75 static qboolean vid_canalttab = false;
76 static qboolean vid_wassuspended = false;
77 static int              usingmouse;
78 extern qboolean mouseactive;  // from in_win.c
79 static HICON    hIcon;
80
81 int                     DIBWidth, DIBHeight;
82 RECT            WindowRect;
83 DWORD           WindowStyle, ExWindowStyle;
84
85 HWND    mainwindow;
86
87 int                     vid_modenum = NO_MODE;
88 int                     vid_realmode;
89 int                     vid_default = MODE_WINDOWED;
90 static int      windowed_default;
91 unsigned char   vid_curpal[256*3];
92
93 HGLRC   baseRC;
94 HDC             maindc;
95
96 glvert_t glv;
97
98 HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
99
100 viddef_t        vid;                            // global video state
101
102 float           gldepthmin, gldepthmax;
103
104 modestate_t     modestate = MS_UNINIT;
105
106 void VID_MenuDraw (void);
107 void VID_MenuKey (int key);
108
109 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
110 void AppActivate(BOOL fActive, BOOL minimize);
111 char *VID_GetModeDescription (int mode);
112 void ClearAllStates (void);
113 void VID_UpdateWindowStatus (void);
114
115 //====================================
116
117 // Note that 0 is MODE_WINDOWED
118 //cvar_t                _vid_default_mode = {"_vid_default_mode","0", true};
119 // Note that 3 is MODE_FULLSCREEN_DEFAULT
120 //cvar_t                _vid_default_mode_win = {"_vid_default_mode_win","3", true};
121
122 int                     window_center_x, window_center_y, window_x, window_y, window_width, window_height;
123 RECT            window_rect;
124
125 // direct draw software compatability stuff
126
127 void CenterWindow(HWND hWndCenter, int width, int height, BOOL lefttopjustify)
128 {
129     int     CenterX, CenterY;
130
131         CenterX = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
132         CenterY = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
133         if (CenterX > CenterY*2)
134                 CenterX >>= 1;  // dual screens
135         CenterX = (CenterX < 0) ? 0: CenterX;
136         CenterY = (CenterY < 0) ? 0: CenterY;
137         SetWindowPos (hWndCenter, NULL, CenterX, CenterY, 0, 0,
138                         SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
139 }
140
141 qboolean VID_SetWindowedMode (int modenum)
142 {
143         int                             lastmodestate, width, height;
144         RECT                    rect;
145
146         lastmodestate = modestate;
147
148         WindowRect.top = WindowRect.left = 0;
149
150         WindowRect.right = modelist[modenum].width;
151         WindowRect.bottom = modelist[modenum].height;
152
153         DIBWidth = modelist[modenum].width;
154         DIBHeight = modelist[modenum].height;
155
156         WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
157         ExWindowStyle = 0;
158
159         rect = WindowRect;
160         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
161
162         width = rect.right - rect.left;
163         height = rect.bottom - rect.top;
164
165         // Create the DIB window
166         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlaces", "DarkPlacesGL", WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
167
168         if (!mainwindow)
169                 Sys_Error ("Couldn't create DIB window");
170
171         // Center and show the DIB window
172         CenterWindow(mainwindow, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, false);
173
174         ShowWindow (mainwindow, SW_SHOWDEFAULT);
175         UpdateWindow (mainwindow);
176
177         modestate = MS_WINDOWED;
178
179         if (vid.conheight > modelist[modenum].height)
180                 vid.conheight = modelist[modenum].height;
181         if (vid.conwidth > modelist[modenum].width)
182                 vid.conwidth = modelist[modenum].width;
183         vid.width = vid.conwidth;
184         vid.height = vid.conheight;
185
186         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
187         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
188
189         return true;
190 }
191
192
193 qboolean VID_SetFullDIBMode (int modenum)
194 {
195         int                             lastmodestate, width, height;
196         RECT                    rect;
197
198         if (!leavecurrentmode)
199         {
200                 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
201                 gdevmode.dmBitsPerPel = modelist[modenum].bpp;
202                 gdevmode.dmPelsWidth = modelist[modenum].width <<
203                                                            modelist[modenum].halfscreen;
204                 gdevmode.dmPelsHeight = modelist[modenum].height;
205                 gdevmode.dmSize = sizeof (gdevmode);
206
207                 if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
208                         Sys_Error ("Couldn't set fullscreen DIB mode");
209         }
210
211         lastmodestate = modestate;
212         modestate = MS_FULLDIB;
213
214         WindowRect.top = WindowRect.left = 0;
215
216         WindowRect.right = modelist[modenum].width;
217         WindowRect.bottom = modelist[modenum].height;
218
219         DIBWidth = modelist[modenum].width;
220         DIBHeight = modelist[modenum].height;
221
222         WindowStyle = WS_POPUP;
223         ExWindowStyle = 0;
224
225         rect = WindowRect;
226         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
227
228         width = rect.right - rect.left;
229         height = rect.bottom - rect.top;
230
231         // Create the DIB window
232         mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlaces", "DarkPlacesGL", WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
233
234         if (!mainwindow)
235                 Sys_Error ("Couldn't create DIB window");
236
237         ShowWindow (mainwindow, SW_SHOWDEFAULT);
238         UpdateWindow (mainwindow);
239
240         if (vid.conheight > modelist[modenum].height)
241                 vid.conheight = modelist[modenum].height;
242         if (vid.conwidth > modelist[modenum].width)
243                 vid.conwidth = modelist[modenum].width;
244         vid.width = vid.conwidth;
245         vid.height = vid.conheight;
246
247 // needed because we're not getting WM_MOVE messages fullscreen on NT
248         window_x = 0;
249         window_y = 0;
250
251         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
252         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
253
254         return true;
255 }
256
257
258 int VID_SetMode (int modenum)
259 {
260         int                             original_mode, temp;
261         qboolean                stat;
262     MSG                         msg;
263
264         if ((windowed && (modenum != 0)) || (!windowed && (modenum < 1)) || (!windowed && (modenum >= nummodes)))
265                 Sys_Error ("Bad video mode\n");
266
267 // so Con_Printfs don't mess us up by forcing vid and snd updates
268         temp = scr_disabled_for_loading;
269         scr_disabled_for_loading = true;
270
271         CDAudio_Pause ();
272
273         if (vid_modenum == NO_MODE)
274                 original_mode = windowed_default;
275         else
276                 original_mode = vid_modenum;
277
278         // Set either the fullscreen or windowed mode
279         if (modelist[modenum].type == MS_WINDOWED)
280         {
281 //              if (vid_mouse.value && key_dest == key_game)
282 //              {
283 //                      stat = VID_SetWindowedMode(modenum);
284 //                      usingmouse = true;
285 //                      IN_ActivateMouse ();
286 //                      IN_HideMouse ();
287 //              }
288 //              else
289 //              {
290 //                      usingmouse = false;
291 //                      IN_DeactivateMouse ();
292 //                      IN_ShowMouse ();
293 //                      stat = VID_SetWindowedMode(modenum);
294 //              }
295                 stat = VID_SetWindowedMode(modenum);
296         }
297         else if (modelist[modenum].type == MS_FULLDIB)
298         {
299                 stat = VID_SetFullDIBMode(modenum);
300 //              usingmouse = true;
301 //              IN_ActivateMouse ();
302 //              IN_HideMouse ();
303         }
304         else
305                 Sys_Error ("VID_SetMode: Bad mode type in modelist");
306
307         window_width = DIBWidth;
308         window_height = DIBHeight;
309         VID_UpdateWindowStatus ();
310
311         CDAudio_Resume ();
312         scr_disabled_for_loading = temp;
313
314         if (!stat)
315                 Sys_Error ("Couldn't set video mode");
316
317 // now we try to make sure we get the focus on the mode switch, because
318 // sometimes in some systems we don't.  We grab the foreground, then
319 // finish setting up, pump all our messages, and sleep for a little while
320 // to let messages finish bouncing around the system, then we put
321 // ourselves at the top of the z order, then grab the foreground again,
322 // Who knows if it helps, but it probably doesn't hurt
323         SetForegroundWindow (mainwindow);
324         vid_modenum = modenum;
325         Cvar_SetValue ("vid_mode", (float)vid_modenum);
326
327         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
328         {
329         TranslateMessage (&msg);
330         DispatchMessage (&msg);
331         }
332
333         Sleep (100);
334
335         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
336
337         SetForegroundWindow (mainwindow);
338
339 // fix the leftover Alt from any Alt-Tab or the like that switched us away
340         ClearAllStates ();
341
342         if (!msg_suppress_1)
343                 Con_SafePrintf ("Video mode %s initialized.\n", VID_GetModeDescription (vid_modenum));
344
345         vid.recalc_refdef = 1;
346
347         return true;
348 }
349
350
351 /*
352 ================
353 VID_UpdateWindowStatus
354 ================
355 */
356 void VID_UpdateWindowStatus (void)
357 {
358
359         window_rect.left = window_x;
360         window_rect.top = window_y;
361         window_rect.right = window_x + window_width;
362         window_rect.bottom = window_y + window_height;
363         window_center_x = (window_rect.left + window_rect.right) / 2;
364         window_center_y = (window_rect.top + window_rect.bottom) / 2;
365
366         IN_UpdateClipCursor ();
367 }
368
369
370 //====================================
371
372 void VID_CheckMultitexture(void) 
373 {
374         qglMTexCoord2f = NULL;
375         qglSelectTexture = NULL;
376         gl_mtexable = false;
377         // Check to see if multitexture is disabled
378         if (COM_CheckParm("-nomtex"))
379         {
380                 Con_Printf("...multitexture disabled\n");
381                 return;
382         }
383         // Test for ARB_multitexture
384         if (!COM_CheckParm("-SGISmtex") && strstr(gl_extensions, "GL_ARB_multitexture "))
385         {
386                 Con_Printf("...using GL_ARB_multitexture\n");
387                 qglMTexCoord2f = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
388                 qglSelectTexture = (void *) wglGetProcAddress("glActiveTextureARB");
389                 gl_mtexable = true;
390                 gl_mtex_enum = GL_TEXTURE0_ARB;
391         }
392         else if (strstr(gl_extensions, "GL_SGIS_multitexture ")) // Test for SGIS_multitexture (if ARB_multitexture not found)
393         {
394                 Con_Printf("...using GL_SGIS_multitexture\n");
395                 qglMTexCoord2f = (void *) wglGetProcAddress("glMTexCoord2fSGIS");
396                 qglSelectTexture = (void *) wglGetProcAddress("glSelectTextureSGIS");
397                 gl_mtexable = true;
398                 gl_mtex_enum = TEXTURE0_SGIS;
399         }
400         else
401                 Con_Printf("...multitexture disabled (not detected)\n");
402 }
403
404 void VID_CheckCVA(void)
405 {
406         qglLockArraysEXT = NULL;
407         qglUnlockArraysEXT = NULL;
408         gl_supportslockarrays = false;
409         if (COM_CheckParm("-nocva"))
410         {
411                 Con_Printf("...compiled vertex arrays disabled\n");
412                 return;
413         }
414         if (strstr(gl_extensions, "GL_EXT_compiled_vertex_array"))
415         {
416                 Con_Printf("...using compiled vertex arrays\n");
417                 qglLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT");
418                 qglUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
419                 gl_supportslockarrays = true;
420         }
421 }
422
423 /*
424 =================
425 GL_BeginRendering
426
427 =================
428 */
429 void GL_BeginRendering (int *x, int *y, int *width, int *height)
430 {
431         *x = *y = 0;
432         *width = WindowRect.right - WindowRect.left;
433         *height = WindowRect.bottom - WindowRect.top;
434
435 //      if (!wglMakeCurrent( maindc, baseRC ))
436 //              Sys_Error ("wglMakeCurrent failed");
437
438 //      glViewport (*x, *y, *width, *height);
439 }
440
441
442 void GL_EndRendering (void)
443 {
444         int usemouse;
445         if (r_render.value && !scr_skipupdate)
446                 SwapBuffers(maindc);
447
448 // handle the mouse state when windowed if that's changed
449         usemouse = false;
450         if (vid_mouse.value && key_dest == key_game)
451                 usemouse = true;
452         if (modestate == MS_FULLDIB)
453                 usemouse = true;
454         if (!ActiveApp)
455                 usemouse = false;
456         if (usemouse)
457         {
458                 if (!usingmouse)
459                 {
460                         usingmouse = true;
461                         IN_ActivateMouse ();
462                         IN_HideMouse();
463                 }
464         }
465         else
466         {
467                 if (usingmouse)
468                 {
469                         usingmouse = false;
470                         IN_DeactivateMouse ();
471                         IN_ShowMouse();
472                 }
473         }
474 }
475
476 void VID_SetDefaultMode (void)
477 {
478         IN_DeactivateMouse ();
479 }
480
481 void VID_RestoreSystemGamma(void);
482
483 void    VID_Shutdown (void)
484 {
485         HGLRC hRC;
486         HDC       hDC;
487         int i;
488         GLuint temp[8192];
489
490         if (vid_initialized)
491         {
492                 vid_canalttab = false;
493                 hRC = wglGetCurrentContext();
494         hDC = wglGetCurrentDC();
495
496         wglMakeCurrent(NULL, NULL);
497
498                 // LordHavoc: free textures before closing (may help NVIDIA)
499                 for (i = 0;i < 8192;i++)
500                         temp[i] = i+1;
501                 glDeleteTextures(8192, temp);
502
503         if (hRC)
504             wglDeleteContext(hRC);
505
506                 if (hDC && mainwindow)
507                         ReleaseDC(mainwindow, hDC);
508
509                 if (modestate == MS_FULLDIB)
510                         ChangeDisplaySettings (NULL, 0);
511
512                 if (maindc && mainwindow)
513                         ReleaseDC (mainwindow, maindc);
514
515                 AppActivate(false, false);
516
517                 VID_RestoreSystemGamma();
518         }
519 }
520
521
522 //==========================================================================
523
524
525 BOOL bSetupPixelFormat(HDC hDC)
526 {
527     static PIXELFORMATDESCRIPTOR pfd = {
528         sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
529         1,                              // version number
530         PFD_DRAW_TO_WINDOW              // support window
531         |  PFD_SUPPORT_OPENGL   // support OpenGL
532         |  PFD_DOUBLEBUFFER ,   // double buffered
533         PFD_TYPE_RGBA,                  // RGBA type
534         24,                             // 24-bit color depth
535         0, 0, 0, 0, 0, 0,               // color bits ignored
536         0,                              // no alpha buffer
537         0,                              // shift bit ignored
538         0,                              // no accumulation buffer
539         0, 0, 0, 0,                     // accum bits ignored
540         32,                             // 32-bit z-buffer      
541         0,                              // no stencil buffer
542         0,                              // no auxiliary buffer
543         PFD_MAIN_PLANE,                 // main layer
544         0,                              // reserved
545         0, 0, 0                         // layer masks ignored
546     };
547     int pixelformat;
548
549     if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
550     {
551         MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
552         return false;
553     }
554
555     if (SetPixelFormat(hDC, pixelformat, &pfd) == false)
556     {
557         MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
558         return false;
559     }
560
561     return true;
562 }
563
564
565
566 byte scantokey[128] =
567 {
568 //      0           1      2     3     4     5       6       7      8         9      A       B           C     D            E           F
569         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'    ,'0'        ,'-'  ,'='         ,K_BACKSPACE,9     , // 0
570         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['    ,']'        ,13   ,K_CTRL      ,'a'        ,'s'   , // 1
571         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT,'\\'       ,'z'  ,'x'         ,'c'        ,'v'   , // 2
572         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2 ,K_F3        ,K_F4       ,K_F5  , // 3
573         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,'-'    ,K_LEFTARROW,'5'  ,K_RIGHTARROW,'+'        ,K_END , // 4
574         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 5
575         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 6
576         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0       // 7
577 };
578
579 /*
580 byte shiftscantokey[128] =
581
582 //      0           1      2     3     4     5       6       7      8         9      A       B           C    D            E           F 
583         0          ,27    ,'!'  ,'@'  ,'#'  ,'$'    ,'%'    ,'^'   ,'&'      ,'*'   ,'('    ,')'        ,'_' ,'+'         ,K_BACKSPACE,9    , // 0
584         'Q'        ,'W'   ,'E'  ,'R'  ,'T'  ,'Y'    ,'U'    ,'I'   ,'O'      ,'P'   ,'{'    ,'}'        ,13  ,K_CTRL      ,'A'        ,'S'  , // 1
585         'D'        ,'F'   ,'G'  ,'H'  ,'J'  ,'K'    ,'L'    ,':'   ,'"'      ,'~'   ,K_SHIFT,'|'        ,'Z' ,'X'         ,'C'        ,'V'  , // 2
586         'B'        ,'N'   ,'M'  ,'<'  ,'>'  ,'?'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2,K_F3        ,K_F4       ,K_F5 , // 3
587         K_F6       ,K_F7  ,K_F8 ,K_F9 ,K_F10,K_PAUSE,0      ,K_HOME,K_UPARROW,K_PGUP,'_'    ,K_LEFTARROW,'%' ,K_RIGHTARROW,'+'        ,K_END, // 4
588         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0   ,0           ,0          ,0    , // 5
589         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0   ,0           ,0          ,0    , // 6
590         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0   ,0           ,0          ,0      // 7 
591 }; 
592 */
593
594 /*
595 =======
596 MapKey
597
598 Map from windows to quake keynums
599 =======
600 */
601 int MapKey (int key, int virtualkey)
602 {
603         key = (key>>16)&255;
604         if (key > 127)
605                 return 0;
606         if (scantokey[key] == 0)
607                 Con_DPrintf("key 0x%02x has no translation\n", key);
608 //      if (scantokey[key] >= 0x20 && scantokey[key] < 0x7F)
609 //              return realchar;
610         return scantokey[key];
611 }
612
613 /*
614 ===================================================================
615
616 MAIN WINDOW
617
618 ===================================================================
619 */
620
621 /*
622 ================
623 ClearAllStates
624 ================
625 */
626 void ClearAllStates (void)
627 {
628         int             i;
629         
630 // send an up event for each key, to make sure the server clears them all
631         for (i=0 ; i<256 ; i++)
632         {
633                 Key_Event (i, false);
634         }
635
636         Key_ClearStates ();
637         IN_ClearStates ();
638 }
639
640 void VID_RestoreGameGamma(void);
641
642 void AppActivate(BOOL fActive, BOOL minimize)
643 /****************************************************************************
644 *
645 * Function:     AppActivate
646 * Parameters:   fActive - True if app is activating
647 *
648 * Description:  If the application is activating, then swap the system
649 *               into SYSPAL_NOSTATIC mode so that our palettes will display
650 *               correctly.
651 *
652 ****************************************************************************/
653 {
654         static BOOL     sound_active;
655
656         ActiveApp = fActive;
657         Minimized = minimize;
658
659 // enable/disable sound on focus gain/loss
660         if (!ActiveApp && sound_active)
661         {
662                 S_BlockSound ();
663                 sound_active = false;
664         }
665         else if (ActiveApp && !sound_active)
666         {
667                 S_UnblockSound ();
668                 sound_active = true;
669         }
670
671         if (fActive)
672         {
673                 if (modestate == MS_FULLDIB)
674                 {
675 //                      usingmouse = true;
676 //                      IN_ActivateMouse ();
677 //                      IN_HideMouse ();
678                         if (vid_canalttab && vid_wassuspended)
679                         {
680                                 vid_wassuspended = false;
681                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
682                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
683                         }
684
685                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
686                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
687                 }
688 //              else if ((modestate == MS_WINDOWED) && vid_mouse.value && key_dest == key_game)
689 //              {
690 //                      usingmouse = true;
691 //                      IN_ActivateMouse ();
692 //                      IN_HideMouse ();
693 //              }
694                 VID_RestoreGameGamma();
695         }
696
697         if (!fActive)
698         {
699                 usingmouse = false;
700                 IN_DeactivateMouse ();
701                 IN_ShowMouse ();
702                 if (modestate == MS_FULLDIB)
703                 {
704 //                      usingmouse = false;
705 //                      IN_DeactivateMouse ();
706 //                      IN_ShowMouse ();
707                         if (vid_canalttab)
708                         { 
709                                 ChangeDisplaySettings (NULL, 0);
710                                 vid_wassuspended = true;
711                         }
712                 }
713 //              else if ((modestate == MS_WINDOWED) && vid_mouse.value)
714 //              {
715 //                      usingmouse = false;
716 //                      IN_DeactivateMouse ();
717 //                      IN_ShowMouse ();
718 //              }
719                 VID_RestoreSystemGamma();
720         }
721 }
722
723 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
724
725 /* main window procedure */
726 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
727 {
728     LONG    lRet = 1;
729         int             fActive, fMinimized, temp;
730         extern unsigned int uiWheelMessage;
731
732         if ( uMsg == uiWheelMessage )
733                 uMsg = WM_MOUSEWHEEL;
734
735     switch (uMsg)
736     {
737                 case WM_KILLFOCUS:
738                         if (modestate == MS_FULLDIB)
739                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
740                         break;
741
742                 case WM_CREATE:
743                         break;
744
745                 case WM_MOVE:
746                         window_x = (int) LOWORD(lParam);
747                         window_y = (int) HIWORD(lParam);
748                         VID_UpdateWindowStatus ();
749                         break;
750
751                 case WM_KEYDOWN:
752                 case WM_SYSKEYDOWN:
753                         Key_Event (MapKey(lParam, wParam), true);
754                         break;
755                         
756                 case WM_KEYUP:
757                 case WM_SYSKEYUP:
758                         Key_Event (MapKey(lParam, wParam), false);
759                         break;
760
761                 case WM_SYSCHAR:
762                 // keep Alt-Space from happening
763                         break;
764
765         // this is complicated because Win32 seems to pack multiple mouse events into
766         // one update sometimes, so we always check all states and look for events
767                 case WM_LBUTTONDOWN:
768                 case WM_LBUTTONUP:
769                 case WM_RBUTTONDOWN:
770                 case WM_RBUTTONUP:
771                 case WM_MBUTTONDOWN:
772                 case WM_MBUTTONUP:
773                 case WM_MOUSEMOVE:
774                         temp = 0;
775
776                         if (wParam & MK_LBUTTON)
777                                 temp |= 1;
778
779                         if (wParam & MK_RBUTTON)
780                                 temp |= 2;
781
782                         if (wParam & MK_MBUTTON)
783                                 temp |= 4;
784
785                         IN_MouseEvent (temp);
786
787                         break;
788
789                 // JACK: This is the mouse wheel with the Intellimouse
790                 // Its delta is either positive or neg, and we generate the proper
791                 // Event.
792                 case WM_MOUSEWHEEL: 
793                         if ((short) HIWORD(wParam) > 0) {
794                                 Key_Event(K_MWHEELUP, true);
795                                 Key_Event(K_MWHEELUP, false);
796                         } else {
797                                 Key_Event(K_MWHEELDOWN, true);
798                                 Key_Event(K_MWHEELDOWN, false);
799                         }
800                         break;
801
802         case WM_SIZE:
803             break;
804
805             case WM_CLOSE:
806                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
807                                 Sys_Quit ();
808
809                 break;
810
811                 case WM_ACTIVATE:
812                         fActive = LOWORD(wParam);
813                         fMinimized = (BOOL) HIWORD(wParam);
814                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
815
816                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
817                         ClearAllStates ();
818
819                         break;
820
821             case WM_DESTROY:
822         {
823                         if (mainwindow)
824                                 DestroyWindow (mainwindow);
825
826             PostQuitMessage (0);
827         }
828         break;
829
830                 case MM_MCINOTIFY:
831             lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
832                         break;
833
834         default:
835             /* pass all unhandled messages to DefWindowProc */
836             lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
837         break;
838     }
839
840     /* return 1 if handled message, 0 if not */
841     return lRet;
842 }
843
844
845 /*
846 =================
847 VID_NumModes
848 =================
849 */
850 int VID_NumModes (void)
851 {
852         return nummodes;
853 }
854
855         
856 /*
857 =================
858 VID_GetModePtr
859 =================
860 */
861 vmode_t *VID_GetModePtr (int modenum)
862 {
863
864         if ((modenum >= 0) && (modenum < nummodes))
865                 return &modelist[modenum];
866         else
867                 return &badmode;
868 }
869
870
871 /*
872 =================
873 VID_GetModeDescription
874 =================
875 */
876 char *VID_GetModeDescription (int mode)
877 {
878         char            *pinfo;
879         vmode_t         *pv;
880         static char     temp[100];
881
882         if ((mode < 0) || (mode >= nummodes))
883                 return NULL;
884
885         if (!leavecurrentmode)
886         {
887                 pv = VID_GetModePtr (mode);
888                 pinfo = pv->modedesc;
889         }
890         else
891         {
892                 sprintf (temp, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
893                 pinfo = temp;
894         }
895
896         return pinfo;
897 }
898
899
900 // KJB: Added this to return the mode driver name in description for console
901
902 char *VID_GetExtModeDescription (int mode)
903 {
904         static char     pinfo[40];
905         vmode_t         *pv;
906
907         if ((mode < 0) || (mode >= nummodes))
908                 return NULL;
909
910         pv = VID_GetModePtr (mode);
911         if (modelist[mode].type == MS_FULLDIB)
912         {
913                 if (!leavecurrentmode)
914                         sprintf(pinfo,"%s fullscreen", pv->modedesc);
915                 else
916                         sprintf (pinfo, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
917         }
918         else
919         {
920                 if (modestate == MS_WINDOWED)
921                         sprintf(pinfo, "%s windowed", pv->modedesc);
922                 else
923                         sprintf(pinfo, "windowed");
924         }
925
926         return pinfo;
927 }
928
929
930 /*
931 =================
932 VID_DescribeCurrentMode_f
933 =================
934 */
935 void VID_DescribeCurrentMode_f (void)
936 {
937         Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum));
938 }
939
940
941 /*
942 =================
943 VID_NumModes_f
944 =================
945 */
946 void VID_NumModes_f (void)
947 {
948
949         if (nummodes == 1)
950                 Con_Printf ("%d video mode is available\n", nummodes);
951         else
952                 Con_Printf ("%d video modes are available\n", nummodes);
953 }
954
955
956 /*
957 =================
958 VID_DescribeMode_f
959 =================
960 */
961 void VID_DescribeMode_f (void)
962 {
963         int             t, modenum;
964         
965         modenum = atoi (Cmd_Argv(1));
966
967         t = leavecurrentmode;
968         leavecurrentmode = 0;
969
970         Con_Printf ("%s\n", VID_GetExtModeDescription (modenum));
971
972         leavecurrentmode = t;
973 }
974
975
976 /*
977 =================
978 VID_DescribeModes_f
979 =================
980 */
981 void VID_DescribeModes_f (void)
982 {
983         int                     i, lnummodes, t;
984         char            *pinfo;
985         vmode_t         *pv;
986
987         lnummodes = VID_NumModes ();
988
989         t = leavecurrentmode;
990         leavecurrentmode = 0;
991
992         for (i=1 ; i<lnummodes ; i++)
993         {
994                 pv = VID_GetModePtr (i);
995                 pinfo = VID_GetExtModeDescription (i);
996                 Con_Printf ("%2d: %s\n", i, pinfo);
997         }
998
999         leavecurrentmode = t;
1000 }
1001
1002 void VID_AddMode(int type, int width, int height, int modenum, int halfscreen, int dib, int fullscreen, int bpp)
1003 {
1004         int i;
1005         if (nummodes >= MAX_MODE_LIST)
1006                 return;
1007         modelist[nummodes].type = type;
1008         modelist[nummodes].width = width;
1009         modelist[nummodes].height = height;
1010         modelist[nummodes].modenum = modenum;
1011         modelist[nummodes].halfscreen = halfscreen;
1012         modelist[nummodes].dib = dib;
1013         modelist[nummodes].fullscreen = fullscreen;
1014         modelist[nummodes].bpp = bpp;
1015         if (bpp == 0)
1016                 sprintf (modelist[nummodes].modedesc, "%dx%d", width, height);
1017         else
1018                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", width, height, bpp);
1019         for (i = 0;i < nummodes;i++)
1020         {
1021                 if (!memcmp(&modelist[i], &modelist[nummodes], sizeof(vmode_t)))
1022                         return;
1023         }
1024         nummodes++;
1025 }
1026
1027 void VID_InitDIB (HINSTANCE hInstance)
1028 {
1029         int w, h;
1030         WNDCLASS                wc;
1031
1032         // Register the frame class
1033     wc.style         = 0;
1034     wc.lpfnWndProc   = (WNDPROC)MainWndProc;
1035     wc.cbClsExtra    = 0;
1036     wc.cbWndExtra    = 0;
1037     wc.hInstance     = hInstance;
1038     wc.hIcon         = 0;
1039     wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
1040         wc.hbrBackground = NULL;
1041     wc.lpszMenuName  = 0;
1042     wc.lpszClassName = "DarkPlaces";
1043
1044     if (!RegisterClass (&wc) )
1045                 Sys_Error ("Couldn't register window class");
1046
1047         /*
1048         modelist[0].type = MS_WINDOWED;
1049
1050         if (COM_CheckParm("-width"))
1051                 modelist[0].width = atoi(com_argv[COM_CheckParm("-width")+1]);
1052         else
1053                 modelist[0].width = 640;
1054
1055         if (modelist[0].width < 320)
1056                 modelist[0].width = 320;
1057
1058         if (COM_CheckParm("-height"))
1059                 modelist[0].height= atoi(com_argv[COM_CheckParm("-height")+1]);
1060         else
1061                 modelist[0].height = modelist[0].width * 240/320;
1062
1063         if (modelist[0].height < 240)
1064                 modelist[0].height = 240;
1065
1066         sprintf (modelist[0].modedesc, "%dx%d", modelist[0].width, modelist[0].height);
1067
1068         modelist[0].modenum = MODE_WINDOWED;
1069         modelist[0].dib = 1;
1070         modelist[0].fullscreen = 0;
1071         modelist[0].halfscreen = 0;
1072         modelist[0].bpp = 0;
1073
1074         nummodes = 1;
1075         */
1076         if (COM_CheckParm("-width"))
1077                 w = atoi(com_argv[COM_CheckParm("-width")+1]);
1078         else
1079                 w = 640;
1080
1081         if (w < 320)
1082                 w = 320;
1083
1084         if (COM_CheckParm("-height"))
1085                 h = atoi(com_argv[COM_CheckParm("-height")+1]);
1086         else
1087                 h = w * 240/320;
1088
1089         if (h < 240)
1090                 h = 240;
1091
1092         VID_AddMode(MS_WINDOWED, w, h, 0, 0, 1, 0, 0);
1093 }
1094
1095
1096 /*
1097 =================
1098 VID_InitFullDIB
1099 =================
1100 */
1101 void VID_InitFullDIB (HINSTANCE hInstance)
1102 {
1103         DEVMODE devmode;
1104 //      int             i;
1105         int             modenum;
1106         int             originalnummodes;
1107 //      int             existingmode;
1108         int             numlowresmodes;
1109         int             j;
1110         int             bpp;
1111         int             done;
1112         BOOL    stat;
1113
1114 // enumerate >8 bpp modes
1115         originalnummodes = nummodes;
1116         modenum = 0;
1117
1118         do
1119         {
1120                 stat = EnumDisplaySettings (NULL, modenum, &devmode);
1121
1122                 if ((devmode.dmBitsPerPel >= 15) && (devmode.dmPelsWidth <= MAXWIDTH) && (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST))
1123                 {
1124                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1125
1126                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
1127                         {
1128                         // if the width is more than twice the height, reduce it by half because this
1129                         // is probably a dual-screen monitor
1130                                 if ((!COM_CheckParm("-noadjustaspect")) && (devmode.dmPelsWidth > (devmode.dmPelsHeight << 1)))
1131                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth >> 1, devmode.dmPelsHeight, 0, 1, 1, 1, devmode.dmBitsPerPel);
1132                                 else
1133                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
1134                                 /*
1135                                 modelist[nummodes].type = MS_FULLDIB;
1136                                 modelist[nummodes].width = devmode.dmPelsWidth;
1137                                 modelist[nummodes].height = devmode.dmPelsHeight;
1138                                 modelist[nummodes].modenum = 0;
1139                                 modelist[nummodes].halfscreen = 0;
1140                                 modelist[nummodes].dib = 1;
1141                                 modelist[nummodes].fullscreen = 1;
1142                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1143                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight, devmode.dmBitsPerPel);
1144
1145                         // if the width is more than twice the height, reduce it by half because this
1146                         // is probably a dual-screen monitor
1147                                 if (!COM_CheckParm("-noadjustaspect"))
1148                                 {
1149                                         if (modelist[nummodes].width > (modelist[nummodes].height << 1))
1150                                         {
1151                                                 modelist[nummodes].width >>= 1;
1152                                                 modelist[nummodes].halfscreen = 1;
1153                                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", modelist[nummodes].width, modelist[nummodes].height, modelist[nummodes].bpp);
1154                                         }
1155                                 }
1156
1157                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1158                                 {
1159                                         if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp == modelist[i].bpp))
1160                                         {
1161                                                 existingmode = 1;
1162                                                 break;
1163                                         }
1164                                 }
1165
1166                                 if (!existingmode)
1167                                         nummodes++;
1168                                 */
1169                         }
1170                 }
1171
1172                 modenum++;
1173         }
1174         while (stat);
1175
1176 // see if there are any low-res modes that aren't being reported
1177         numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]);
1178         bpp = 16;
1179         done = 0;
1180
1181         do
1182         {
1183                 for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++)
1184                 {
1185                         devmode.dmBitsPerPel = bpp;
1186                         devmode.dmPelsWidth = lowresmodes[j].width;
1187                         devmode.dmPelsHeight = lowresmodes[j].height;
1188                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1189
1190                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
1191                                 VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
1192                         /*
1193                         {
1194                                 modelist[nummodes].type = MS_FULLDIB;
1195                                 modelist[nummodes].width = devmode.dmPelsWidth;
1196                                 modelist[nummodes].height = devmode.dmPelsHeight;
1197                                 modelist[nummodes].modenum = 0;
1198                                 modelist[nummodes].halfscreen = 0;
1199                                 modelist[nummodes].dib = 1;
1200                                 modelist[nummodes].fullscreen = 1;
1201                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1202                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight, devmode.dmBitsPerPel);
1203
1204                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1205                                 {
1206                                         if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp == modelist[i].bpp))
1207                                         {
1208                                                 existingmode = 1;
1209                                                 break;
1210                                         }
1211                                 }
1212
1213                                 if (!existingmode)
1214                                         nummodes++;
1215                         }
1216                         */
1217                 }
1218                 switch (bpp)
1219                 {
1220                         case 16:
1221                                 bpp = 32;
1222                                 break;
1223
1224                         case 32:
1225                                 bpp = 24;
1226                                 break;
1227
1228                         case 24:
1229                                 done = 1;
1230                                 break;
1231                 }
1232         }
1233         while (!done);
1234
1235         if (nummodes == originalnummodes)
1236                 Con_SafePrintf ("No fullscreen DIB modes found\n");
1237 }
1238
1239 static int grabsysgamma = true;
1240 WORD systemgammaramps[3][256], currentgammaramps[3][256];
1241
1242 int VID_SetGamma(float prescale, float gamma, float scale, float base)
1243 {
1244         int i;
1245         HDC hdc;
1246         hdc = GetDC (NULL);
1247
1248         BuildGammaTable16(prescale, gamma, scale, base, &currentgammaramps[0][0]);
1249         for (i = 0;i < 256;i++)
1250                 currentgammaramps[1][i] = currentgammaramps[2][i] = currentgammaramps[0][i];
1251
1252         i = SetDeviceGammaRamp(hdc, &currentgammaramps[0][0]);
1253
1254         ReleaseDC (NULL, hdc);
1255         return i; // return success or failure
1256 }
1257
1258 void VID_RestoreGameGamma(void)
1259 {
1260         VID_UpdateGamma(true);
1261 }
1262
1263 void VID_GetSystemGamma(void)
1264 {
1265         HDC hdc;
1266         hdc = GetDC (NULL);
1267
1268         GetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1269
1270         ReleaseDC (NULL, hdc);
1271 }
1272
1273 void VID_RestoreSystemGamma(void)
1274 {
1275         HDC hdc;
1276         hdc = GetDC (NULL);
1277
1278         SetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1279
1280         ReleaseDC (NULL, hdc);
1281 }
1282
1283 /*
1284 ===================
1285 VID_Init
1286 ===================
1287 */
1288 void    VID_Init (void)
1289 {
1290         int             i;
1291 //      int             existingmode;
1292         int             basenummodes, width, height, bpp, findbpp, done;
1293         HDC             hdc;
1294         DEVMODE devmode;
1295
1296         memset(&devmode, 0, sizeof(devmode));
1297
1298 //      Cvar_RegisterVariable (&_vid_default_mode);
1299 //      Cvar_RegisterVariable (&_vid_default_mode_win);
1300
1301         Cmd_AddCommand ("vid_nummodes", VID_NumModes_f);
1302         Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f);
1303         Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f);
1304         Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f);
1305
1306         VID_GetSystemGamma();
1307
1308         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON2));
1309
1310         InitCommonControls();
1311
1312         VID_InitDIB (global_hInstance);
1313         basenummodes = nummodes = 1;
1314
1315         VID_InitFullDIB (global_hInstance);
1316
1317         if (COM_CheckParm("-window"))
1318         {
1319                 hdc = GetDC (NULL);
1320
1321                 if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)
1322                         Sys_Error ("Can't run in non-RGB mode");
1323
1324                 ReleaseDC (NULL, hdc);
1325
1326                 windowed = true;
1327
1328                 vid_default = MODE_WINDOWED;
1329         }
1330         else
1331         {
1332                 if (nummodes == 1)
1333                         Sys_Error ("No RGB fullscreen modes available");
1334
1335                 windowed = false;
1336
1337                 if (COM_CheckParm("-mode"))
1338                         vid_default = atoi(com_argv[COM_CheckParm("-mode")+1]);
1339                 else
1340                 {
1341                         if (COM_CheckParm("-current"))
1342                         {
1343                                 modelist[MODE_FULLSCREEN_DEFAULT].width = GetSystemMetrics (SM_CXSCREEN);
1344                                 modelist[MODE_FULLSCREEN_DEFAULT].height = GetSystemMetrics (SM_CYSCREEN);
1345                                 vid_default = MODE_FULLSCREEN_DEFAULT;
1346                                 leavecurrentmode = 1;
1347                         }
1348                         else
1349                         {
1350                                 if (COM_CheckParm("-width"))
1351                                         width = atoi(com_argv[COM_CheckParm("-width")+1]);
1352                                 else
1353                                         width = 640;
1354
1355                                 if (COM_CheckParm("-bpp"))
1356                                 {
1357                                         bpp = atoi(com_argv[COM_CheckParm("-bpp")+1]);
1358                                         findbpp = 0;
1359                                 }
1360                                 else
1361                                 {
1362                                         bpp = 15;
1363                                         findbpp = 1;
1364                                 }
1365
1366                                 if (COM_CheckParm("-height"))
1367                                         height = atoi(com_argv[COM_CheckParm("-height")+1]);
1368
1369                         // if they want to force it, add the specified mode to the list
1370                                 if (COM_CheckParm("-force") && (nummodes < MAX_MODE_LIST))
1371                                         VID_AddMode(MS_FULLDIB, width, height, 0, 0, 1, 1, bpp);
1372                                 /*
1373                                 {
1374                                         modelist[nummodes].type = MS_FULLDIB;
1375                                         modelist[nummodes].width = width;
1376                                         modelist[nummodes].height = height;
1377                                         modelist[nummodes].modenum = 0;
1378                                         modelist[nummodes].halfscreen = 0;
1379                                         modelist[nummodes].dib = 1;
1380                                         modelist[nummodes].fullscreen = 1;
1381                                         modelist[nummodes].bpp = bpp;
1382                                         sprintf (modelist[nummodes].modedesc, "%dx%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight, devmode.dmBitsPerPel);
1383
1384                                         for (i=nummodes, existingmode = 0 ; i<nummodes ; i++)
1385                                         {
1386                                                 if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp == modelist[i].bpp))
1387                                                 {
1388                                                         existingmode = 1;
1389                                                         break;
1390                                                 }
1391                                         }
1392
1393                                         if (!existingmode)
1394                                                 nummodes++;
1395                                 }
1396                                 */
1397
1398                                 done = 0;
1399
1400                                 do
1401                                 {
1402                                         if (COM_CheckParm("-height"))
1403                                         {
1404                                                 height = atoi(com_argv[COM_CheckParm("-height")+1]);
1405
1406                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1407                                                 {
1408                                                         if ((modelist[i].width == width) && (modelist[i].height == height) && (modelist[i].bpp == bpp))
1409                                                         {
1410                                                                 vid_default = i;
1411                                                                 done = 1;
1412                                                                 break;
1413                                                         }
1414                                                 }
1415                                         }
1416                                         else
1417                                         {
1418                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1419                                                 {
1420                                                         if ((modelist[i].width == width) && (modelist[i].bpp == bpp))
1421                                                         {
1422                                                                 vid_default = i;
1423                                                                 done = 1;
1424                                                                 break;
1425                                                         }
1426                                                 }
1427                                         }
1428
1429                                         if (!done)
1430                                         {
1431                                                 if (findbpp)
1432                                                 {
1433                                                         switch (bpp)
1434                                                         {
1435                                                         case 15: bpp = 16;break;
1436                                                         case 16: bpp = 32;break;
1437                                                         case 32: bpp = 24;break;
1438                                                         case 24: done = 1;break;
1439                                                         }
1440                                                 }
1441                                                 else
1442                                                         done = 1;
1443                                         }
1444                                 }
1445                                 while (!done);
1446
1447                                 if (!vid_default)
1448                                         Sys_Error ("Specified video mode not available");
1449                         }
1450                 }
1451         }
1452
1453         vid_initialized = true;
1454
1455         if ((i = COM_CheckParm("-conwidth")) != 0)
1456                 vid.conwidth = atoi(com_argv[i+1]);
1457         else
1458                 vid.conwidth = 640;
1459
1460         vid.conwidth &= 0xfff8; // make it a multiple of eight
1461
1462         if (vid.conwidth < 320)
1463                 vid.conwidth = 320;
1464
1465         // pick a conheight that matches with correct aspect
1466         vid.conheight = vid.conwidth*3 / 4;
1467
1468         if ((i = COM_CheckParm("-conheight")) != 0)
1469                 vid.conheight = atoi(com_argv[i+1]);
1470         if (vid.conheight < 200)
1471                 vid.conheight = 200;
1472
1473         VID_SetMode (vid_default);
1474
1475         maindc = GetDC(mainwindow);
1476         bSetupPixelFormat(maindc);
1477
1478         baseRC = wglCreateContext( maindc );
1479         if (!baseRC)
1480                 Sys_Error ("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.");
1481         if (!wglMakeCurrent( maindc, baseRC ))
1482                 Sys_Error ("wglMakeCurrent failed");
1483
1484         GL_Init ();
1485
1486         // LordHavoc: special differences for ATI (broken 8bit color when also using 32bit? weird!)
1487         if (strncasecmp(gl_vendor,"ATI",3)==0)
1488         {
1489                 if (strncasecmp(gl_renderer,"Rage Pro",8)==0)
1490                         isRagePro = true;
1491         }
1492         if (strncasecmp(gl_renderer,"Matrox G200 Direct3D",20)==0) // a D3D driver for GL? sigh...
1493                 isG200 = true;
1494
1495 //      sprintf (gldir, "%s/glquake", com_gamedir);
1496 //      Sys_mkdir (gldir);
1497
1498         vid_realmode = vid_modenum;
1499
1500         vid_menudrawfn = VID_MenuDraw;
1501         vid_menukeyfn = VID_MenuKey;
1502
1503         strcpy (badmode.modedesc, "Bad mode");
1504         vid_canalttab = true;
1505 }
1506
1507
1508 //========================================================
1509 // Video menu stuff
1510 //========================================================
1511
1512 extern void M_Menu_Options_f (void);
1513 extern void M_Print (int cx, int cy, char *str);
1514 extern void M_PrintWhite (int cx, int cy, char *str);
1515 extern void M_DrawCharacter (int cx, int line, int num);
1516 extern void M_DrawPic (int x, int y, qpic_t *pic);
1517
1518 static int      vid_line, vid_wmodes;
1519
1520 typedef struct
1521 {
1522         int             modenum;
1523         char    *desc;
1524         int             iscur;
1525 } modedesc_t;
1526
1527 #define MAX_COLUMN_SIZE         9
1528 #define MODE_AREA_HEIGHT        (MAX_COLUMN_SIZE + 2)
1529 #define MAX_MODEDESCS           (MAX_COLUMN_SIZE*3)
1530
1531 static modedesc_t       modedescs[MAX_MODEDESCS];
1532
1533 /*
1534 ================
1535 VID_MenuDraw
1536 ================
1537 */
1538 void VID_MenuDraw (void)
1539 {
1540         qpic_t          *p;
1541         char            *ptr;
1542         int                     lnummodes, i, k, column, row;
1543         vmode_t         *pv;
1544
1545         p = Draw_CachePic ("gfx/vidmodes.lmp");
1546         M_DrawPic ( (320-p->width)/2, 4, p);
1547
1548         vid_wmodes = 0;
1549         lnummodes = VID_NumModes ();
1550         
1551         for (i=1 ; (i<lnummodes) && (vid_wmodes < MAX_MODEDESCS) ; i++)
1552         {
1553                 ptr = VID_GetModeDescription (i);
1554                 pv = VID_GetModePtr (i);
1555
1556                 k = vid_wmodes;
1557
1558                 modedescs[k].modenum = i;
1559                 modedescs[k].desc = ptr;
1560                 modedescs[k].iscur = 0;
1561
1562                 if (i == vid_modenum)
1563                         modedescs[k].iscur = 1;
1564
1565                 vid_wmodes++;
1566
1567         }
1568
1569         if (vid_wmodes > 0)
1570         {
1571                 M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)");
1572
1573                 column = 8;
1574                 row = 36+2*8;
1575
1576                 for (i=0 ; i<vid_wmodes ; i++)
1577                 {
1578                         if (modedescs[i].iscur)
1579                                 M_PrintWhite (column, row, modedescs[i].desc);
1580                         else
1581                                 M_Print (column, row, modedescs[i].desc);
1582
1583                         column += 13*8;
1584
1585                         if ((i % VID_ROW_SIZE) == (VID_ROW_SIZE - 1))
1586                         {
1587                                 column = 8;
1588                                 row += 8;
1589                         }
1590                 }
1591         }
1592
1593         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*2, "Video modes must be set from the");
1594         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "command line with -width <width>");
1595         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, "and -bpp <bits-per-pixel>");
1596         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Select windowed mode with -window");
1597 }
1598
1599
1600 /*
1601 ================
1602 VID_MenuKey
1603 ================
1604 */
1605 void VID_MenuKey (int key)
1606 {
1607         switch (key)
1608         {
1609         case K_ESCAPE:
1610                 S_LocalSound ("misc/menu1.wav");
1611                 M_Menu_Options_f ();
1612                 break;
1613
1614         default:
1615                 break;
1616         }
1617 }