renamed byte to qbyte throughout engine to eliminate a mingw conflict
[divverent/darkplaces.git] / vid_wgl.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // gl_vidnt.c -- NT GL vid component
21
22 #include "quakedef.h"
23 #include "winquake.h"
24 #include "resource.h"
25 #include <commctrl.h>
26
27 #define MAX_MODE_LIST   30
28 #define VID_ROW_SIZE    3
29 #define MAXWIDTH                10000
30 #define MAXHEIGHT               10000
31
32 #define MODE_WINDOWED                   0
33 #define NO_MODE                                 (MODE_WINDOWED - 1)
34 #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 1)
35
36 typedef struct {
37         modestate_t     type;
38         int                     width;
39         int                     height;
40         int                     modenum;
41         int                     dib;
42         int                     fullscreen;
43         int                     bpp;
44         int                     halfscreen;
45         char            modedesc[17];
46 } vmode_t;
47
48 typedef struct {
49         int                     width;
50         int                     height;
51 } lmode_t;
52
53 lmode_t lowresmodes[] = {
54         {320, 200},
55         {320, 240},
56         {400, 300},
57         {512, 384},
58 };
59
60 const char *gl_vendor;
61 const char *gl_renderer;
62 const char *gl_version;
63 const char *gl_extensions;
64
65 qboolean                scr_skipupdate;
66
67 static vmode_t  modelist[MAX_MODE_LIST];
68 static int              nummodes;
69 //static vmode_t        *pcurrentmode;
70 static vmode_t  badmode;
71
72 static DEVMODE  gdevmode;
73 static qboolean vid_initialized = false;
74 static qboolean windowed, leavecurrentmode;
75 static qboolean vid_canalttab = false;
76 static qboolean vid_wassuspended = false;
77 static int              usingmouse;
78 extern qboolean mouseactive;  // from in_win.c
79 static HICON    hIcon;
80
81 int                     DIBWidth, DIBHeight;
82 RECT            WindowRect;
83 DWORD           WindowStyle, ExWindowStyle;
84
85 HWND    mainwindow;
86
87 int                     vid_modenum = NO_MODE;
88 int                     vid_realmode;
89 int                     vid_default = MODE_WINDOWED;
90 static int      windowed_default;
91 unsigned char   vid_curpal[256*3];
92
93 HGLRC   baseRC;
94 HDC             maindc;
95
96 HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow);
97
98 viddef_t        vid;                            // global video state
99
100 float           gldepthmin, gldepthmax;
101
102 modestate_t     modestate = MS_UNINIT;
103
104 void VID_MenuDraw (void);
105 void VID_MenuKey (int key);
106
107 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
108 void AppActivate(BOOL fActive, BOOL minimize);
109 char *VID_GetModeDescription (int mode);
110 void ClearAllStates (void);
111 void VID_UpdateWindowStatus (void);
112
113 //====================================
114
115 // Note that 0 is MODE_WINDOWED
116 //cvar_t                _vid_default_mode = {"_vid_default_mode","0", true};
117 // Note that 3 is MODE_FULLSCREEN_DEFAULT
118 //cvar_t                _vid_default_mode_win = {"_vid_default_mode_win","3", true};
119
120 int                     window_center_x, window_center_y, window_x, window_y, window_width, window_height;
121 RECT            window_rect;
122
123 // direct draw software compatability stuff
124
125 void CenterWindow(HWND hWndCenter, int width, int height, BOOL lefttopjustify)
126 {
127     int     CenterX, CenterY;
128
129         CenterX = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
130         CenterY = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
131         if (CenterX > CenterY*2)
132                 CenterX >>= 1;  // dual screens
133         CenterX = (CenterX < 0) ? 0: CenterX;
134         CenterY = (CenterY < 0) ? 0: CenterY;
135         SetWindowPos (hWndCenter, NULL, CenterX, CenterY, 0, 0,
136                         SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
137 }
138
139 qboolean VID_SetWindowedMode (int modenum)
140 {
141         int                             lastmodestate, width, height;
142         RECT                    rect;
143
144         lastmodestate = modestate;
145
146         WindowRect.top = WindowRect.left = 0;
147
148         WindowRect.right = modelist[modenum].width;
149         WindowRect.bottom = modelist[modenum].height;
150
151         DIBWidth = modelist[modenum].width;
152         DIBHeight = modelist[modenum].height;
153
154         WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
155         ExWindowStyle = 0;
156
157         rect = WindowRect;
158         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
159
160         width = rect.right - rect.left;
161         height = rect.bottom - rect.top;
162
163         // Create the DIB window
164         mainwindow = CreateWindowEx (ExWindowStyle, gamename, gamename, WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
165
166         if (!mainwindow)
167                 Sys_Error ("Couldn't create DIB window");
168
169         // Center and show the DIB window
170         CenterWindow(mainwindow, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, false);
171
172         ShowWindow (mainwindow, SW_SHOWDEFAULT);
173         UpdateWindow (mainwindow);
174
175         modestate = MS_WINDOWED;
176
177         if (vid.conheight > modelist[modenum].height)
178                 vid.conheight = modelist[modenum].height;
179         if (vid.conwidth > modelist[modenum].width)
180                 vid.conwidth = modelist[modenum].width;
181
182         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
183         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
184
185         return true;
186 }
187
188
189 qboolean VID_SetFullDIBMode (int modenum)
190 {
191         int                             lastmodestate, width, height;
192         RECT                    rect;
193
194         if (!leavecurrentmode)
195         {
196                 gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
197                 gdevmode.dmBitsPerPel = modelist[modenum].bpp;
198                 gdevmode.dmPelsWidth = modelist[modenum].width <<
199                                                            modelist[modenum].halfscreen;
200                 gdevmode.dmPelsHeight = modelist[modenum].height;
201                 gdevmode.dmSize = sizeof (gdevmode);
202
203                 if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
204                         Sys_Error ("Couldn't set fullscreen DIB mode");
205         }
206
207         lastmodestate = modestate;
208         modestate = MS_FULLDIB;
209
210         WindowRect.top = WindowRect.left = 0;
211
212         WindowRect.right = modelist[modenum].width;
213         WindowRect.bottom = modelist[modenum].height;
214
215         DIBWidth = modelist[modenum].width;
216         DIBHeight = modelist[modenum].height;
217
218         WindowStyle = WS_POPUP;
219         ExWindowStyle = 0;
220
221         rect = WindowRect;
222         AdjustWindowRectEx(&rect, WindowStyle, false, 0);
223
224         width = rect.right - rect.left;
225         height = rect.bottom - rect.top;
226
227         // Create the DIB window
228         mainwindow = CreateWindowEx (ExWindowStyle, gamename, gamename, WindowStyle, rect.left, rect.top, width, height, NULL, NULL, global_hInstance, NULL);
229
230         if (!mainwindow)
231                 Sys_Error ("Couldn't create DIB window");
232
233         ShowWindow (mainwindow, SW_SHOWDEFAULT);
234         UpdateWindow (mainwindow);
235
236         if (vid.conheight > modelist[modenum].height)
237                 vid.conheight = modelist[modenum].height;
238         if (vid.conwidth > modelist[modenum].width)
239                 vid.conwidth = modelist[modenum].width;
240
241 // needed because we're not getting WM_MOVE messages fullscreen on NT
242         window_x = 0;
243         window_y = 0;
244
245         SendMessage (mainwindow, WM_SETICON, (WPARAM)true, (LPARAM)hIcon);
246         SendMessage (mainwindow, WM_SETICON, (WPARAM)false, (LPARAM)hIcon);
247
248         return true;
249 }
250
251
252 int VID_SetMode (int modenum)
253 {
254         int                             original_mode, temp;
255         qboolean                stat = 0;
256     MSG                         msg;
257
258         if ((windowed && (modenum != 0)) || (!windowed && (modenum < 1)) || (!windowed && (modenum >= nummodes)))
259                 Sys_Error ("Bad video mode\n");
260
261 // so Con_Printfs don't mess us up by forcing vid and snd updates
262         temp = scr_disabled_for_loading;
263         scr_disabled_for_loading = true;
264
265         CDAudio_Pause ();
266
267         if (vid_modenum == NO_MODE)
268                 original_mode = windowed_default;
269         else
270                 original_mode = vid_modenum;
271
272         // Set either the fullscreen or windowed mode
273         if (modelist[modenum].type == MS_WINDOWED)
274         {
275 //              if (vid_mouse.integer && key_dest == key_game)
276 //              {
277 //                      stat = VID_SetWindowedMode(modenum);
278 //                      usingmouse = true;
279 //                      IN_ActivateMouse ();
280 //                      IN_HideMouse ();
281 //              }
282 //              else
283 //              {
284 //                      usingmouse = false;
285 //                      IN_DeactivateMouse ();
286 //                      IN_ShowMouse ();
287 //                      stat = VID_SetWindowedMode(modenum);
288 //              }
289                 stat = VID_SetWindowedMode(modenum);
290         }
291         else if (modelist[modenum].type == MS_FULLDIB)
292         {
293                 stat = VID_SetFullDIBMode(modenum);
294 //              usingmouse = true;
295 //              IN_ActivateMouse ();
296 //              IN_HideMouse ();
297         }
298         else
299                 Sys_Error ("VID_SetMode: Bad mode type in modelist");
300
301         window_width = DIBWidth;
302         window_height = DIBHeight;
303         VID_UpdateWindowStatus ();
304
305         CDAudio_Resume ();
306         scr_disabled_for_loading = temp;
307
308         if (!stat)
309                 Sys_Error ("Couldn't set video mode");
310
311 // now we try to make sure we get the focus on the mode switch, because
312 // sometimes in some systems we don't.  We grab the foreground, then
313 // finish setting up, pump all our messages, and sleep for a little while
314 // to let messages finish bouncing around the system, then we put
315 // ourselves at the top of the z order, then grab the foreground again,
316 // Who knows if it helps, but it probably doesn't hurt
317         SetForegroundWindow (mainwindow);
318         vid_modenum = modenum;
319         Cvar_SetValue ("vid_mode", (float)vid_modenum);
320
321         while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
322         {
323         TranslateMessage (&msg);
324         DispatchMessage (&msg);
325         }
326
327         Sleep (100);
328
329         SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
330
331         SetForegroundWindow (mainwindow);
332
333 // fix the leftover Alt from any Alt-Tab or the like that switched us away
334         ClearAllStates ();
335
336         if (!msg_suppress_1)
337                 Con_SafePrintf ("Video mode %s initialized.\n", VID_GetModeDescription (vid_modenum));
338
339 //      vid.recalc_refdef = 1;
340
341         return true;
342 }
343
344
345 /*
346 ================
347 VID_UpdateWindowStatus
348 ================
349 */
350 void VID_UpdateWindowStatus (void)
351 {
352
353         window_rect.left = window_x;
354         window_rect.top = window_y;
355         window_rect.right = window_x + window_width;
356         window_rect.bottom = window_y + window_height;
357         window_center_x = (window_rect.left + window_rect.right) / 2;
358         window_center_y = (window_rect.top + window_rect.bottom) / 2;
359
360         IN_UpdateClipCursor ();
361 }
362
363
364 //====================================
365
366 /*
367 =================
368 VID_GetWindowSize
369 =================
370 */
371 void VID_GetWindowSize (int *x, int *y, int *width, int *height)
372 {
373         *x = *y = 0;
374         *width = WindowRect.right - WindowRect.left;
375         *height = WindowRect.bottom - WindowRect.top;
376 }
377
378
379 void VID_Finish (void)
380 {
381         int usemouse;
382         if (r_render.integer && !scr_skipupdate)
383         {
384                 glFinish();
385                 SwapBuffers(maindc);
386         }
387
388 // handle the mouse state when windowed if that's changed
389         usemouse = false;
390         if (vid_mouse.integer && key_dest == key_game)
391                 usemouse = true;
392         if (modestate == MS_FULLDIB)
393                 usemouse = true;
394         if (!ActiveApp)
395                 usemouse = false;
396         if (usemouse)
397         {
398                 if (!usingmouse)
399                 {
400                         usingmouse = true;
401                         IN_ActivateMouse ();
402                         IN_HideMouse();
403                 }
404         }
405         else
406         {
407                 if (usingmouse)
408                 {
409                         usingmouse = false;
410                         IN_DeactivateMouse ();
411                         IN_ShowMouse();
412                 }
413         }
414 }
415
416 void VID_SetDefaultMode (void)
417 {
418         IN_DeactivateMouse ();
419 }
420
421 void VID_RestoreSystemGamma(void);
422
423 void    VID_Shutdown (void)
424 {
425         HGLRC hRC;
426         HDC       hDC;
427         int i;
428         GLuint temp[8192];
429
430         if (vid_initialized)
431         {
432                 vid_canalttab = false;
433                 hRC = wglGetCurrentContext();
434         hDC = wglGetCurrentDC();
435
436         wglMakeCurrent(NULL, NULL);
437
438                 // LordHavoc: free textures before closing (may help NVIDIA)
439                 for (i = 0;i < 8192;i++)
440                         temp[i] = i+1;
441                 glDeleteTextures(8192, temp);
442
443         if (hRC)
444             wglDeleteContext(hRC);
445
446                 if (hDC && mainwindow)
447                         ReleaseDC(mainwindow, hDC);
448
449                 if (modestate == MS_FULLDIB)
450                         ChangeDisplaySettings (NULL, 0);
451
452                 if (maindc && mainwindow)
453                         ReleaseDC (mainwindow, maindc);
454
455                 AppActivate(false, false);
456
457                 VID_RestoreSystemGamma();
458         }
459 }
460
461
462 //==========================================================================
463
464
465 BOOL bSetupPixelFormat(HDC hDC)
466 {
467     static PIXELFORMATDESCRIPTOR pfd = {
468         sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
469         1,                              // version number
470         PFD_DRAW_TO_WINDOW              // support window
471         |  PFD_SUPPORT_OPENGL   // support OpenGL
472         |  PFD_DOUBLEBUFFER ,   // double buffered
473         PFD_TYPE_RGBA,                  // RGBA type
474         24,                             // 24-bit color depth
475         0, 0, 0, 0, 0, 0,               // color bits ignored
476         0,                              // no alpha buffer
477         0,                              // shift bit ignored
478         0,                              // no accumulation buffer
479         0, 0, 0, 0,                     // accum bits ignored
480         32,                             // 32-bit z-buffer      
481         0,                              // no stencil buffer
482         0,                              // no auxiliary buffer
483         PFD_MAIN_PLANE,                 // main layer
484         0,                              // reserved
485         0, 0, 0                         // layer masks ignored
486     };
487     int pixelformat;
488
489     if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
490     {
491         MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
492         return false;
493     }
494
495     if (SetPixelFormat(hDC, pixelformat, &pfd) == false)
496     {
497         MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
498         return false;
499     }
500
501     return true;
502 }
503
504
505
506 qbyte scantokey[128] =
507 {
508 //      0           1      2     3     4     5       6       7      8         9      A       B           C     D            E           F
509         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'    ,'0'        ,'-'  ,'='         ,K_BACKSPACE,9     , // 0
510         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['    ,']'        ,13   ,K_CTRL      ,'a'        ,'s'   , // 1
511         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT,'\\'       ,'z'  ,'x'         ,'c'        ,'v'   , // 2
512         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2 ,K_F3        ,K_F4       ,K_F5  , // 3
513         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
514         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 5
515         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 6
516         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0       // 7
517 };
518
519 /*
520 qbyte shiftscantokey[128] =
521
522 //      0           1      2     3     4     5       6       7      8         9      A       B           C    D            E           F 
523         0          ,27    ,'!'  ,'@'  ,'#'  ,'$'    ,'%'    ,'^'   ,'&'      ,'*'   ,'('    ,')'        ,'_' ,'+'         ,K_BACKSPACE,9    , // 0
524         'Q'        ,'W'   ,'E'  ,'R'  ,'T'  ,'Y'    ,'U'    ,'I'   ,'O'      ,'P'   ,'{'    ,'}'        ,13  ,K_CTRL      ,'A'        ,'S'  , // 1
525         'D'        ,'F'   ,'G'  ,'H'  ,'J'  ,'K'    ,'L'    ,':'   ,'"'      ,'~'   ,K_SHIFT,'|'        ,'Z' ,'X'         ,'C'        ,'V'  , // 2
526         'B'        ,'N'   ,'M'  ,'<'  ,'>'  ,'?'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2,K_F3        ,K_F4       ,K_F5 , // 3
527         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
528         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0   ,0           ,0          ,0    , // 5
529         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0   ,0           ,0          ,0    , // 6
530         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0   ,0           ,0          ,0      // 7 
531 }; 
532 */
533
534 /*
535 =======
536 MapKey
537
538 Map from windows to quake keynums
539 =======
540 */
541 int MapKey (int key, int virtualkey)
542 {
543         key = (key>>16)&255;
544         if (key > 127)
545                 return 0;
546         if (scantokey[key] == 0)
547                 Con_DPrintf("key 0x%02x has no translation\n", key);
548 //      if (scantokey[key] >= 0x20 && scantokey[key] < 0x7F)
549 //              return realchar;
550         return scantokey[key];
551 }
552
553 /*
554 ===================================================================
555
556 MAIN WINDOW
557
558 ===================================================================
559 */
560
561 /*
562 ================
563 ClearAllStates
564 ================
565 */
566 void ClearAllStates (void)
567 {
568         int             i;
569         
570 // send an up event for each key, to make sure the server clears them all
571         for (i=0 ; i<256 ; i++)
572         {
573                 Key_Event (i, false);
574         }
575
576         Key_ClearStates ();
577         IN_ClearStates ();
578 }
579
580 void VID_RestoreGameGamma(void);
581 extern qboolean host_loopactive;
582
583 void AppActivate(BOOL fActive, BOOL minimize)
584 /****************************************************************************
585 *
586 * Function:     AppActivate
587 * Parameters:   fActive - True if app is activating
588 *
589 * Description:  If the application is activating, then swap the system
590 *               into SYSPAL_NOSTATIC mode so that our palettes will display
591 *               correctly.
592 *
593 ****************************************************************************/
594 {
595         static BOOL     sound_active;
596
597         ActiveApp = fActive;
598         Minimized = minimize;
599
600 // enable/disable sound on focus gain/loss
601         if (!ActiveApp && sound_active)
602         {
603                 S_BlockSound ();
604                 sound_active = false;
605         }
606         else if (ActiveApp && !sound_active)
607         {
608                 S_UnblockSound ();
609                 sound_active = true;
610         }
611
612         if (fActive)
613         {
614                 if (modestate == MS_FULLDIB)
615                 {
616 //                      usingmouse = true;
617 //                      IN_ActivateMouse ();
618 //                      IN_HideMouse ();
619                         if (vid_canalttab && vid_wassuspended)
620                         {
621                                 vid_wassuspended = false;
622                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
623                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
624                         }
625
626                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
627                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
628                 }
629 //              else if ((modestate == MS_WINDOWED) && vid_mouse.integer && key_dest == key_game)
630 //              {
631 //                      usingmouse = true;
632 //                      IN_ActivateMouse ();
633 //                      IN_HideMouse ();
634 //              }
635                 if (host_loopactive)
636                         VID_RestoreGameGamma();
637         }
638
639         if (!fActive)
640         {
641                 usingmouse = false;
642                 IN_DeactivateMouse ();
643                 IN_ShowMouse ();
644                 if (modestate == MS_FULLDIB)
645                 {
646 //                      usingmouse = false;
647 //                      IN_DeactivateMouse ();
648 //                      IN_ShowMouse ();
649                         if (vid_canalttab)
650                         { 
651                                 ChangeDisplaySettings (NULL, 0);
652                                 vid_wassuspended = true;
653                         }
654                 }
655 //              else if ((modestate == MS_WINDOWED) && vid_mouse.integer)
656 //              {
657 //                      usingmouse = false;
658 //                      IN_DeactivateMouse ();
659 //                      IN_ShowMouse ();
660 //              }
661                 VID_RestoreSystemGamma();
662         }
663 }
664
665 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
666
667 /* main window procedure */
668 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
669 {
670     LONG    lRet = 1;
671         int             fActive, fMinimized, temp;
672         extern unsigned int uiWheelMessage;
673
674         if ( uMsg == uiWheelMessage )
675                 uMsg = WM_MOUSEWHEEL;
676
677     switch (uMsg)
678     {
679                 case WM_KILLFOCUS:
680                         if (modestate == MS_FULLDIB)
681                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
682                         break;
683
684                 case WM_CREATE:
685                         break;
686
687                 case WM_MOVE:
688                         window_x = (int) LOWORD(lParam);
689                         window_y = (int) HIWORD(lParam);
690                         VID_UpdateWindowStatus ();
691                         break;
692
693                 case WM_KEYDOWN:
694                 case WM_SYSKEYDOWN:
695                         Key_Event (MapKey(lParam, wParam), true);
696                         break;
697                         
698                 case WM_KEYUP:
699                 case WM_SYSKEYUP:
700                         Key_Event (MapKey(lParam, wParam), false);
701                         break;
702
703                 case WM_SYSCHAR:
704                 // keep Alt-Space from happening
705                         break;
706
707         // this is complicated because Win32 seems to pack multiple mouse events into
708         // one update sometimes, so we always check all states and look for events
709                 case WM_LBUTTONDOWN:
710                 case WM_LBUTTONUP:
711                 case WM_RBUTTONDOWN:
712                 case WM_RBUTTONUP:
713                 case WM_MBUTTONDOWN:
714                 case WM_MBUTTONUP:
715                 case WM_MOUSEMOVE:
716                         temp = 0;
717
718                         if (wParam & MK_LBUTTON)
719                                 temp |= 1;
720
721                         if (wParam & MK_RBUTTON)
722                                 temp |= 2;
723
724                         if (wParam & MK_MBUTTON)
725                                 temp |= 4;
726
727                         IN_MouseEvent (temp);
728
729                         break;
730
731                 // JACK: This is the mouse wheel with the Intellimouse
732                 // Its delta is either positive or neg, and we generate the proper
733                 // Event.
734                 case WM_MOUSEWHEEL: 
735                         if ((short) HIWORD(wParam) > 0) {
736                                 Key_Event(K_MWHEELUP, true);
737                                 Key_Event(K_MWHEELUP, false);
738                         } else {
739                                 Key_Event(K_MWHEELDOWN, true);
740                                 Key_Event(K_MWHEELDOWN, false);
741                         }
742                         break;
743
744         case WM_SIZE:
745             break;
746
747             case WM_CLOSE:
748                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
749                                 Sys_Quit ();
750
751                 break;
752
753                 case WM_ACTIVATE:
754                         fActive = LOWORD(wParam);
755                         fMinimized = (BOOL) HIWORD(wParam);
756                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
757
758                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
759                         ClearAllStates ();
760
761                         break;
762
763             case WM_DESTROY:
764         {
765                         if (mainwindow)
766                                 DestroyWindow (mainwindow);
767
768             PostQuitMessage (0);
769         }
770         break;
771
772                 case MM_MCINOTIFY:
773             lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
774                         break;
775
776         default:
777             /* pass all unhandled messages to DefWindowProc */
778             lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
779         break;
780     }
781
782     /* return 1 if handled message, 0 if not */
783     return lRet;
784 }
785
786
787 /*
788 =================
789 VID_NumModes
790 =================
791 */
792 int VID_NumModes (void)
793 {
794         return nummodes;
795 }
796
797         
798 /*
799 =================
800 VID_GetModePtr
801 =================
802 */
803 vmode_t *VID_GetModePtr (int modenum)
804 {
805
806         if ((modenum >= 0) && (modenum < nummodes))
807                 return &modelist[modenum];
808         else
809                 return &badmode;
810 }
811
812
813 /*
814 =================
815 VID_GetModeDescription
816 =================
817 */
818 char *VID_GetModeDescription (int mode)
819 {
820         char            *pinfo;
821         vmode_t         *pv;
822         static char     temp[100];
823
824         if ((mode < 0) || (mode >= nummodes))
825                 return NULL;
826
827         if (!leavecurrentmode)
828         {
829                 pv = VID_GetModePtr (mode);
830                 pinfo = pv->modedesc;
831         }
832         else
833         {
834                 sprintf (temp, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
835                 pinfo = temp;
836         }
837
838         return pinfo;
839 }
840
841
842 // KJB: Added this to return the mode driver name in description for console
843
844 char *VID_GetExtModeDescription (int mode)
845 {
846         static char     pinfo[40];
847         vmode_t         *pv;
848
849         if ((mode < 0) || (mode >= nummodes))
850                 return NULL;
851
852         pv = VID_GetModePtr (mode);
853         if (modelist[mode].type == MS_FULLDIB)
854         {
855                 if (!leavecurrentmode)
856                         sprintf(pinfo,"%s fullscreen", pv->modedesc);
857                 else
858                         sprintf (pinfo, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
859         }
860         else
861         {
862                 if (modestate == MS_WINDOWED)
863                         sprintf(pinfo, "%s windowed", pv->modedesc);
864                 else
865                         sprintf(pinfo, "windowed");
866         }
867
868         return pinfo;
869 }
870
871
872 /*
873 =================
874 VID_DescribeCurrentMode_f
875 =================
876 */
877 void VID_DescribeCurrentMode_f (void)
878 {
879         Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum));
880 }
881
882
883 /*
884 =================
885 VID_NumModes_f
886 =================
887 */
888 void VID_NumModes_f (void)
889 {
890
891         if (nummodes == 1)
892                 Con_Printf ("%d video mode is available\n", nummodes);
893         else
894                 Con_Printf ("%d video modes are available\n", nummodes);
895 }
896
897
898 /*
899 =================
900 VID_DescribeMode_f
901 =================
902 */
903 void VID_DescribeMode_f (void)
904 {
905         int             t, modenum;
906         
907         modenum = atoi (Cmd_Argv(1));
908
909         t = leavecurrentmode;
910         leavecurrentmode = 0;
911
912         Con_Printf ("%s\n", VID_GetExtModeDescription (modenum));
913
914         leavecurrentmode = t;
915 }
916
917
918 /*
919 =================
920 VID_DescribeModes_f
921 =================
922 */
923 void VID_DescribeModes_f (void)
924 {
925         int                     i, lnummodes, t;
926         char            *pinfo;
927         vmode_t         *pv;
928
929         lnummodes = VID_NumModes ();
930
931         t = leavecurrentmode;
932         leavecurrentmode = 0;
933
934         for (i=1 ; i<lnummodes ; i++)
935         {
936                 pv = VID_GetModePtr (i);
937                 pinfo = VID_GetExtModeDescription (i);
938                 Con_Printf ("%2d: %s\n", i, pinfo);
939         }
940
941         leavecurrentmode = t;
942 }
943
944 void VID_AddMode(int type, int width, int height, int modenum, int halfscreen, int dib, int fullscreen, int bpp)
945 {
946         int i;
947         if (nummodes >= MAX_MODE_LIST)
948                 return;
949         modelist[nummodes].type = type;
950         modelist[nummodes].width = width;
951         modelist[nummodes].height = height;
952         modelist[nummodes].modenum = modenum;
953         modelist[nummodes].halfscreen = halfscreen;
954         modelist[nummodes].dib = dib;
955         modelist[nummodes].fullscreen = fullscreen;
956         modelist[nummodes].bpp = bpp;
957         if (bpp == 0)
958                 sprintf (modelist[nummodes].modedesc, "%dx%d", width, height);
959         else
960                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", width, height, bpp);
961         for (i = 0;i < nummodes;i++)
962         {
963                 if (!memcmp(&modelist[i], &modelist[nummodes], sizeof(vmode_t)))
964                         return;
965         }
966         nummodes++;
967 }
968
969 void VID_InitDIB (HINSTANCE hInstance)
970 {
971         int w, h;
972         WNDCLASS                wc;
973
974         // Register the frame class
975     wc.style         = 0;
976     wc.lpfnWndProc   = (WNDPROC)MainWndProc;
977     wc.cbClsExtra    = 0;
978     wc.cbWndExtra    = 0;
979     wc.hInstance     = hInstance;
980     wc.hIcon         = 0;
981     wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
982         wc.hbrBackground = NULL;
983     wc.lpszMenuName  = 0;
984     wc.lpszClassName = gamename;
985
986     if (!RegisterClass (&wc) )
987                 Sys_Error ("Couldn't register window class");
988
989         /*
990         modelist[0].type = MS_WINDOWED;
991
992         if (COM_CheckParm("-width"))
993                 modelist[0].width = atoi(com_argv[COM_CheckParm("-width")+1]);
994         else
995                 modelist[0].width = 640;
996
997         if (modelist[0].width < 320)
998                 modelist[0].width = 320;
999
1000         if (COM_CheckParm("-height"))
1001                 modelist[0].height= atoi(com_argv[COM_CheckParm("-height")+1]);
1002         else
1003                 modelist[0].height = modelist[0].width * 240/320;
1004
1005         if (modelist[0].height < 240)
1006                 modelist[0].height = 240;
1007
1008         sprintf (modelist[0].modedesc, "%dx%d", modelist[0].width, modelist[0].height);
1009
1010         modelist[0].modenum = MODE_WINDOWED;
1011         modelist[0].dib = 1;
1012         modelist[0].fullscreen = 0;
1013         modelist[0].halfscreen = 0;
1014         modelist[0].bpp = 0;
1015
1016         nummodes = 1;
1017         */
1018         if (COM_CheckParm("-width"))
1019                 w = atoi(com_argv[COM_CheckParm("-width")+1]);
1020         else
1021                 w = 640;
1022
1023         if (w < 320)
1024                 w = 320;
1025
1026         if (COM_CheckParm("-height"))
1027                 h = atoi(com_argv[COM_CheckParm("-height")+1]);
1028         else
1029                 h = w * 240/320;
1030
1031         if (h < 240)
1032                 h = 240;
1033
1034         VID_AddMode(MS_WINDOWED, w, h, 0, 0, 1, 0, 0);
1035 }
1036
1037
1038 /*
1039 =================
1040 VID_InitFullDIB
1041 =================
1042 */
1043 void VID_InitFullDIB (HINSTANCE hInstance)
1044 {
1045         DEVMODE devmode;
1046 //      int             i;
1047         int             modenum;
1048         int             originalnummodes;
1049 //      int             existingmode;
1050         int             numlowresmodes;
1051         int             j;
1052         int             bpp;
1053         int             done;
1054         BOOL    stat;
1055
1056 // enumerate >8 bpp modes
1057         originalnummodes = nummodes;
1058         modenum = 0;
1059
1060         do
1061         {
1062                 stat = EnumDisplaySettings (NULL, modenum, &devmode);
1063
1064                 if ((devmode.dmBitsPerPel >= 15) && (devmode.dmPelsWidth <= MAXWIDTH) && (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST))
1065                 {
1066                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1067
1068                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
1069                         {
1070                         // if the width is more than twice the height, reduce it by half because this
1071                         // is probably a dual-screen monitor
1072                                 if ((!COM_CheckParm("-noadjustaspect")) && (devmode.dmPelsWidth > (devmode.dmPelsHeight << 1)))
1073                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth >> 1, devmode.dmPelsHeight, 0, 1, 1, 1, devmode.dmBitsPerPel);
1074                                 else
1075                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
1076                                 /*
1077                                 modelist[nummodes].type = MS_FULLDIB;
1078                                 modelist[nummodes].width = devmode.dmPelsWidth;
1079                                 modelist[nummodes].height = devmode.dmPelsHeight;
1080                                 modelist[nummodes].modenum = 0;
1081                                 modelist[nummodes].halfscreen = 0;
1082                                 modelist[nummodes].dib = 1;
1083                                 modelist[nummodes].fullscreen = 1;
1084                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1085                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight, devmode.dmBitsPerPel);
1086
1087                         // if the width is more than twice the height, reduce it by half because this
1088                         // is probably a dual-screen monitor
1089                                 if (!COM_CheckParm("-noadjustaspect"))
1090                                 {
1091                                         if (modelist[nummodes].width > (modelist[nummodes].height << 1))
1092                                         {
1093                                                 modelist[nummodes].width >>= 1;
1094                                                 modelist[nummodes].halfscreen = 1;
1095                                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", modelist[nummodes].width, modelist[nummodes].height, modelist[nummodes].bpp);
1096                                         }
1097                                 }
1098
1099                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1100                                 {
1101                                         if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp == modelist[i].bpp))
1102                                         {
1103                                                 existingmode = 1;
1104                                                 break;
1105                                         }
1106                                 }
1107
1108                                 if (!existingmode)
1109                                         nummodes++;
1110                                 */
1111                         }
1112                 }
1113
1114                 modenum++;
1115         }
1116         while (stat);
1117
1118 // see if there are any low-res modes that aren't being reported
1119         numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]);
1120         bpp = 16;
1121         done = 0;
1122
1123         do
1124         {
1125                 for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++)
1126                 {
1127                         devmode.dmBitsPerPel = bpp;
1128                         devmode.dmPelsWidth = lowresmodes[j].width;
1129                         devmode.dmPelsHeight = lowresmodes[j].height;
1130                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1131
1132                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
1133                                 VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
1134                         /*
1135                         {
1136                                 modelist[nummodes].type = MS_FULLDIB;
1137                                 modelist[nummodes].width = devmode.dmPelsWidth;
1138                                 modelist[nummodes].height = devmode.dmPelsHeight;
1139                                 modelist[nummodes].modenum = 0;
1140                                 modelist[nummodes].halfscreen = 0;
1141                                 modelist[nummodes].dib = 1;
1142                                 modelist[nummodes].fullscreen = 1;
1143                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1144                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight, devmode.dmBitsPerPel);
1145
1146                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1147                                 {
1148                                         if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp == modelist[i].bpp))
1149                                         {
1150                                                 existingmode = 1;
1151                                                 break;
1152                                         }
1153                                 }
1154
1155                                 if (!existingmode)
1156                                         nummodes++;
1157                         }
1158                         */
1159                 }
1160                 switch (bpp)
1161                 {
1162                         case 16:
1163                                 bpp = 32;
1164                                 break;
1165
1166                         case 32:
1167                                 bpp = 24;
1168                                 break;
1169
1170                         case 24:
1171                                 done = 1;
1172                                 break;
1173                 }
1174         }
1175         while (!done);
1176
1177         if (nummodes == originalnummodes)
1178                 Con_SafePrintf ("No fullscreen DIB modes found\n");
1179 }
1180
1181 //static int grabsysgamma = true;
1182 WORD systemgammaramps[3][256], currentgammaramps[3][256];
1183
1184 int VID_SetGamma(float prescale, float gamma, float scale, float base)
1185 {
1186         int i;
1187         HDC hdc;
1188         hdc = GetDC (NULL);
1189
1190         BuildGammaTable16(prescale, gamma, scale, base, &currentgammaramps[0][0]);
1191         for (i = 0;i < 256;i++)
1192                 currentgammaramps[1][i] = currentgammaramps[2][i] = currentgammaramps[0][i];
1193
1194         i = SetDeviceGammaRamp(hdc, &currentgammaramps[0][0]);
1195
1196         ReleaseDC (NULL, hdc);
1197         return i; // return success or failure
1198 }
1199
1200 void VID_RestoreGameGamma(void)
1201 {
1202         VID_UpdateGamma(true);
1203 }
1204
1205 void VID_GetSystemGamma(void)
1206 {
1207         HDC hdc;
1208         hdc = GetDC (NULL);
1209
1210         GetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1211
1212         ReleaseDC (NULL, hdc);
1213 }
1214
1215 void VID_RestoreSystemGamma(void)
1216 {
1217         HDC hdc;
1218         hdc = GetDC (NULL);
1219
1220         SetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1221
1222         ReleaseDC (NULL, hdc);
1223 }
1224
1225 /*
1226 ===================
1227 VID_Init
1228 ===================
1229 */
1230 void    VID_Init (void)
1231 {
1232         int             i;
1233 //      int             existingmode;
1234         int             basenummodes, width, height = 0, bpp, findbpp, done;
1235         HDC             hdc;
1236         DEVMODE devmode;
1237
1238         memset(&devmode, 0, sizeof(devmode));
1239
1240 //      Cvar_RegisterVariable (&_vid_default_mode);
1241 //      Cvar_RegisterVariable (&_vid_default_mode_win);
1242
1243         Cmd_AddCommand ("vid_nummodes", VID_NumModes_f);
1244         Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f);
1245         Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f);
1246         Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f);
1247
1248         VID_GetSystemGamma();
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, char *picname);
1459
1460 static int      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         cachepic_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, "gfx/vidmodes.lmp");
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, "Video modes must be set from the");
1536         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "command line with -width <width>");
1537         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, "and -bpp <bits-per-pixel>");
1538         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Select windowed mode with -window");
1539 }
1540
1541
1542 /*
1543 ================
1544 VID_MenuKey
1545 ================
1546 */
1547 void VID_MenuKey (int key)
1548 {
1549         switch (key)
1550         {
1551         case K_ESCAPE:
1552                 S_LocalSound ("misc/menu1.wav");
1553                 M_Menu_Options_f ();
1554                 break;
1555
1556         default:
1557                 break;
1558         }
1559 }