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