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