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