]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_wgl.c
Fixed some of the mess. Might work now...
[xonotic/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         glAlphaFunc(GL_GREATER, 0.5);
572         glCullFace(GL_FRONT);
573 }
574
575 /*
576 =================
577 GL_BeginRendering
578
579 =================
580 */
581 void GL_BeginRendering (int *x, int *y, int *width, int *height)
582 {
583 //      extern cvar_t gl_clear;
584
585         *x = *y = 0;
586         *width = WindowRect.right - WindowRect.left;
587         *height = WindowRect.bottom - WindowRect.top;
588
589 //      if (!wglMakeCurrent( maindc, baseRC ))
590 //              Sys_Error ("wglMakeCurrent failed");
591
592 //      glViewport (*x, *y, *width, *height);
593 }
594
595
596 void GL_EndRendering (void)
597 {
598         if (r_render.value && !scr_skipupdate)
599                 SwapBuffers(maindc);
600
601 // handle the mouse state when windowed if that's changed
602         if (modestate == MS_WINDOWED)
603         {
604                 if (!_windowed_mouse.value)
605                 {
606                         if (windowed_mouse)
607                         {
608                                 IN_DeactivateMouse ();
609                                 IN_ShowMouse ();
610                                 windowed_mouse = false;
611                         }
612                 }
613                 else
614                 {
615                         windowed_mouse = true;
616                         if (key_dest == key_game && !mouseactive && ActiveApp)
617                         {
618                                 IN_ActivateMouse ();
619                                 IN_HideMouse ();
620                         }
621                         else if (mouseactive && key_dest != key_game)
622                         {
623                                 IN_DeactivateMouse ();
624                                 IN_ShowMouse ();
625                         }
626                 }
627         }
628 }
629
630 void VID_SetDefaultMode (void)
631 {
632         IN_DeactivateMouse ();
633 }
634
635
636 void    VID_Shutdown (void)
637 {
638         HGLRC hRC;
639         HDC       hDC;
640         int i;
641         GLuint temp[8192];
642
643         if (vid_initialized)
644         {
645                 vid_canalttab = false;
646                 hRC = wglGetCurrentContext();
647         hDC = wglGetCurrentDC();
648
649         wglMakeCurrent(NULL, NULL);
650
651                 // LordHavoc: free textures before closing (may help NVIDIA)
652                 for (i = 0;i < 8192;i++) temp[i] = i;
653                 glDeleteTextures(8192, temp);
654
655         if (hRC)
656             wglDeleteContext(hRC);
657
658                 if (hDC && dibwindow)
659                         ReleaseDC(dibwindow, hDC);
660
661                 if (modestate == MS_FULLDIB)
662                         ChangeDisplaySettings (NULL, 0);
663
664                 if (maindc && dibwindow)
665                         ReleaseDC (dibwindow, maindc);
666
667                 AppActivate(false, false);
668         }
669 }
670
671
672 //==========================================================================
673
674
675 BOOL bSetupPixelFormat(HDC hDC)
676 {
677     static PIXELFORMATDESCRIPTOR pfd = {
678         sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd
679         1,                              // version number
680         PFD_DRAW_TO_WINDOW              // support window
681         |  PFD_SUPPORT_OPENGL   // support OpenGL
682         |  PFD_DOUBLEBUFFER ,   // double buffered
683         PFD_TYPE_RGBA,                  // RGBA type
684         24,                             // 24-bit color depth
685         0, 0, 0, 0, 0, 0,               // color bits ignored
686         0,                              // no alpha buffer
687         0,                              // shift bit ignored
688         0,                              // no accumulation buffer
689         0, 0, 0, 0,                     // accum bits ignored
690         32,                             // 32-bit z-buffer      
691         0,                              // no stencil buffer
692         0,                              // no auxiliary buffer
693         PFD_MAIN_PLANE,                 // main layer
694         0,                              // reserved
695         0, 0, 0                         // layer masks ignored
696     };
697     int pixelformat;
698
699     if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )
700     {
701         MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK);
702         return FALSE;
703     }
704
705     if (SetPixelFormat(hDC, pixelformat, &pfd) == FALSE)
706     {
707         MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK);
708         return FALSE;
709     }
710
711     return TRUE;
712 }
713
714
715
716 byte        scantokey[128] = 
717                                         { 
718 //  0           1       2       3       4       5       6       7 
719 //  8           9       A       B       C       D       E       F 
720         0  ,    27,     '1',    '2',    '3',    '4',    '5',    '6', 
721         '7',    '8',    '9',    '0',    '-',    '=',    K_BACKSPACE, 9, // 0 
722         'q',    'w',    'e',    'r',    't',    'y',    'u',    'i', 
723         'o',    'p',    '[',    ']',    13 ,    K_CTRL,'a',  's',      // 1 
724         'd',    'f',    'g',    'h',    'j',    'k',    'l',    ';', 
725         '\'' ,    '`',    K_SHIFT,'\\',  'z',    'x',    'c',    'v',      // 2 
726         'b',    'n',    'm',    ',',    '.',    '/',    K_SHIFT,'*', 
727         K_ALT,' ',   0  ,    K_F1, K_F2, K_F3, K_F4, K_F5,   // 3 
728         K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE  ,    0  , K_HOME, 
729         K_UPARROW,K_PGUP,'-',K_LEFTARROW,'5',K_RIGHTARROW,'+',K_END, //4 
730         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0,0,             0,              K_F11, 
731         K_F12,0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0,        // 5 
732         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0, 
733         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0,        // 6 
734         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0, 
735         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0         // 7 
736                                         }; 
737
738 byte        shiftscantokey[128] = 
739                                         { 
740 //  0           1       2       3       4       5       6       7 
741 //  8           9       A       B       C       D       E       F 
742         0  ,    27,     '!',    '@',    '#',    '$',    '%',    '^', 
743         '&',    '*',    '(',    ')',    '_',    '+',    K_BACKSPACE, 9, // 0 
744         'Q',    'W',    'E',    'R',    'T',    'Y',    'U',    'I', 
745         'O',    'P',    '{',    '}',    13 ,    K_CTRL,'A',  'S',      // 1 
746         'D',    'F',    'G',    'H',    'J',    'K',    'L',    ':', 
747         '"' ,    '~',    K_SHIFT,'|',  'Z',    'X',    'C',    'V',      // 2 
748         'B',    'N',    'M',    '<',    '>',    '?',    K_SHIFT,'*', 
749         K_ALT,' ',   0  ,    K_F1, K_F2, K_F3, K_F4, K_F5,   // 3 
750         K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE  ,    0  , K_HOME, 
751         K_UPARROW,K_PGUP,'_',K_LEFTARROW,'%',K_RIGHTARROW,'+',K_END, //4 
752         K_DOWNARROW,K_PGDN,K_INS,K_DEL,0,0,             0,              K_F11, 
753         K_F12,0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0,        // 5 
754         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0, 
755         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0,        // 6 
756         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0, 
757         0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0  ,    0         // 7 
758                                         }; 
759
760
761 /*
762 =======
763 MapKey
764
765 Map from windows to quake keynums
766 =======
767 */
768 int MapKey (int key)
769 {
770         key = (key>>16)&255;
771         if (key > 127)
772                 return 0;
773         if (scantokey[key] == 0)
774                 Con_DPrintf("key 0x%02x has no translation\n", key);
775         return scantokey[key];
776 }
777
778 /*
779 ===================================================================
780
781 MAIN WINDOW
782
783 ===================================================================
784 */
785
786 /*
787 ================
788 ClearAllStates
789 ================
790 */
791 void ClearAllStates (void)
792 {
793         int             i;
794         
795 // send an up event for each key, to make sure the server clears them all
796         for (i=0 ; i<256 ; i++)
797         {
798                 Key_Event (i, false);
799         }
800
801         Key_ClearStates ();
802         IN_ClearStates ();
803 }
804
805 void AppActivate(BOOL fActive, BOOL minimize)
806 /****************************************************************************
807 *
808 * Function:     AppActivate
809 * Parameters:   fActive - True if app is activating
810 *
811 * Description:  If the application is activating, then swap the system
812 *               into SYSPAL_NOSTATIC mode so that our palettes will display
813 *               correctly.
814 *
815 ****************************************************************************/
816 {
817         static BOOL     sound_active;
818
819         ActiveApp = fActive;
820         Minimized = minimize;
821
822 // enable/disable sound on focus gain/loss
823         if (!ActiveApp && sound_active)
824         {
825                 S_BlockSound ();
826                 sound_active = false;
827         }
828         else if (ActiveApp && !sound_active)
829         {
830                 S_UnblockSound ();
831                 sound_active = true;
832         }
833
834         if (fActive)
835         {
836                 if (modestate == MS_FULLDIB)
837                 {
838                         IN_ActivateMouse ();
839                         IN_HideMouse ();
840                         if (vid_canalttab && vid_wassuspended) {
841                                 vid_wassuspended = false;
842                                 ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
843                                 ShowWindow(mainwindow, SW_SHOWNORMAL);
844                         }
845                 }
846                 else if ((modestate == MS_WINDOWED) && _windowed_mouse.value && key_dest == key_game)
847                 {
848                         IN_ActivateMouse ();
849                         IN_HideMouse ();
850                 }
851         }
852
853         if (!fActive)
854         {
855                 if (modestate == MS_FULLDIB)
856                 {
857                         IN_DeactivateMouse ();
858                         IN_ShowMouse ();
859                         if (vid_canalttab) { 
860                                 ChangeDisplaySettings (NULL, 0);
861                                 vid_wassuspended = true;
862                         }
863                 }
864                 else if ((modestate == MS_WINDOWED) && _windowed_mouse.value)
865                 {
866                         IN_DeactivateMouse ();
867                         IN_ShowMouse ();
868                 }
869         }
870 }
871
872 LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
873
874 /* main window procedure */
875 LONG WINAPI MainWndProc (
876     HWND    hWnd,
877     UINT    uMsg,
878     WPARAM  wParam,
879     LPARAM  lParam)
880 {
881     LONG    lRet = 1;
882         int             fActive, fMinimized, temp;
883         extern unsigned int uiWheelMessage;
884
885         if ( uMsg == uiWheelMessage )
886                 uMsg = WM_MOUSEWHEEL;
887
888     switch (uMsg)
889     {
890                 case WM_KILLFOCUS:
891                         if (modestate == MS_FULLDIB)
892                                 ShowWindow(mainwindow, SW_SHOWMINNOACTIVE);
893                         break;
894
895                 case WM_CREATE:
896                         break;
897
898                 case WM_MOVE:
899                         window_x = (int) LOWORD(lParam);
900                         window_y = (int) HIWORD(lParam);
901                         VID_UpdateWindowStatus ();
902                         break;
903
904                 case WM_KEYDOWN:
905                 case WM_SYSKEYDOWN:
906                         Key_Event (MapKey(lParam), true);
907                         break;
908                         
909                 case WM_KEYUP:
910                 case WM_SYSKEYUP:
911                         Key_Event (MapKey(lParam), false);
912                         break;
913
914                 case WM_SYSCHAR:
915                 // keep Alt-Space from happening
916                         break;
917
918         // this is complicated because Win32 seems to pack multiple mouse events into
919         // one update sometimes, so we always check all states and look for events
920                 case WM_LBUTTONDOWN:
921                 case WM_LBUTTONUP:
922                 case WM_RBUTTONDOWN:
923                 case WM_RBUTTONUP:
924                 case WM_MBUTTONDOWN:
925                 case WM_MBUTTONUP:
926                 case WM_MOUSEMOVE:
927                         temp = 0;
928
929                         if (wParam & MK_LBUTTON)
930                                 temp |= 1;
931
932                         if (wParam & MK_RBUTTON)
933                                 temp |= 2;
934
935                         if (wParam & MK_MBUTTON)
936                                 temp |= 4;
937
938                         IN_MouseEvent (temp);
939
940                         break;
941
942                 // JACK: This is the mouse wheel with the Intellimouse
943                 // Its delta is either positive or neg, and we generate the proper
944                 // Event.
945                 case WM_MOUSEWHEEL: 
946                         if ((short) HIWORD(wParam) > 0) {
947                                 Key_Event(K_MWHEELUP, true);
948                                 Key_Event(K_MWHEELUP, false);
949                         } else {
950                                 Key_Event(K_MWHEELDOWN, true);
951                                 Key_Event(K_MWHEELDOWN, false);
952                         }
953                         break;
954
955         case WM_SIZE:
956             break;
957
958             case WM_CLOSE:
959                         if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit",
960                                                 MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES)
961                         {
962                                 Sys_Quit ();
963                         }
964
965                 break;
966
967                 case WM_ACTIVATE:
968                         fActive = LOWORD(wParam);
969                         fMinimized = (BOOL) HIWORD(wParam);
970                         AppActivate(!(fActive == WA_INACTIVE), fMinimized);
971
972                 // fix the leftover Alt from any Alt-Tab or the like that switched us away
973                         ClearAllStates ();
974
975                         break;
976
977             case WM_DESTROY:
978         {
979                         if (dibwindow)
980                                 DestroyWindow (dibwindow);
981
982             PostQuitMessage (0);
983         }
984         break;
985
986                 case MM_MCINOTIFY:
987             lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam);
988                         break;
989
990         default:
991             /* pass all unhandled messages to DefWindowProc */
992             lRet = DefWindowProc (hWnd, uMsg, wParam, lParam);
993         break;
994     }
995
996     /* return 1 if handled message, 0 if not */
997     return lRet;
998 }
999
1000
1001 /*
1002 =================
1003 VID_NumModes
1004 =================
1005 */
1006 int VID_NumModes (void)
1007 {
1008         return nummodes;
1009 }
1010
1011         
1012 /*
1013 =================
1014 VID_GetModePtr
1015 =================
1016 */
1017 vmode_t *VID_GetModePtr (int modenum)
1018 {
1019
1020         if ((modenum >= 0) && (modenum < nummodes))
1021                 return &modelist[modenum];
1022         else
1023                 return &badmode;
1024 }
1025
1026
1027 /*
1028 =================
1029 VID_GetModeDescription
1030 =================
1031 */
1032 char *VID_GetModeDescription (int mode)
1033 {
1034         char            *pinfo;
1035         vmode_t         *pv;
1036         static char     temp[100];
1037
1038         if ((mode < 0) || (mode >= nummodes))
1039                 return NULL;
1040
1041         if (!leavecurrentmode)
1042         {
1043                 pv = VID_GetModePtr (mode);
1044                 pinfo = pv->modedesc;
1045         }
1046         else
1047         {
1048                 sprintf (temp, "Desktop resolution (%dx%d)",
1049                                  modelist[MODE_FULLSCREEN_DEFAULT].width,
1050                                  modelist[MODE_FULLSCREEN_DEFAULT].height);
1051                 pinfo = temp;
1052         }
1053
1054         return pinfo;
1055 }
1056
1057
1058 // KJB: Added this to return the mode driver name in description for console
1059
1060 char *VID_GetExtModeDescription (int mode)
1061 {
1062         static char     pinfo[40];
1063         vmode_t         *pv;
1064
1065         if ((mode < 0) || (mode >= nummodes))
1066                 return NULL;
1067
1068         pv = VID_GetModePtr (mode);
1069         if (modelist[mode].type == MS_FULLDIB)
1070         {
1071                 if (!leavecurrentmode)
1072                 {
1073                         sprintf(pinfo,"%s fullscreen", pv->modedesc);
1074                 }
1075                 else
1076                 {
1077                         sprintf (pinfo, "Desktop resolution (%dx%d)",
1078                                          modelist[MODE_FULLSCREEN_DEFAULT].width,
1079                                          modelist[MODE_FULLSCREEN_DEFAULT].height);
1080                 }
1081         }
1082         else
1083         {
1084                 if (modestate == MS_WINDOWED)
1085                         sprintf(pinfo, "%s windowed", pv->modedesc);
1086                 else
1087                         sprintf(pinfo, "windowed");
1088         }
1089
1090         return pinfo;
1091 }
1092
1093
1094 /*
1095 =================
1096 VID_DescribeCurrentMode_f
1097 =================
1098 */
1099 void VID_DescribeCurrentMode_f (void)
1100 {
1101         Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum));
1102 }
1103
1104
1105 /*
1106 =================
1107 VID_NumModes_f
1108 =================
1109 */
1110 void VID_NumModes_f (void)
1111 {
1112
1113         if (nummodes == 1)
1114                 Con_Printf ("%d video mode is available\n", nummodes);
1115         else
1116                 Con_Printf ("%d video modes are available\n", nummodes);
1117 }
1118
1119
1120 /*
1121 =================
1122 VID_DescribeMode_f
1123 =================
1124 */
1125 void VID_DescribeMode_f (void)
1126 {
1127         int             t, modenum;
1128         
1129         modenum = atoi (Cmd_Argv(1));
1130
1131         t = leavecurrentmode;
1132         leavecurrentmode = 0;
1133
1134         Con_Printf ("%s\n", VID_GetExtModeDescription (modenum));
1135
1136         leavecurrentmode = t;
1137 }
1138
1139
1140 /*
1141 =================
1142 VID_DescribeModes_f
1143 =================
1144 */
1145 void VID_DescribeModes_f (void)
1146 {
1147         int                     i, lnummodes, t;
1148         char            *pinfo;
1149         vmode_t         *pv;
1150
1151         lnummodes = VID_NumModes ();
1152
1153         t = leavecurrentmode;
1154         leavecurrentmode = 0;
1155
1156         for (i=1 ; i<lnummodes ; i++)
1157         {
1158                 pv = VID_GetModePtr (i);
1159                 pinfo = VID_GetExtModeDescription (i);
1160                 Con_Printf ("%2d: %s\n", i, pinfo);
1161         }
1162
1163         leavecurrentmode = t;
1164 }
1165
1166
1167 void VID_InitDIB (HINSTANCE hInstance)
1168 {
1169         WNDCLASS                wc;
1170
1171         /* Register the frame class */
1172     wc.style         = 0;
1173     wc.lpfnWndProc   = (WNDPROC)MainWndProc;
1174     wc.cbClsExtra    = 0;
1175     wc.cbWndExtra    = 0;
1176     wc.hInstance     = hInstance;
1177     wc.hIcon         = 0;
1178     wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
1179         wc.hbrBackground = NULL;
1180     wc.lpszMenuName  = 0;
1181 #ifdef NEHAHRA
1182     wc.lpszClassName = "DPNehahraQuake";
1183 #else
1184     wc.lpszClassName = "DarkPlacesQuake";
1185 #endif
1186
1187     if (!RegisterClass (&wc) )
1188                 Sys_Error ("Couldn't register window class");
1189
1190         modelist[0].type = MS_WINDOWED;
1191
1192         if (COM_CheckParm("-width"))
1193                 modelist[0].width = atoi(com_argv[COM_CheckParm("-width")+1]);
1194         else
1195                 modelist[0].width = 640;
1196
1197         if (modelist[0].width < 320)
1198                 modelist[0].width = 320;
1199
1200         if (COM_CheckParm("-height"))
1201                 modelist[0].height= atoi(com_argv[COM_CheckParm("-height")+1]);
1202         else
1203                 modelist[0].height = modelist[0].width * 240/320;
1204
1205         if (modelist[0].height < 240)
1206                 modelist[0].height = 240;
1207
1208         sprintf (modelist[0].modedesc, "%dx%d",
1209                          modelist[0].width, modelist[0].height);
1210
1211         modelist[0].modenum = MODE_WINDOWED;
1212         modelist[0].dib = 1;
1213         modelist[0].fullscreen = 0;
1214         modelist[0].halfscreen = 0;
1215         modelist[0].bpp = 0;
1216
1217         nummodes = 1;
1218 }
1219
1220
1221 /*
1222 =================
1223 VID_InitFullDIB
1224 =================
1225 */
1226 void VID_InitFullDIB (HINSTANCE hInstance)
1227 {
1228         DEVMODE devmode;
1229         int             i, modenum, originalnummodes, existingmode, numlowresmodes;
1230         int             j, bpp, done;
1231         BOOL    stat;
1232
1233 // enumerate >8 bpp modes
1234         originalnummodes = nummodes;
1235         modenum = 0;
1236
1237         do
1238         {
1239                 stat = EnumDisplaySettings (NULL, modenum, &devmode);
1240
1241                 if ((devmode.dmBitsPerPel >= 15) &&
1242                         (devmode.dmPelsWidth <= MAXWIDTH) &&
1243                         (devmode.dmPelsHeight <= MAXHEIGHT) &&
1244                         (nummodes < MAX_MODE_LIST))
1245                 {
1246                         devmode.dmFields = DM_BITSPERPEL |
1247                                                            DM_PELSWIDTH |
1248                                                            DM_PELSHEIGHT;
1249
1250                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) ==
1251                                         DISP_CHANGE_SUCCESSFUL)
1252                         {
1253                                 modelist[nummodes].type = MS_FULLDIB;
1254                                 modelist[nummodes].width = devmode.dmPelsWidth;
1255                                 modelist[nummodes].height = devmode.dmPelsHeight;
1256                                 modelist[nummodes].modenum = 0;
1257                                 modelist[nummodes].halfscreen = 0;
1258                                 modelist[nummodes].dib = 1;
1259                                 modelist[nummodes].fullscreen = 1;
1260                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1261                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d",
1262                                                  devmode.dmPelsWidth, devmode.dmPelsHeight,
1263                                                  devmode.dmBitsPerPel);
1264
1265                         // if the width is more than twice the height, reduce it by half because this
1266                         // is probably a dual-screen monitor
1267                                 if (!COM_CheckParm("-noadjustaspect"))
1268                                 {
1269                                         if (modelist[nummodes].width > (modelist[nummodes].height << 1))
1270                                         {
1271                                                 modelist[nummodes].width >>= 1;
1272                                                 modelist[nummodes].halfscreen = 1;
1273                                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d",
1274                                                                  modelist[nummodes].width,
1275                                                                  modelist[nummodes].height,
1276                                                                  modelist[nummodes].bpp);
1277                                         }
1278                                 }
1279
1280                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1281                                 {
1282                                         if ((modelist[nummodes].width == modelist[i].width)   &&
1283                                                 (modelist[nummodes].height == modelist[i].height) &&
1284                                                 (modelist[nummodes].bpp == modelist[i].bpp))
1285                                         {
1286                                                 existingmode = 1;
1287                                                 break;
1288                                         }
1289                                 }
1290
1291                                 if (!existingmode)
1292                                 {
1293                                         nummodes++;
1294                                 }
1295                         }
1296                 }
1297
1298                 modenum++;
1299         } while (stat);
1300
1301 // see if there are any low-res modes that aren't being reported
1302         numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]);
1303         bpp = 16;
1304         done = 0;
1305
1306         do
1307         {
1308                 for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++)
1309                 {
1310                         devmode.dmBitsPerPel = bpp;
1311                         devmode.dmPelsWidth = lowresmodes[j].width;
1312                         devmode.dmPelsHeight = lowresmodes[j].height;
1313                         devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1314
1315                         if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) ==
1316                                         DISP_CHANGE_SUCCESSFUL)
1317                         {
1318                                 modelist[nummodes].type = MS_FULLDIB;
1319                                 modelist[nummodes].width = devmode.dmPelsWidth;
1320                                 modelist[nummodes].height = devmode.dmPelsHeight;
1321                                 modelist[nummodes].modenum = 0;
1322                                 modelist[nummodes].halfscreen = 0;
1323                                 modelist[nummodes].dib = 1;
1324                                 modelist[nummodes].fullscreen = 1;
1325                                 modelist[nummodes].bpp = devmode.dmBitsPerPel;
1326                                 sprintf (modelist[nummodes].modedesc, "%dx%dx%d",
1327                                                  devmode.dmPelsWidth, devmode.dmPelsHeight,
1328                                                  devmode.dmBitsPerPel);
1329
1330                                 for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++)
1331                                 {
1332                                         if ((modelist[nummodes].width == modelist[i].width)   &&
1333                                                 (modelist[nummodes].height == modelist[i].height) &&
1334                                                 (modelist[nummodes].bpp == modelist[i].bpp))
1335                                         {
1336                                                 existingmode = 1;
1337                                                 break;
1338                                         }
1339                                 }
1340
1341                                 if (!existingmode)
1342                                 {
1343                                         nummodes++;
1344                                 }
1345                         }
1346                 }
1347                 switch (bpp)
1348                 {
1349                         case 16:
1350                                 bpp = 32;
1351                                 break;
1352
1353                         case 32:
1354                                 bpp = 24;
1355                                 break;
1356
1357                         case 24:
1358                                 done = 1;
1359                                 break;
1360                 }
1361         } while (!done);
1362
1363         if (nummodes == originalnummodes)
1364                 Con_SafePrintf ("No fullscreen DIB modes found\n");
1365 }
1366
1367 qboolean VID_Is8bit()
1368 {
1369         return is8bit;
1370 }
1371
1372 #define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB
1373
1374 void VID_Init8bitPalette() 
1375 {
1376         // Check for 8bit Extensions and initialize them.
1377         int i;
1378         char thePalette[256*3];
1379         char *oldPalette, *newPalette;
1380         // LordHavoc: 8bit texture support broke many things...  it now must be specifically stated on the commandline (-no8bit became -8bit)
1381         if (!COM_CheckParm("-8bit"))
1382                 return;
1383         if (strstr(gl_extensions, "GL_EXT_shared_texture_palette"))
1384                 return;
1385         if (!(glColorTableEXT = (void *)wglGetProcAddress("glColorTableEXT")))
1386                 return;
1387
1388         Con_SafePrintf("8-bit GL extensions enabled.\n");
1389         glEnable( GL_SHARED_TEXTURE_PALETTE_EXT );
1390         oldPalette = (char *) d_8to24table;
1391         newPalette = thePalette;
1392         for (i=0;i<256;i++)
1393         {
1394                 *newPalette++ = *oldPalette++;
1395                 *newPalette++ = *oldPalette++;
1396                 *newPalette++ = *oldPalette++;
1397                 oldPalette++;
1398         }
1399         glColorTableEXT(GL_SHARED_TEXTURE_PALETTE_EXT, GL_RGB, 256, GL_RGB, GL_UNSIGNED_BYTE, (void *) thePalette);
1400         is8bit = TRUE;
1401 }
1402
1403 extern void Check_Gamma (unsigned char *pal);
1404 void VID_Setup15to8Palette ();
1405
1406 /*
1407 ===================
1408 VID_Init
1409 ===================
1410 */
1411 void    VID_Init (unsigned char *palette)
1412 {
1413         int             i, existingmode;
1414         int             basenummodes, width, height, bpp, findbpp, done;
1415 //      char    gldir[MAX_OSPATH];
1416         HDC             hdc;
1417         DEVMODE devmode;
1418
1419         memset(&devmode, 0, sizeof(devmode));
1420
1421         Cvar_RegisterVariable (&vid_mode);
1422         Cvar_RegisterVariable (&vid_wait);
1423         Cvar_RegisterVariable (&vid_nopageflip);
1424         Cvar_RegisterVariable (&_vid_wait_override);
1425         Cvar_RegisterVariable (&_vid_default_mode);
1426         Cvar_RegisterVariable (&_vid_default_mode_win);
1427         Cvar_RegisterVariable (&vid_config_x);
1428         Cvar_RegisterVariable (&vid_config_y);
1429         Cvar_RegisterVariable (&vid_stretch_by_2);
1430         Cvar_RegisterVariable (&_windowed_mouse);
1431
1432         Cmd_AddCommand ("vid_nummodes", VID_NumModes_f);
1433         Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f);
1434         Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f);
1435         Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f);
1436
1437         hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON2));
1438
1439         InitCommonControls();
1440
1441         VID_InitDIB (global_hInstance);
1442         basenummodes = nummodes = 1;
1443
1444         VID_InitFullDIB (global_hInstance);
1445
1446         if (COM_CheckParm("-window"))
1447         {
1448                 hdc = GetDC (NULL);
1449
1450                 if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE)
1451                 {
1452                         Sys_Error ("Can't run in non-RGB mode");
1453                 }
1454
1455                 ReleaseDC (NULL, hdc);
1456
1457                 windowed = true;
1458
1459                 vid_default = MODE_WINDOWED;
1460         }
1461         else
1462         {
1463                 if (nummodes == 1)
1464                         Sys_Error ("No RGB fullscreen modes available");
1465
1466                 windowed = false;
1467
1468                 if (COM_CheckParm("-mode"))
1469                 {
1470                         vid_default = atoi(com_argv[COM_CheckParm("-mode")+1]);
1471                 }
1472                 else
1473                 {
1474                         if (COM_CheckParm("-current"))
1475                         {
1476                                 modelist[MODE_FULLSCREEN_DEFAULT].width =
1477                                                 GetSystemMetrics (SM_CXSCREEN);
1478                                 modelist[MODE_FULLSCREEN_DEFAULT].height =
1479                                                 GetSystemMetrics (SM_CYSCREEN);
1480                                 vid_default = MODE_FULLSCREEN_DEFAULT;
1481                                 leavecurrentmode = 1;
1482                         }
1483                         else
1484                         {
1485                                 if (COM_CheckParm("-width"))
1486                                 {
1487                                         width = atoi(com_argv[COM_CheckParm("-width")+1]);
1488                                 }
1489                                 else
1490                                 {
1491                                         width = 640;
1492                                 }
1493
1494                                 if (COM_CheckParm("-bpp"))
1495                                 {
1496                                         bpp = atoi(com_argv[COM_CheckParm("-bpp")+1]);
1497                                         findbpp = 0;
1498                                 }
1499                                 else
1500                                 {
1501                                         bpp = 15;
1502                                         findbpp = 1;
1503                                 }
1504
1505                                 if (COM_CheckParm("-height"))
1506                                         height = atoi(com_argv[COM_CheckParm("-height")+1]);
1507
1508                         // if they want to force it, add the specified mode to the list
1509                                 if (COM_CheckParm("-force") && (nummodes < MAX_MODE_LIST))
1510                                 {
1511                                         modelist[nummodes].type = MS_FULLDIB;
1512                                         modelist[nummodes].width = width;
1513                                         modelist[nummodes].height = height;
1514                                         modelist[nummodes].modenum = 0;
1515                                         modelist[nummodes].halfscreen = 0;
1516                                         modelist[nummodes].dib = 1;
1517                                         modelist[nummodes].fullscreen = 1;
1518                                         modelist[nummodes].bpp = bpp;
1519                                         sprintf (modelist[nummodes].modedesc, "%dx%dx%d",
1520                                                          devmode.dmPelsWidth, devmode.dmPelsHeight,
1521                                                          devmode.dmBitsPerPel);
1522
1523                                         for (i=nummodes, existingmode = 0 ; i<nummodes ; i++)
1524                                         {
1525                                                 if ((modelist[nummodes].width == modelist[i].width)   &&
1526                                                         (modelist[nummodes].height == modelist[i].height) &&
1527                                                         (modelist[nummodes].bpp == modelist[i].bpp))
1528                                                 {
1529                                                         existingmode = 1;
1530                                                         break;
1531                                                 }
1532                                         }
1533
1534                                         if (!existingmode)
1535                                         {
1536                                                 nummodes++;
1537                                         }
1538                                 }
1539
1540                                 done = 0;
1541
1542                                 do
1543                                 {
1544                                         if (COM_CheckParm("-height"))
1545                                         {
1546                                                 height = atoi(com_argv[COM_CheckParm("-height")+1]);
1547
1548                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1549                                                 {
1550                                                         if ((modelist[i].width == width) &&
1551                                                                 (modelist[i].height == height) &&
1552                                                                 (modelist[i].bpp == bpp))
1553                                                         {
1554                                                                 vid_default = i;
1555                                                                 done = 1;
1556                                                                 break;
1557                                                         }
1558                                                 }
1559                                         }
1560                                         else
1561                                         {
1562                                                 for (i=1, vid_default=0 ; i<nummodes ; i++)
1563                                                 {
1564                                                         if ((modelist[i].width == width) && (modelist[i].bpp == bpp))
1565                                                         {
1566                                                                 vid_default = i;
1567                                                                 done = 1;
1568                                                                 break;
1569                                                         }
1570                                                 }
1571                                         }
1572
1573                                         if (!done)
1574                                         {
1575                                                 if (findbpp)
1576                                                 {
1577                                                         switch (bpp)
1578                                                         {
1579                                                         case 15:
1580                                                                 bpp = 16;
1581                                                                 break;
1582                                                         case 16:
1583                                                                 bpp = 32;
1584                                                                 break;
1585                                                         case 32:
1586                                                                 bpp = 24;
1587                                                                 break;
1588                                                         case 24:
1589                                                                 done = 1;
1590                                                                 break;
1591                                                         }
1592                                                 }
1593                                                 else
1594                                                 {
1595                                                         done = 1;
1596                                                 }
1597                                         }
1598                                 }
1599                                 while (!done);
1600
1601                                 if (!vid_default)
1602                                 {
1603                                         Sys_Error ("Specified video mode not available");
1604                                 }
1605                         }
1606                 }
1607         }
1608
1609         vid_initialized = true;
1610
1611         if ((i = COM_CheckParm("-conwidth")) != 0)
1612                 vid.conwidth = atoi(com_argv[i+1]);
1613         else
1614                 vid.conwidth = 640;
1615
1616         vid.conwidth &= 0xfff8; // make it a multiple of eight
1617
1618         if (vid.conwidth < 320)
1619                 vid.conwidth = 320;
1620
1621         // pick a conheight that matches with correct aspect
1622         vid.conheight = vid.conwidth*3 / 4;
1623
1624         if ((i = COM_CheckParm("-conheight")) != 0)
1625                 vid.conheight = atoi(com_argv[i+1]);
1626         if (vid.conheight < 200)
1627                 vid.conheight = 200;
1628
1629         DestroyWindow (hwnd_dialog);
1630
1631         VID_SetPalette (palette);
1632
1633         Check_Gamma(palette);
1634
1635         VID_SetMode (vid_default, palette);
1636
1637         maindc = GetDC(mainwindow);
1638         bSetupPixelFormat(maindc);
1639
1640         baseRC = wglCreateContext( maindc );
1641         if (!baseRC)
1642                 Sys_Error ("Could not initialize GL (wglCreateContext failed).\n\nMake sure you are in 65536 color mode, and try running -window.");
1643         if (!wglMakeCurrent( maindc, baseRC ))
1644                 Sys_Error ("wglMakeCurrent failed");
1645
1646         GL_Init ();
1647
1648 //      sprintf (gldir, "%s/glquake", com_gamedir);
1649 //      Sys_mkdir (gldir);
1650
1651         vid_realmode = vid_modenum;
1652
1653         VID_Init8bitPalette();
1654
1655         if (is8bit) // LordHavoc: avoid calculating 15to8 table if it won't be used
1656                 VID_Setup15to8Palette ();
1657
1658         vid_menudrawfn = VID_MenuDraw;
1659         vid_menukeyfn = VID_MenuKey;
1660
1661         strcpy (badmode.modedesc, "Bad mode");
1662         vid_canalttab = true;
1663 }
1664
1665
1666 //========================================================
1667 // Video menu stuff
1668 //========================================================
1669
1670 extern void M_Menu_Options_f (void);
1671 extern void M_Print (int cx, int cy, char *str);
1672 extern void M_PrintWhite (int cx, int cy, char *str);
1673 extern void M_DrawCharacter (int cx, int line, int num);
1674 extern void M_DrawPic (int x, int y, qpic_t *pic);
1675
1676 static int      vid_line, vid_wmodes;
1677
1678 typedef struct
1679 {
1680         int             modenum;
1681         char    *desc;
1682         int             iscur;
1683 } modedesc_t;
1684
1685 #define MAX_COLUMN_SIZE         9
1686 #define MODE_AREA_HEIGHT        (MAX_COLUMN_SIZE + 2)
1687 #define MAX_MODEDESCS           (MAX_COLUMN_SIZE*3)
1688
1689 static modedesc_t       modedescs[MAX_MODEDESCS];
1690
1691 /*
1692 ================
1693 VID_MenuDraw
1694 ================
1695 */
1696 void VID_MenuDraw (void)
1697 {
1698         qpic_t          *p;
1699         char            *ptr;
1700         int                     lnummodes, i, k, column, row;
1701         vmode_t         *pv;
1702
1703         p = Draw_CachePic ("gfx/vidmodes.lmp");
1704         M_DrawPic ( (320-p->width)/2, 4, p);
1705
1706         vid_wmodes = 0;
1707         lnummodes = VID_NumModes ();
1708         
1709         for (i=1 ; (i<lnummodes) && (vid_wmodes < MAX_MODEDESCS) ; i++)
1710         {
1711                 ptr = VID_GetModeDescription (i);
1712                 pv = VID_GetModePtr (i);
1713
1714                 k = vid_wmodes;
1715
1716                 modedescs[k].modenum = i;
1717                 modedescs[k].desc = ptr;
1718                 modedescs[k].iscur = 0;
1719
1720                 if (i == vid_modenum)
1721                         modedescs[k].iscur = 1;
1722
1723                 vid_wmodes++;
1724
1725         }
1726
1727         if (vid_wmodes > 0)
1728         {
1729                 M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)");
1730
1731                 column = 8;
1732                 row = 36+2*8;
1733
1734                 for (i=0 ; i<vid_wmodes ; i++)
1735                 {
1736                         if (modedescs[i].iscur)
1737                                 M_PrintWhite (column, row, modedescs[i].desc);
1738                         else
1739                                 M_Print (column, row, modedescs[i].desc);
1740
1741                         column += 13*8;
1742
1743                         if ((i % VID_ROW_SIZE) == (VID_ROW_SIZE - 1))
1744                         {
1745                                 column = 8;
1746                                 row += 8;
1747                         }
1748                 }
1749         }
1750
1751         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*2,
1752                          "Video modes must be set from the");
1753         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3,
1754                          "command line with -width <width>");
1755         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4,
1756                          "and -bpp <bits-per-pixel>");
1757         M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6,
1758                          "Select windowed mode with -window");
1759 }
1760
1761
1762 /*
1763 ================
1764 VID_MenuKey
1765 ================
1766 */
1767 void VID_MenuKey (int key)
1768 {
1769         switch (key)
1770         {
1771         case K_ESCAPE:
1772                 S_LocalSound ("misc/menu1.wav");
1773                 M_Menu_Options_f ();
1774                 break;
1775
1776         default:
1777                 break;
1778         }
1779 }