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