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