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