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