]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_wgl.c
fix mouse in win32, I had forgotten to update a lot of code
[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                 if (hDC && mainwindow)
405                         ReleaseDC(mainwindow, hDC);
406
407                 if (modestate == MS_FULLDIB)
408                         ChangeDisplaySettings (NULL, 0);
409
410                 if (maindc && mainwindow)
411                         ReleaseDC (mainwindow, maindc);
412
413                 AppActivate(false, false);
414
415                 VID_RestoreSystemGamma();
416         }
417
418         GL_CloseLibrary();
419 }
420
421
422 //==========================================================================
423
424
425 BOOL bSetupPixelFormat(HDC hDC)
426 {
427         static PIXELFORMATDESCRIPTOR pfd = {
428         sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
429         1,                              // version number
430         PFD_DRAW_TO_WINDOW              // support window
431         |  PFD_SUPPORT_OPENGL   // support OpenGL
432         |  PFD_DOUBLEBUFFER ,   // double buffered
433         PFD_TYPE_RGBA,                  // RGBA type
434         24,                             // 24-bit color depth
435         0, 0, 0, 0, 0, 0,               // color bits ignored
436         0,                              // no alpha buffer
437         0,                              // shift bit ignored
438         0,                              // no accumulation buffer
439         0, 0, 0, 0,                     // accum bits ignored
440         32,                             // 32-bit z-buffer
441         0,                              // no stencil buffer
442         0,                              // no auxiliary buffer
443         PFD_MAIN_PLANE,                 // main layer
444         0,                              // reserved
445         0, 0, 0                         // layer masks ignored
446         };
447         int pixelformat;
448
449         if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
450         {
451                 MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
452                 return false;
453         }
454
455         if (SetPixelFormat(hDC, pixelformat, &pfd) == false)
456         {
457                 MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
458                 return false;
459         }
460
461         return true;
462 }
463
464
465
466 qbyte scantokey[128] =
467 {
468 //      0           1      2     3     4     5       6       7      8         9      A       B           C     D            E           F
469         0          ,27    ,'1'  ,'2'  ,'3'  ,'4'    ,'5'    ,'6'   ,'7'      ,'8'   ,'9'    ,'0'        ,'-'  ,'='         ,K_BACKSPACE,9     , // 0
470         'q'        ,'w'   ,'e'  ,'r'  ,'t'  ,'y'    ,'u'    ,'i'   ,'o'      ,'p'   ,'['    ,']'        ,13   ,K_CTRL      ,'a'        ,'s'   , // 1
471         'd'        ,'f'   ,'g'  ,'h'  ,'j'  ,'k'    ,'l'    ,';'   ,'\''     ,'`'   ,K_SHIFT,'\\'       ,'z'  ,'x'         ,'c'        ,'v'   , // 2
472         'b'        ,'n'   ,'m'  ,','  ,'.'  ,'/'    ,K_SHIFT,'*'   ,K_ALT    ,' '   ,0      ,K_F1       ,K_F2 ,K_F3        ,K_F4       ,K_F5  , // 3
473         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
474         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0    ,0      ,0      ,K_F11 ,K_F12    ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 5
475         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0     , // 6
476         0          ,0     ,0    ,0    ,0    ,0      ,0      ,0     ,0        ,0     ,0      ,0          ,0    ,0           ,0          ,0       // 7
477 };
478
479
480 /*
481 =======
482 MapKey
483
484 Map from windows to quake keynums
485 =======
486 */
487 int MapKey (int key, int virtualkey)
488 {
489         key = (key>>16)&255;
490         if (key > 127)
491                 return 0;
492         if (scantokey[key] == 0)
493                 Con_DPrintf("key 0x%02x has no translation\n", key);
494         return scantokey[key];
495 }
496
497 /*
498 ===================================================================
499
500 MAIN WINDOW
501
502 ===================================================================
503 */
504
505 /*
506 ================
507 ClearAllStates
508 ================
509 */
510 void ClearAllStates (void)
511 {
512         int             i;
513
514 // send an up event for each key, to make sure the server clears them all
515         for (i=0 ; i<256 ; i++)
516         {
517                 Key_Event (i, false);
518         }
519
520         Key_ClearStates ();
521         IN_ClearStates ();
522 }
523
524 void VID_RestoreGameGamma(void);
525 extern qboolean host_loopactive;
526
527 void AppActivate(BOOL fActive, BOOL minimize)
528 /****************************************************************************
529 *
530 * Function:     AppActivate
531 * Parameters:   fActive - True if app is activating
532 *
533 * Description:  If the application is activating, then swap the system
534 *               into SYSPAL_NOSTATIC mode so that our palettes will display
535 *               correctly.
536 *
537 ****************************************************************************/
538 {
539         static BOOL     sound_active;
540
541         vid_activewindow = fActive;
542         vid_hidden = minimize;
543
544 // enable/disable sound on focus gain/loss
545         if (!vid_activewindow && sound_active)
546         {
547                 S_BlockSound ();
548                 sound_active = false;
549         }
550         else if (vid_activewindow && !sound_active)
551         {
552                 S_UnblockSound ();
553                 sound_active = true;
554         }
555
556         if (fActive)
557         {
558                 if (modestate == MS_FULLDIB)
559                 {
560                         if (vid_canalttab && vid_wassuspended)
561                         {
562                                 vid_wassuspended = false;
563                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
564                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
565                         }
566
567                         // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
568                         MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
569                 }
570                 if (host_loopactive)
571                         VID_RestoreGameGamma();
572         }
573
574         if (!fActive)
575         {
576                 vid_usingmouse = false;
577                 IN_DeactivateMouse ();
578                 IN_ShowMouse ();
579                 if (modestate == MS_FULLDIB && vid_canalttab)
580                 {
581                         ChangeDisplaySettings (NULL, 0);
582                         vid_wassuspended = true;
583                 }
584                 VID_RestoreSystemGamma();
585         }
586 }
587
588 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
589
590 /* main window procedure */
591 LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
592 {
593         LONG    lRet = 1;
594         int             fActive, fMinimized, temp;
595         extern unsigned int uiWheelMessage;
596
597         if ( uMsg == uiWheelMessage )
598                 uMsg = WM_MOUSEWHEEL;
599
600         switch (uMsg)
601         {
602                 case WM_KILLFOCUS:
603                         if (modestate == MS_FULLDIB)
604                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
605                         break;
606
607                 case WM_CREATE:
608                         break;
609
610                 case WM_MOVE:
611                         window_x = (int) LOWORD(lParam);
612                         window_y = (int) HIWORD(lParam);
613                         VID_UpdateWindowStatus ();
614                         break;
615
616                 case WM_KEYDOWN:
617                 case WM_SYSKEYDOWN:
618                         Key_Event (MapKey(lParam, wParam), true);
619                         break;
620
621                 case WM_KEYUP:
622                 case WM_SYSKEYUP:
623                         Key_Event (MapKey(lParam, wParam), false);
624                         break;
625
626                 case WM_SYSCHAR:
627                 // keep Alt-Space from happening
628                         break;
629
630         // this is complicated because Win32 seems to pack multiple mouse events into
631         // one update sometimes, so we always check all states and look for events
632                 case WM_LBUTTONDOWN:
633                 case WM_LBUTTONUP:
634                 case WM_RBUTTONDOWN:
635                 case WM_RBUTTONUP:
636                 case WM_MBUTTONDOWN:
637                 case WM_MBUTTONUP:
638                 case WM_MOUSEMOVE:
639                         temp = 0;
640
641                         if (wParam & MK_LBUTTON)
642                                 temp |= 1;
643
644                         if (wParam & MK_RBUTTON)
645                                 temp |= 2;
646
647                         if (wParam & MK_MBUTTON)
648                                 temp |= 4;
649
650                         IN_MouseEvent (temp);
651
652                         break;
653
654                 // JACK: This is the mouse wheel with the Intellimouse
655                 // Its delta is either positive or neg, and we generate the proper
656                 // Event.
657                 case WM_MOUSEWHEEL:
658                         if ((short) HIWORD(wParam) > 0) {
659                                 Key_Event(K_MWHEELUP, true);
660                                 Key_Event(K_MWHEELUP, false);
661                         } else {
662                                 Key_Event(K_MWHEELDOWN, true);
663                                 Key_Event(K_MWHEELDOWN, false);
664                         }
665                         break;
666
667                 case WM_SIZE:
668                         break;
669
670                 case WM_CLOSE:
671                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
672                                 Sys_Quit ();
673
674                         break;
675
676                 case WM_ACTIVATE:
677                         fActive = LOWORD(wParam);
678                         fMinimized = (BOOL) HIWORD(wParam);
679                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
680
681                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
682                         ClearAllStates ();
683
684                         break;
685
686                 case WM_DESTROY:
687                 {
688                         if (mainwindow)
689                                 DestroyWindow (mainwindow);
690
691                         PostQuitMessage (0);
692                 }
693                 break;
694
695                 case MM_MCINOTIFY:
696                         lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
697                         break;
698
699                 default:
700                         /* pass all unhandled messages to DefWindowProc */
701                         lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
702                 break;
703         }
704
705         /* return 1 if handled message, 0 if not */
706         return lRet;
707 }
708
709
710 /*
711 =================
712 VID_NumModes
713 =================
714 */
715 int VID_NumModes (void)
716 {
717         return nummodes;
718 }
719
720
721 /*
722 =================
723 VID_GetModePtr
724 =================
725 */
726 vmode_t *VID_GetModePtr (int modenum)
727 {
728
729         if ((modenum >= 0) && (modenum < nummodes))
730                 return &modelist[modenum];
731         else
732                 return &badmode;
733 }
734
735
736 /*
737 =================
738 VID_GetModeDescription
739 =================
740 */
741 char *VID_GetModeDescription (int mode)
742 {
743         char            *pinfo;
744         vmode_t         *pv;
745         static char     temp[100];
746
747         if ((mode < 0) || (mode >= nummodes))
748                 return NULL;
749
750         if (!leavecurrentmode)
751         {
752                 pv = VID_GetModePtr (mode);
753                 pinfo = pv->modedesc;
754         }
755         else
756         {
757                 sprintf (temp, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
758                 pinfo = temp;
759         }
760
761         return pinfo;
762 }
763
764
765 // KJB: Added this to return the mode driver name in description for console
766
767 char *VID_GetExtModeDescription (int mode)
768 {
769         static char     pinfo[40];
770         vmode_t         *pv;
771
772         if ((mode < 0) || (mode >= nummodes))
773                 return NULL;
774
775         pv = VID_GetModePtr (mode);
776         if (modelist[mode].type == MS_FULLDIB)
777         {
778                 if (!leavecurrentmode)
779                         sprintf(pinfo,"%s fullscreen", pv->modedesc);
780                 else
781                         sprintf (pinfo, "Desktop resolution (%dx%d)", modelist[MODE_FULLSCREEN_DEFAULT].width, modelist[MODE_FULLSCREEN_DEFAULT].height);
782         }
783         else
784         {
785                 if (modestate == MS_WINDOWED)
786                         sprintf(pinfo, "%s windowed", pv->modedesc);
787                 else
788                         sprintf(pinfo, "windowed");
789         }
790
791         return pinfo;
792 }
793
794
795 /*
796 =================
797 VID_DescribeCurrentMode_f
798 =================
799 */
800 void VID_DescribeCurrentMode_f (void)
801 {
802         Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum));
803 }
804
805
806 /*
807 =================
808 VID_NumModes_f
809 =================
810 */
811 void VID_NumModes_f (void)
812 {
813         if (nummodes == 1)
814                 Con_Printf ("%d video mode is available\n", nummodes);
815         else
816                 Con_Printf ("%d video modes are available\n", nummodes);
817 }
818
819
820 /*
821 =================
822 VID_DescribeMode_f
823 =================
824 */
825 void VID_DescribeMode_f (void)
826 {
827         int             t, modenum;
828
829         modenum = atoi (Cmd_Argv(1));
830
831         t = leavecurrentmode;
832         leavecurrentmode = 0;
833
834         Con_Printf ("%s\n", VID_GetExtModeDescription (modenum));
835
836         leavecurrentmode = t;
837 }
838
839
840 /*
841 =================
842 VID_DescribeModes_f
843 =================
844 */
845 void VID_DescribeModes_f (void)
846 {
847         int                     i, lnummodes, t;
848         char            *pinfo;
849         vmode_t         *pv;
850
851         lnummodes = VID_NumModes ();
852
853         t = leavecurrentmode;
854         leavecurrentmode = 0;
855
856         for (i=1 ; i<lnummodes ; i++)
857         {
858                 pv = VID_GetModePtr (i);
859                 pinfo = VID_GetExtModeDescription (i);
860                 Con_Printf ("%2d: %s\n", i, pinfo);
861         }
862
863         leavecurrentmode = t;
864 }
865
866 void VID_AddMode(int type, int width, int height, int modenum, int halfscreen, int dib, int fullscreen, int bpp)
867 {
868         int i;
869         if (nummodes >= MAX_MODE_LIST)
870                 return;
871         modelist[nummodes].type = type;
872         modelist[nummodes].width = width;
873         modelist[nummodes].height = height;
874         modelist[nummodes].modenum = modenum;
875         modelist[nummodes].halfscreen = halfscreen;
876         modelist[nummodes].dib = dib;
877         modelist[nummodes].fullscreen = fullscreen;
878         modelist[nummodes].bpp = bpp;
879         if (bpp == 0)
880                 sprintf (modelist[nummodes].modedesc, "%dx%d", width, height);
881         else
882                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d", width, height, bpp);
883         for (i = 0;i < nummodes;i++)
884         {
885                 if (!memcmp(&modelist[i], &modelist[nummodes], sizeof(vmode_t)))
886                         return;
887         }
888         nummodes++;
889 }
890
891 void VID_InitDIB (HINSTANCE hInstance)
892 {
893         int w, h;
894         WNDCLASS                wc;
895
896         // Register the frame class
897         wc.style         = 0;
898         wc.lpfnWndProc   = (WNDPROC)MainWndProc;
899         wc.cbClsExtra    = 0;
900         wc.cbWndExtra    = 0;
901         wc.hInstance     = hInstance;
902         wc.hIcon         = 0;
903         wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
904         wc.hbrBackground = NULL;
905         wc.lpszMenuName  = 0;
906         wc.lpszClassName = gamename;
907
908         if (!RegisterClass (&wc) )
909                 Sys_Error ("Couldn't register window class");
910
911         if (COM_CheckParm("-width"))
912                 w = atoi(com_argv[COM_CheckParm("-width")+1]);
913         else
914                 w = 640;
915
916         if (w < 320)
917                 w = 320;
918
919         if (COM_CheckParm("-height"))
920                 h = atoi(com_argv[COM_CheckParm("-height")+1]);
921         else
922                 h = w * 240/320;
923
924         if (h < 240)
925                 h = 240;
926
927         VID_AddMode(MS_WINDOWED, w, h, 0, 0, 1, 0, 0);
928 }
929
930
931 /*
932 =================
933 VID_InitFullDIB
934 =================
935 */
936 void VID_InitFullDIB (HINSTANCE hInstance)
937 {
938         DEVMODE devmode;
939         int             modenum;
940         int             originalnummodes;
941         int             numlowresmodes;
942         int             j;
943         int             bpp;
944         int             done;
945         BOOL    stat;
946
947 // enumerate >8 bpp modes
948         originalnummodes = nummodes;
949         modenum = 0;
950
951         do
952         {
953                 stat = EnumDisplaySettings (NULL, modenum, &devmode);
954
955                 if ((devmode.dmBitsPerPel >= 15) && (devmode.dmPelsWidth <= MAXWIDTH) && (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST))
956                 {
957                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
958
959                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
960                         {
961                         // if the width is more than twice the height, reduce it by half because this
962                         // is probably a dual-screen monitor
963                                 if ((!COM_CheckParm("-noadjustaspect")) && (devmode.dmPelsWidth > (devmode.dmPelsHeight << 1)))
964                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth >> 1, devmode.dmPelsHeight, 0, 1, 1, 1, devmode.dmBitsPerPel);
965                                 else
966                                         VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
967                         }
968                 }
969
970                 modenum++;
971         }
972         while (stat);
973
974 // see if there are any low-res modes that aren't being reported
975         numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]);
976         bpp = 16;
977         done = 0;
978
979         do
980         {
981                 for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++)
982                 {
983                         devmode.dmBitsPerPel = bpp;
984                         devmode.dmPelsWidth = lowresmodes[j].width;
985                         devmode.dmPelsHeight = lowresmodes[j].height;
986                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
987
988                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL)
989                                 VID_AddMode(MS_FULLDIB, devmode.dmPelsWidth, devmode.dmPelsHeight, 0, 0, 1, 1, devmode.dmBitsPerPel);
990                 }
991                 switch (bpp)
992                 {
993                         case 16:
994                                 bpp = 32;
995                                 break;
996
997                         case 32:
998                                 bpp = 24;
999                                 break;
1000
1001                         case 24:
1002                                 done = 1;
1003                                 break;
1004                 }
1005         }
1006         while (!done);
1007
1008         if (nummodes == originalnummodes)
1009                 Con_SafePrintf ("No fullscreen DIB modes found\n");
1010 }
1011
1012 //static int grabsysgamma = true;
1013 WORD systemgammaramps[3][256], currentgammaramps[3][256];
1014
1015 int VID_SetGamma(float prescale, float gamma, float scale, float base)
1016 {
1017         int i;
1018         HDC hdc;
1019         hdc = GetDC (NULL);
1020
1021         BuildGammaTable16(prescale, gamma, scale, base, &currentgammaramps[0][0]);
1022         for (i = 0;i < 256;i++)
1023                 currentgammaramps[1][i] = currentgammaramps[2][i] = currentgammaramps[0][i];
1024
1025         i = SetDeviceGammaRamp(hdc, &currentgammaramps[0][0]);
1026
1027         ReleaseDC (NULL, hdc);
1028         return i; // return success or failure
1029 }
1030
1031 void VID_RestoreGameGamma(void)
1032 {
1033         VID_UpdateGamma(true);
1034 }
1035
1036 void VID_GetSystemGamma(void)
1037 {
1038         HDC hdc;
1039         hdc = GetDC (NULL);
1040
1041         GetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1042
1043         ReleaseDC (NULL, hdc);
1044 }
1045
1046 void VID_RestoreSystemGamma(void)
1047 {
1048         HDC hdc;
1049         hdc = GetDC (NULL);
1050
1051         SetDeviceGammaRamp(hdc, &systemgammaramps[0][0]);
1052
1053         ReleaseDC (NULL, hdc);
1054 }
1055
1056 /*
1057 ===================
1058 VID_Init
1059 ===================
1060 */
1061 void VID_Init (void)
1062 {
1063         int i;
1064         int basenummodes, width, height = 0, bpp, findbpp, done;
1065         HDC hdc;
1066         DEVMODE devmode;
1067
1068         GL_OpenLibrary();
1069
1070         memset(&devmode, 0, sizeof(devmode));
1071
1072         Cmd_AddCommand ("vid_nummodes", VID_NumModes_f);
1073         Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f);
1074         Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f);
1075         Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f);
1076
1077         VID_GetSystemGamma();
1078
1079         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON2));
1080
1081         InitCommonControls();
1082
1083         VID_InitDIB (global_hInstance);
1084         basenummodes = nummodes = 1;
1085
1086         VID_InitFullDIB (global_hInstance);
1087
1088         if (COM_CheckParm("-window"))
1089         {
1090                 hdc = GetDC (NULL);
1091
1092                 if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)
1093                         Sys_Error ("Can't run in non-RGB mode");
1094
1095                 ReleaseDC (NULL, hdc);
1096
1097                 windowed = true;
1098
1099                 vid_default = MODE_WINDOWED;
1100         }
1101         else
1102         {
1103                 if (nummodes == 1)
1104                         Sys_Error ("No RGB fullscreen modes available");
1105
1106                 windowed = false;
1107
1108                 if (COM_CheckParm("-mode"))
1109                         vid_default = atoi(com_argv[COM_CheckParm("-mode")+1]);
1110                 else
1111                 {
1112                         if (COM_CheckParm("-current"))
1113                         {
1114                                 modelist[MODE_FULLSCREEN_DEFAULT].width = GetSystemMetrics (SM_CXSCREEN);
1115                                 modelist[MODE_FULLSCREEN_DEFAULT].height = GetSystemMetrics (SM_CYSCREEN);
1116                                 vid_default = MODE_FULLSCREEN_DEFAULT;
1117                                 leavecurrentmode = 1;
1118                         }
1119                         else
1120                         {
1121                                 if (COM_CheckParm("-width"))
1122                                         width = atoi(com_argv[COM_CheckParm("-width")+1]);
1123                                 else
1124                                         width = 640;
1125
1126                                 if (COM_CheckParm("-bpp"))
1127                                 {
1128                                         bpp = atoi(com_argv[COM_CheckParm("-bpp")+1]);
1129                                         findbpp = 0;
1130                                 }
1131                                 else
1132                                 {
1133                                         bpp = 15;
1134                                         findbpp = 1;
1135                                 }
1136
1137                                 if (COM_CheckParm("-height"))
1138                                         height = atoi(com_argv[COM_CheckParm("-height")+1]);
1139
1140                         // if they want to force it, add the specified mode to the list
1141                                 if (COM_CheckParm("-force") && (nummodes < MAX_MODE_LIST))
1142                                         VID_AddMode(MS_FULLDIB, width, height, 0, 0, 1, 1, bpp);
1143
1144                                 done = 0;
1145
1146                                 do
1147                                 {
1148                                         if (COM_CheckParm("-height"))
1149                                         {
1150                                                 height = atoi(com_argv[COM_CheckParm("-height")+1]);
1151
1152                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1153                                                 {
1154                                                         if ((modelist[i].width == width) && (modelist[i].height == height) && (modelist[i].bpp == bpp))
1155                                                         {
1156                                                                 vid_default = i;
1157                                                                 done = 1;
1158                                                                 break;
1159                                                         }
1160                                                 }
1161                                         }
1162                                         else
1163                                         {
1164                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1165                                                 {
1166                                                         if ((modelist[i].width == width) && (modelist[i].bpp == bpp))
1167                                                         {
1168                                                                 vid_default = i;
1169                                                                 done = 1;
1170                                                                 break;
1171                                                         }
1172                                                 }
1173                                         }
1174
1175                                         if (!done)
1176                                         {
1177                                                 if (findbpp)
1178                                                 {
1179                                                         switch (bpp)
1180                                                         {
1181                                                         case 15: bpp = 16;break;
1182                                                         case 16: bpp = 32;break;
1183                                                         case 32: bpp = 24;break;
1184                                                         case 24: done = 1;break;
1185                                                         }
1186                                                 }
1187                                                 else
1188                                                         done = 1;
1189                                         }
1190                                 }
1191                                 while (!done);
1192
1193                                 if (!vid_default)
1194                                         Sys_Error ("Specified video mode not available");
1195                         }
1196                 }
1197         }
1198
1199         vid_initialized = true;
1200
1201         if ((i = COM_CheckParm("-conwidth")) != 0)
1202                 vid.conwidth = atoi(com_argv[i+1]);
1203         else
1204                 vid.conwidth = 640;
1205
1206         vid.conwidth &= 0xfff8; // make it a multiple of eight
1207
1208         if (vid.conwidth < 320)
1209                 vid.conwidth = 320;
1210
1211         // pick a conheight that matches with correct aspect
1212         vid.conheight = vid.conwidth*3 / 4;
1213
1214         if ((i = COM_CheckParm("-conheight")) != 0)
1215                 vid.conheight = atoi(com_argv[i+1]);
1216         if (vid.conheight < 200)
1217                 vid.conheight = 200;
1218
1219         VID_SetMode (vid_default);
1220
1221         maindc = GetDC(mainwindow);
1222         bSetupPixelFormat(maindc);
1223
1224         baseRC = wglCreateContext( maindc );
1225         if (!baseRC)
1226                 Sys_Error ("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.");
1227         if (!wglMakeCurrent( maindc, baseRC ))
1228                 Sys_Error ("wglMakeCurrent failed");
1229
1230         GL_Init ();
1231
1232         // LordHavoc: special differences for ATI (broken 8bit color when also using 32bit? weird!)
1233         if (strncasecmp(gl_vendor,"ATI",3)==0)
1234         {
1235                 if (strncasecmp(gl_renderer,"Rage Pro",8)==0)
1236                         isRagePro = true;
1237         }
1238         if (strncasecmp(gl_renderer,"Matrox G200 Direct3D",20)==0) // a D3D driver for GL? sigh...
1239                 isG200 = true;
1240
1241         vid_realmode = vid_modenum;
1242
1243         vid_menudrawfn = VID_MenuDraw;
1244         vid_menukeyfn = VID_MenuKey;
1245
1246         strcpy (badmode.modedesc, "Bad mode");
1247         vid_canalttab = true;
1248
1249         vid_hidden = false;
1250 }
1251
1252
1253 //========================================================
1254 // Video menu stuff
1255 //========================================================
1256
1257 extern void M_Menu_Options_f (void);
1258 extern void M_Print (float cx, float cy, char *str);
1259 extern void M_PrintWhite (float cx, float cy, char *str);
1260 extern void M_DrawCharacter (float cx, float cy, int num);
1261 extern void M_DrawPic (float cx, float cy, char *picname);
1262
1263 static int vid_wmodes;
1264
1265 typedef struct
1266 {
1267         int modenum;
1268         char *desc;
1269         int iscur;
1270 } modedesc_t;
1271
1272 #define MAX_COLUMN_SIZE         9
1273 #define MODE_AREA_HEIGHT        (MAX_COLUMN_SIZE + 2)
1274 #define MAX_MODEDESCS           (MAX_COLUMN_SIZE*3)
1275
1276 static modedesc_t modedescs[MAX_MODEDESCS];
1277
1278 /*
1279 ================
1280 VID_MenuDraw
1281 ================
1282 */
1283 void VID_MenuDraw (void)
1284 {
1285         cachepic_t *p;
1286         char *ptr;
1287         int lnummodes, i, k, column, row;
1288         vmode_t *pv;
1289
1290         p = Draw_CachePic ("gfx/vidmodes.lmp");
1291         M_DrawPic ( (320-p->width)/2, 4, "gfx/vidmodes.lmp");
1292
1293         vid_wmodes = 0;
1294         lnummodes = VID_NumModes ();
1295
1296         for (i=1 ; (i<lnummodes) && (vid_wmodes < MAX_MODEDESCS) ; i++)
1297         {
1298                 ptr = VID_GetModeDescription (i);
1299                 pv = VID_GetModePtr (i);
1300
1301                 k = vid_wmodes;
1302
1303                 modedescs[k].modenum = i;
1304                 modedescs[k].desc = ptr;
1305                 modedescs[k].iscur = 0;
1306
1307                 if (i == vid_modenum)
1308                         modedescs[k].iscur = 1;
1309
1310                 vid_wmodes++;
1311
1312         }
1313
1314         if (vid_wmodes > 0)
1315         {
1316                 M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)");
1317
1318                 column = 8;
1319                 row = 36+2*8;
1320
1321                 for (i=0 ; i<vid_wmodes ; i++)
1322                 {
1323                         if (modedescs[i].iscur)
1324                                 M_PrintWhite (column, row, modedescs[i].desc);
1325                         else
1326                                 M_Print (column, row, modedescs[i].desc);
1327
1328                         column += 13*8;
1329
1330                         if ((i % VID_ROW_SIZE) == (VID_ROW_SIZE - 1))
1331                         {
1332                                 column = 8;
1333                                 row += 8;
1334                         }
1335                 }
1336         }
1337
1338         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*2, "Video modes must be set from the");
1339         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "command line with -width <width>");
1340         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, "and -bpp <bits-per-pixel>");
1341         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Select windowed mode with -window");
1342 }
1343
1344
1345 /*
1346 ================
1347 VID_MenuKey
1348 ================
1349 */
1350 void VID_MenuKey (int key)
1351 {
1352         switch (key)
1353         {
1354         case K_ESCAPE:
1355                 S_LocalSound ("misc/menu1.wav");
1356                 M_Menu_Options_f ();
1357                 break;
1358
1359         default:
1360                 break;
1361         }
1362 }
1363