]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cl_screen.c
b268e8448396ccd256720384d5a942464f5723a2
[xonotic/darkplaces.git] / cl_screen.c
1
2 #include "quakedef.h"
3 #include "cl_video.h"
4 #include "image.h"
5 #include "jpeg.h"
6 #include "cl_collision.h"
7 #include "libcurl.h"
8 #include "csprogs.h"
9
10 // we have to include snd_main.h here only to get access to snd_renderbuffer->format.speed when writing the AVI headers
11 #include "snd_main.h"
12
13 cvar_t scr_viewsize = {CVAR_SAVE, "viewsize","100", "how large the view should be, 110 disables inventory bar, 120 disables status bar"};
14 cvar_t scr_fov = {CVAR_SAVE, "fov","90", "field of vision, 1-170 degrees, default 90, some players use 110-130"};
15 cvar_t scr_conalpha = {CVAR_SAVE, "scr_conalpha", "1", "opacity of console background"};
16 cvar_t scr_conbrightness = {CVAR_SAVE, "scr_conbrightness", "1", "brightness of console background (0 = black, 1 = image)"};
17 cvar_t scr_conforcewhiledisconnected = {0, "scr_conforcewhiledisconnected", "1", "forces fullscreen console while disconnected"};
18 cvar_t scr_menuforcewhiledisconnected = {0, "scr_menuforcewhiledisconnected", "0", "forces menu while disconnected"};
19 cvar_t scr_centertime = {0, "scr_centertime","2", "how long centerprint messages show"};
20 cvar_t scr_showram = {CVAR_SAVE, "showram","1", "show ram icon if low on surface cache memory (not used)"};
21 cvar_t scr_showturtle = {CVAR_SAVE, "showturtle","0", "show turtle icon when framerate is too low"};
22 cvar_t scr_showpause = {CVAR_SAVE, "showpause","1", "show pause icon when game is paused"};
23 cvar_t scr_showbrand = {0, "showbrand","0", "shows gfx/brand.tga in a corner of the screen (different values select different positions, including centered)"};
24 cvar_t scr_printspeed = {0, "scr_printspeed","0", "speed of intermission printing (episode end texts), a value of 0 disables the slow printing"};
25 cvar_t vid_conwidth = {CVAR_SAVE, "vid_conwidth", "640", "virtual width of 2D graphics system"};
26 cvar_t vid_conheight = {CVAR_SAVE, "vid_conheight", "480", "virtual height of 2D graphics system"};
27 cvar_t vid_pixelheight = {CVAR_SAVE, "vid_pixelheight", "1", "adjusts vertical field of vision to account for non-square pixels (1280x1024 on a CRT monitor for example)"};
28 cvar_t scr_screenshot_jpeg = {CVAR_SAVE, "scr_screenshot_jpeg","1", "save jpeg instead of targa"};
29 cvar_t scr_screenshot_jpeg_quality = {CVAR_SAVE, "scr_screenshot_jpeg_quality","0.9", "image quality of saved jpeg"};
30 cvar_t scr_screenshot_gammaboost = {CVAR_SAVE, "scr_screenshot_gammaboost","1", "gamma correction on saved screenshots and videos, 1.0 saves unmodified images"};
31 // scr_screenshot_name is defined in fs.c
32 cvar_t cl_capturevideo = {0, "cl_capturevideo", "0", "enables saving of video to a .avi file using uncompressed I420 colorspace and PCM audio, note that scr_screenshot_gammaboost affects the brightness of the output)"};
33 cvar_t cl_capturevideo_realtime = {0, "cl_capturevideo_realtime", "0", "causes video saving to operate in realtime (mostly useful while playing, not while capturing demos), this can produce a much lower quality video due to poor sound/video sync and will abort saving if your machine stalls for over 1 second"};
34 cvar_t cl_capturevideo_fps = {0, "cl_capturevideo_fps", "30", "how many frames per second to save (29.97 for NTSC, 30 for typical PC video, 15 can be useful)"};
35 cvar_t cl_capturevideo_number = {CVAR_SAVE, "cl_capturevideo_number", "1", "number to append to video filename, incremented each time a capture begins"};
36 cvar_t r_letterbox = {0, "r_letterbox", "0", "reduces vertical height of view to simulate a letterboxed movie effect (can be used by mods for cutscenes)"};
37 cvar_t r_stereo_separation = {0, "r_stereo_separation", "4", "separation of eyes in the world (try negative values too)"};
38 cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0", "side by side views (for those who can't afford glasses but can afford eye strain)"};
39 cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
40 cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0", "red/cyan anaglyph stereo glasses, the kind given away at drive-in movies like Creature From The Black Lagoon In 3D"};
41 cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
42 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0", "displays a zoomed in overlay window"};
43 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20", "horizontal viewsize of zoom window"};
44 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20", "vertical viewsize of zoom window"};
45 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20", "fov of zoom window"};
46 cvar_t scr_stipple = {0, "scr_stipple", "0", "interlacing-like stippling of the display"};
47 cvar_t scr_refresh = {0, "scr_refresh", "1", "allows you to completely shut off rendering for benchmarking purposes"};
48
49
50 int jpeg_supported = false;
51
52 qboolean        scr_initialized;                // ready to draw
53
54 float           scr_con_current;
55
56 extern int      con_vislines;
57
58 static void SCR_ScreenShot_f (void);
59 static void R_Envmap_f (void);
60
61 // backend
62 void R_ClearScreen(void);
63
64 /*
65 ===============================================================================
66
67 CENTER PRINTING
68
69 ===============================================================================
70 */
71
72 char            scr_centerstring[MAX_INPUTLINE];
73 float           scr_centertime_start;   // for slow victory printing
74 float           scr_centertime_off;
75 int                     scr_center_lines;
76 int                     scr_erase_lines;
77 int                     scr_erase_center;
78
79 /*
80 ==============
81 SCR_CenterPrint
82
83 Called for important messages that should stay in the center of the screen
84 for a few moments
85 ==============
86 */
87 void SCR_CenterPrint(char *str)
88 {
89         strlcpy (scr_centerstring, str, sizeof (scr_centerstring));
90         scr_centertime_off = scr_centertime.value;
91         scr_centertime_start = cl.time;
92
93 // count the number of lines for centering
94         scr_center_lines = 1;
95         while (*str)
96         {
97                 if (*str == '\n')
98                         scr_center_lines++;
99                 str++;
100         }
101 }
102
103
104 void SCR_DrawCenterString (void)
105 {
106         char    *start;
107         int             l;
108         int             x, y;
109         int             remaining;
110         int             color;
111
112 // the finale prints the characters one at a time, except if printspeed is an absurdly high value
113         if (cl.intermission && scr_printspeed.value > 0 && scr_printspeed.value < 1000000)
114                 remaining = (int)(scr_printspeed.value * (cl.time - scr_centertime_start));
115         else
116                 remaining = 9999;
117
118         scr_erase_center = 0;
119         start = scr_centerstring;
120
121         if (remaining < 1)
122                 return;
123
124         if (scr_center_lines <= 4)
125                 y = (int)(vid_conheight.integer*0.35);
126         else
127                 y = 48;
128
129         color = -1;
130         do
131         {
132                 // scan the number of characters on the line, not counting color codes
133                 int chars = 0;
134                 for (l=0 ; l<vid_conwidth.integer/8 ; l++)
135                 {
136                         if (start[l] == '\n' || !start[l])
137                                 break;
138                         // color codes add no visible characters, so don't count them
139                         if (start[l] == STRING_COLOR_TAG && (start[l+1] >= '0' && start[l+1] <= '9'))
140                                 l++;
141                         else
142                                 chars++;
143                 }
144                 x = (vid_conwidth.integer - chars*8)/2;
145                 if (l > 0)
146                 {
147                         if (remaining < l)
148                                 l = remaining;
149                         DrawQ_ColoredString(x, y, start, l, 8, 8, 1, 1, 1, 1, 0, &color);
150                         remaining -= l;
151                         if (remaining <= 0)
152                                 return;
153                 }
154
155                 y += 8;
156
157                 while (*start && *start != '\n')
158                         start++;
159
160                 if (!*start)
161                         break;
162                 start++;                // skip the \n
163         } while (1);
164 }
165
166 void SCR_CheckDrawCenterString (void)
167 {
168         if (scr_center_lines > scr_erase_lines)
169                 scr_erase_lines = scr_center_lines;
170
171         if (cl.time > cl.oldtime)
172                 scr_centertime_off -= cl.time - cl.oldtime;
173
174         // don't draw if this is a normal stats-screen intermission,
175         // only if it is not an intermission, or a finale intermission
176         if (cl.intermission == 1)
177                 return;
178         if (scr_centertime_off <= 0 && !cl.intermission)
179                 return;
180         if (key_dest != key_game)
181                 return;
182
183         SCR_DrawCenterString ();
184 }
185
186 /*
187 ==============
188 SCR_DrawTurtle
189 ==============
190 */
191 void SCR_DrawTurtle (void)
192 {
193         static int      count;
194
195         if (cls.state != ca_connected)
196                 return;
197
198         if (!scr_showturtle.integer)
199                 return;
200
201         if (cl.realframetime < 0.1)
202         {
203                 count = 0;
204                 return;
205         }
206
207         count++;
208         if (count < 3)
209                 return;
210
211         DrawQ_Pic (0, 0, Draw_CachePic("gfx/turtle", true), 0, 0, 1, 1, 1, 1, 0);
212 }
213
214 /*
215 ==============
216 SCR_DrawNet
217 ==============
218 */
219 void SCR_DrawNet (void)
220 {
221         if (cls.state != ca_connected)
222                 return;
223         if (realtime - cl.last_received_message < 0.3)
224                 return;
225         if (cls.demoplayback)
226                 return;
227
228         DrawQ_Pic (64, 0, Draw_CachePic("gfx/net", true), 0, 0, 1, 1, 1, 1, 0);
229 }
230
231 /*
232 ==============
233 DrawPause
234 ==============
235 */
236 void SCR_DrawPause (void)
237 {
238         cachepic_t      *pic;
239
240         if (cls.state != ca_connected)
241                 return;
242
243         if (!scr_showpause.integer)             // turn off for screenshots
244                 return;
245
246         if (!cl.paused)
247                 return;
248
249         pic = Draw_CachePic ("gfx/pause", true);
250         DrawQ_Pic ((vid_conwidth.integer - pic->width)/2, (vid_conheight.integer - pic->height)/2, pic, 0, 0, 1, 1, 1, 1, 0);
251 }
252
253 /*
254 ==============
255 SCR_DrawBrand
256 ==============
257 */
258 void SCR_DrawBrand (void)
259 {
260         cachepic_t      *pic;
261         float           x, y;
262
263         if (!scr_showbrand.value)
264                 return;
265
266         pic = Draw_CachePic ("gfx/brand", true);
267
268         switch ((int)scr_showbrand.value)
269         {
270         case 1: // bottom left
271                 x = 0;
272                 y = vid_conheight.integer - pic->height;
273                 break;
274         case 2: // bottom centre
275                 x = (vid_conwidth.integer - pic->width) / 2;
276                 y = vid_conheight.integer - pic->height;
277                 break;
278         case 3: // bottom right
279                 x = vid_conwidth.integer - pic->width;
280                 y = vid_conheight.integer - pic->height;
281                 break;
282         case 4: // centre right
283                 x = vid_conwidth.integer - pic->width;
284                 y = (vid_conheight.integer - pic->height) / 2;
285                 break;
286         case 5: // top right
287                 x = vid_conwidth.integer - pic->width;
288                 y = 0;
289                 break;
290         case 6: // top centre
291                 x = (vid_conwidth.integer - pic->width) / 2;
292                 y = 0;
293                 break;
294         case 7: // top left
295                 x = 0;
296                 y = 0;
297                 break;
298         case 8: // centre left
299                 x = 0;
300                 y = (vid_conheight.integer - pic->height) / 2;
301                 break;
302         default:
303                 return;
304         }
305
306         DrawQ_Pic (x, y, pic, 0, 0, 1, 1, 1, 1, 0);
307 }
308
309 /*
310 ==============
311 SCR_DrawQWDownload
312 ==============
313 */
314 static int SCR_DrawQWDownload(int offset)
315 {
316         int len;
317         float x, y;
318         float size = 8;
319         char temp[256];
320         if (!cls.qw_downloadname[0])
321         {
322                 cls.qw_downloadspeedrate = 0;
323                 cls.qw_downloadspeedtime = realtime;
324                 cls.qw_downloadspeedcount = 0;
325                 return 0;
326         }
327         if (realtime >= cls.qw_downloadspeedtime + 1)
328         {
329                 cls.qw_downloadspeedrate = cls.qw_downloadspeedcount;
330                 cls.qw_downloadspeedtime = realtime;
331                 cls.qw_downloadspeedcount = 0;
332         }
333         if (cls.protocol == PROTOCOL_QUAKEWORLD)
334                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i) at %i bytes/s\n", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadspeedrate);
335         else
336                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i/%i) at %i bytes/s\n", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize, cls.qw_downloadspeedrate);
337         len = (int)strlen(temp);
338         x = (vid_conwidth.integer - len*size) / 2;
339         y = vid_conheight.integer - size - offset;
340         DrawQ_Pic(0, y, NULL, vid_conwidth.integer, size, 0, 0, 0, 0.5, 0);
341         DrawQ_String(x, y, temp, len, size, size, 1, 1, 1, 1, 0);
342         return 8;
343 }
344
345 /*
346 ==============
347 SCR_DrawCurlDownload
348 ==============
349 */
350 static int SCR_DrawCurlDownload(int offset)
351 {
352         int len;
353         int nDownloads;
354         int i;
355         float x, y;
356         float size = 8;
357         Curl_downloadinfo_t *downinfo;
358         char temp[256];
359         const char *addinfo;
360
361         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo);
362         if(!downinfo)
363                 return 0;
364
365         y = vid_conheight.integer - size * nDownloads - offset;
366
367         if(addinfo)
368         {
369                 len = (int)strlen(addinfo);
370                 x = (vid_conwidth.integer - len*size) / 2;
371                 DrawQ_Pic(0, y - size, NULL, vid_conwidth.integer, size, 1, 1, 1, 0.8, 0);
372                 DrawQ_String(x, y - size, addinfo, len, size, size, 0, 0, 0, 1, 0);
373         }
374
375         for(i = 0; i != nDownloads; ++i)
376         {
377                 if(downinfo[i].queued)
378                         dpsnprintf(temp, sizeof(temp), "Still in queue: %s\n", downinfo[i].filename);
379                 else if(downinfo[i].progress <= 0)
380                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  ???.?%% @ %.1f KiB/s\n", downinfo[i].filename, downinfo[i].speed / 1024.0);
381                 else
382                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  %5.1f%% @ %.1f KiB/s\n", downinfo[i].filename, 100.0 * downinfo[i].progress, downinfo[i].speed / 1024.0);
383                 len = (int)strlen(temp);
384                 x = (vid_conwidth.integer - len*size) / 2;
385                 DrawQ_Pic(0, y + i * size, NULL, vid_conwidth.integer, size, 0, 0, 0, 0.8, 0);
386                 DrawQ_String(x, y + i * size, temp, len, size, size, 1, 1, 1, 1, 0);
387         }
388
389         Z_Free(downinfo);
390
391         return 8 * (nDownloads + (addinfo ? 1 : 0));
392 }
393
394 /*
395 ==============
396 SCR_DrawDownload
397 ==============
398 */
399 static void SCR_DrawDownload()
400 {
401         int offset = 0;
402         offset += SCR_DrawQWDownload(offset);
403         offset += SCR_DrawCurlDownload(offset);
404 }
405
406 //=============================================================================
407
408 /*
409 ==================
410 SCR_SetUpToDrawConsole
411 ==================
412 */
413 void SCR_SetUpToDrawConsole (void)
414 {
415         // lines of console to display
416         float conlines;
417         static int framecounter = 0;
418
419         Con_CheckResize ();
420
421         if (scr_menuforcewhiledisconnected.integer && key_dest == key_game && cls.state == ca_disconnected)
422         {
423                 if (framecounter >= 2)
424                         MR_ToggleMenu_f();
425                 else
426                         framecounter++;
427         }
428         else
429                 framecounter = 0;
430
431         if (scr_conforcewhiledisconnected.integer && key_dest == key_game && cls.signon != SIGNONS)
432                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
433         else
434                 key_consoleactive &= ~KEY_CONSOLEACTIVE_FORCED;
435
436 // decide on the height of the console
437         if (key_consoleactive & KEY_CONSOLEACTIVE_USER)
438                 conlines = vid_conheight.integer/2;     // half screen
439         else
440                 conlines = 0;                           // none visible
441
442         scr_con_current = conlines;
443 }
444
445 /*
446 ==================
447 SCR_DrawConsole
448 ==================
449 */
450 void SCR_DrawConsole (void)
451 {
452         if (key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
453         {
454                 // full screen
455                 Con_DrawConsole (vid_conheight.integer);
456         }
457         else if (scr_con_current)
458                 Con_DrawConsole ((int)scr_con_current);
459         else
460         {
461                 con_vislines = 0;
462                 if ((key_dest == key_game || key_dest == key_message) && !r_letterbox.value)
463                         Con_DrawNotify ();      // only draw notify in game
464         }
465 }
466
467 /*
468 ===============
469 SCR_BeginLoadingPlaque
470
471 ================
472 */
473 void SCR_BeginLoadingPlaque (void)
474 {
475         // save console log up to this point to log_file if it was set by configs
476         Log_Start();
477
478         Host_StartVideo();
479         S_StopAllSounds();
480         SCR_UpdateLoadingScreen(false);
481 }
482
483 //=============================================================================
484
485 char r_speeds_string[1024];
486 int speedstringcount, r_timereport_active;
487 double r_timereport_temp = 0, r_timereport_current = 0, r_timereport_start = 0;
488
489 void R_TimeReport(char *desc)
490 {
491         char tempbuf[256];
492         int length;
493         int t;
494
495         if (r_speeds.integer < 2 || !r_timereport_active)
496                 return;
497
498         CHECKGLERROR
499         qglFinish();CHECKGLERROR
500         r_timereport_temp = r_timereport_current;
501         r_timereport_current = Sys_DoubleTime();
502         t = (int) ((r_timereport_current - r_timereport_temp) * 1000000.0 + 0.5);
503
504         dpsnprintf(tempbuf, sizeof(tempbuf), "%8i %-11s", t, desc);
505         length = (int)strlen(tempbuf);
506         if (speedstringcount + length > (vid_conwidth.integer / 8))
507         {
508                 strlcat(r_speeds_string, "\n", sizeof(r_speeds_string));
509                 speedstringcount = 0;
510         }
511         strlcat(r_speeds_string, tempbuf, sizeof(r_speeds_string));
512         speedstringcount += length;
513 }
514
515 void R_TimeReport_Frame(void)
516 {
517         int i, j, lines, y;
518         cl_locnode_t *loc;
519
520         if (r_speeds_string[0])
521         {
522                 if (r_timereport_active)
523                 {
524                         r_timereport_current = r_timereport_start;
525                         R_TimeReport("total");
526                 }
527
528                 if (r_speeds_string[strlen(r_speeds_string)-1] == '\n')
529                         r_speeds_string[strlen(r_speeds_string)-1] = 0;
530                 lines = 1;
531                 for (i = 0;r_speeds_string[i];i++)
532                         if (r_speeds_string[i] == '\n')
533                                 lines++;
534                 y = vid_conheight.integer - sb_lines - lines * 8;
535                 i = j = 0;
536                 DrawQ_Pic(0, y, NULL, vid_conwidth.integer, lines * 8, 0, 0, 0, 0.5, 0);
537                 while (r_speeds_string[i])
538                 {
539                         j = i;
540                         while (r_speeds_string[i] && r_speeds_string[i] != '\n')
541                                 i++;
542                         if (i - j > 0)
543                                 DrawQ_String(0, y, r_speeds_string + j, i - j, 8, 8, 1, 1, 1, 1, 0);
544                         if (r_speeds_string[i] == '\n')
545                                 i++;
546                         y += 8;
547                 }
548                 r_speeds_string[0] = 0;
549                 r_timereport_active = false;
550         }
551         if (r_speeds.integer && cls.signon == SIGNONS && cls.state == ca_connected)
552         {
553                 speedstringcount = 0;
554                 r_speeds_string[0] = 0;
555                 r_timereport_active = false;
556                 // put the location name in the r_speeds display as it greatly helps
557                 // when creating loc files
558                 loc = CL_Locs_FindNearest(cl.movement_origin);
559                 if (loc)
560                         sprintf(r_speeds_string + strlen(r_speeds_string), "Location: %s\n", loc->name);
561                 sprintf(r_speeds_string + strlen(r_speeds_string), "org:'%+8.2f %+8.2f %+8.2f' dir:'%+2.3f %+2.3f %+2.3f'\n", r_view.origin[0], r_view.origin[1], r_view.origin[2], r_view.forward[0], r_view.forward[1], r_view.forward[2]);
562                 sprintf(r_speeds_string + strlen(r_speeds_string), "%5i entities%6i surfaces%6i triangles%5i leafs%5i portals%6i particles\n", r_refdef.stats.entities, r_refdef.stats.entities_surfaces, r_refdef.stats.entities_triangles, r_refdef.stats.world_leafs, r_refdef.stats.world_portals, r_refdef.stats.particles);
563                 sprintf(r_speeds_string + strlen(r_speeds_string), "%4i lights%4i clears%4i scissored%7i light%7i shadow%7i dynamic\n", r_refdef.stats.lights, r_refdef.stats.lights_clears, r_refdef.stats.lights_scissored, r_refdef.stats.lights_lighttriangles, r_refdef.stats.lights_shadowtriangles, r_refdef.stats.lights_dynamicshadowtriangles);
564                 if (r_refdef.stats.bloom)
565                         sprintf(r_speeds_string + strlen(r_speeds_string), "rendered%6i meshes%8i triangles bloompixels%8i copied%8i drawn\n", r_refdef.stats.meshes, r_refdef.stats.meshes_elements / 3, r_refdef.stats.bloom_copypixels, r_refdef.stats.bloom_drawpixels);
566                 else
567                         sprintf(r_speeds_string + strlen(r_speeds_string), "rendered%6i meshes%8i triangles\n", r_refdef.stats.meshes, r_refdef.stats.meshes_elements / 3);
568
569                 memset(&r_refdef.stats, 0, sizeof(r_refdef.stats));
570
571                 if (r_speeds.integer >= 2)
572                 {
573                         r_timereport_active = true;
574                         r_timereport_start = r_timereport_current = Sys_DoubleTime();
575                 }
576         }
577 }
578
579 /*
580 =================
581 SCR_SizeUp_f
582
583 Keybinding command
584 =================
585 */
586 void SCR_SizeUp_f (void)
587 {
588         Cvar_SetValue ("viewsize",scr_viewsize.value+10);
589 }
590
591
592 /*
593 =================
594 SCR_SizeDown_f
595
596 Keybinding command
597 =================
598 */
599 void SCR_SizeDown_f (void)
600 {
601         Cvar_SetValue ("viewsize",scr_viewsize.value-10);
602 }
603
604 void CL_Screen_Init(void)
605 {
606         Cvar_RegisterVariable (&scr_fov);
607         Cvar_RegisterVariable (&scr_viewsize);
608         Cvar_RegisterVariable (&scr_conalpha);
609         Cvar_RegisterVariable (&scr_conbrightness);
610         Cvar_RegisterVariable (&scr_conforcewhiledisconnected);
611         Cvar_RegisterVariable (&scr_menuforcewhiledisconnected);
612         Cvar_RegisterVariable (&scr_showram);
613         Cvar_RegisterVariable (&scr_showturtle);
614         Cvar_RegisterVariable (&scr_showpause);
615         Cvar_RegisterVariable (&scr_showbrand);
616         Cvar_RegisterVariable (&scr_centertime);
617         Cvar_RegisterVariable (&scr_printspeed);
618         Cvar_RegisterVariable (&vid_conwidth);
619         Cvar_RegisterVariable (&vid_conheight);
620         Cvar_RegisterVariable (&vid_pixelheight);
621         Cvar_RegisterVariable (&scr_screenshot_jpeg);
622         Cvar_RegisterVariable (&scr_screenshot_jpeg_quality);
623         Cvar_RegisterVariable (&scr_screenshot_gammaboost);
624         Cvar_RegisterVariable (&cl_capturevideo);
625         Cvar_RegisterVariable (&cl_capturevideo_realtime);
626         Cvar_RegisterVariable (&cl_capturevideo_fps);
627         Cvar_RegisterVariable (&cl_capturevideo_number);
628         Cvar_RegisterVariable (&r_letterbox);
629         Cvar_RegisterVariable(&r_stereo_separation);
630         Cvar_RegisterVariable(&r_stereo_sidebyside);
631         Cvar_RegisterVariable(&r_stereo_redblue);
632         Cvar_RegisterVariable(&r_stereo_redcyan);
633         Cvar_RegisterVariable(&r_stereo_redgreen);
634         Cvar_RegisterVariable(&scr_zoomwindow);
635         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
636         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
637         Cvar_RegisterVariable(&scr_zoomwindow_fov);
638         Cvar_RegisterVariable(&scr_stipple);
639         Cvar_RegisterVariable(&scr_refresh);
640
641         Cmd_AddCommand ("sizeup",SCR_SizeUp_f, "increase view size (increases viewsize cvar)");
642         Cmd_AddCommand ("sizedown",SCR_SizeDown_f, "decrease view size (decreases viewsize cvar)");
643         Cmd_AddCommand ("screenshot",SCR_ScreenShot_f, "takes a screenshot of the next rendered frame");
644         Cmd_AddCommand ("envmap", R_Envmap_f, "render a cubemap (skybox) of the current scene");
645
646         scr_initialized = true;
647 }
648
649 /*
650 ==================
651 SCR_ScreenShot_f
652 ==================
653 */
654 void SCR_ScreenShot_f (void)
655 {
656         static int shotnumber;
657         static char oldname[MAX_QPATH];
658         char base[MAX_QPATH];
659         char filename[MAX_QPATH];
660         unsigned char *buffer1;
661         unsigned char *buffer2;
662         unsigned char *buffer3;
663         qboolean jpeg = (scr_screenshot_jpeg.integer != 0);
664
665         sprintf (base, "screenshots/%s", scr_screenshot_name.string);
666
667         if (strcmp (oldname, scr_screenshot_name.string))
668         {
669                 sprintf(oldname, "%s", scr_screenshot_name.string);
670                 shotnumber = 0;
671         }
672
673         // find a file name to save it to
674         for (;shotnumber < 1000000;shotnumber++)
675                 if (!FS_SysFileExists(va("%s/%s%06d.tga", fs_gamedir, base, shotnumber)) && !FS_SysFileExists(va("%s/%s%06d.jpg", fs_gamedir, base, shotnumber)))
676                         break;
677         if (shotnumber >= 1000000)
678         {
679                 Con_Print("SCR_ScreenShot_f: Couldn't create the image file\n");
680                 return;
681         }
682
683         sprintf(filename, "%s%06d.%s", base, shotnumber, jpeg ? "jpg" : "tga");
684
685         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3);
686         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3);
687         buffer3 = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * 3 + 18);
688
689         if (SCR_ScreenShot (filename, buffer1, buffer2, buffer3, 0, 0, vid.width, vid.height, false, false, false, jpeg, true))
690                 Con_Printf("Wrote %s\n", filename);
691         else
692                 Con_Printf("unable to write %s\n", filename);
693
694         Mem_Free (buffer1);
695         Mem_Free (buffer2);
696         Mem_Free (buffer3);
697
698         shotnumber++;
699 }
700
701 static void SCR_CaptureVideo_RIFF_Start(void)
702 {
703         memset(&cls.capturevideo.riffbuffer, 0, sizeof(sizebuf_t));
704         cls.capturevideo.riffbuffer.maxsize = sizeof(cls.capturevideo.riffbufferdata);
705         cls.capturevideo.riffbuffer.data = cls.capturevideo.riffbufferdata;
706 }
707
708 static void SCR_CaptureVideo_RIFF_Flush(void)
709 {
710         if (cls.capturevideo.riffbuffer.cursize > 0)
711         {
712                 if (!FS_Write(cls.capturevideo.videofile, cls.capturevideo.riffbuffer.data, cls.capturevideo.riffbuffer.cursize))
713                         cls.capturevideo.error = true;
714                 cls.capturevideo.riffbuffer.cursize = 0;
715                 cls.capturevideo.riffbuffer.overflowed = false;
716         }
717 }
718
719 static void SCR_CaptureVideo_RIFF_WriteBytes(const unsigned char *data, size_t size)
720 {
721         SCR_CaptureVideo_RIFF_Flush();
722         if (!FS_Write(cls.capturevideo.videofile, data, size))
723                 cls.capturevideo.error = true;
724 }
725
726 static void SCR_CaptureVideo_RIFF_Write32(int n)
727 {
728         if (cls.capturevideo.riffbuffer.cursize + 4 > cls.capturevideo.riffbuffer.maxsize)
729                 SCR_CaptureVideo_RIFF_Flush();
730         MSG_WriteLong(&cls.capturevideo.riffbuffer, n);
731 }
732
733 static void SCR_CaptureVideo_RIFF_Write16(int n)
734 {
735         if (cls.capturevideo.riffbuffer.cursize + 2 > cls.capturevideo.riffbuffer.maxsize)
736                 SCR_CaptureVideo_RIFF_Flush();
737         MSG_WriteShort(&cls.capturevideo.riffbuffer, n);
738 }
739
740 static void SCR_CaptureVideo_RIFF_WriteFourCC(const char *chunkfourcc)
741 {
742         if (cls.capturevideo.riffbuffer.cursize + (int)strlen(chunkfourcc) > cls.capturevideo.riffbuffer.maxsize)
743                 SCR_CaptureVideo_RIFF_Flush();
744         MSG_WriteUnterminatedString(&cls.capturevideo.riffbuffer, chunkfourcc);
745 }
746
747 static void SCR_CaptureVideo_RIFF_WriteTerminatedString(const char *string)
748 {
749         if (cls.capturevideo.riffbuffer.cursize + (int)strlen(string) > cls.capturevideo.riffbuffer.maxsize)
750                 SCR_CaptureVideo_RIFF_Flush();
751         MSG_WriteString(&cls.capturevideo.riffbuffer, string);
752 }
753
754 static fs_offset_t SCR_CaptureVideo_RIFF_GetPosition(void)
755 {
756         SCR_CaptureVideo_RIFF_Flush();
757         return FS_Tell(cls.capturevideo.videofile);
758 }
759
760 static void SCR_CaptureVideo_RIFF_Push(const char *chunkfourcc, const char *listtypefourcc)
761 {
762         SCR_CaptureVideo_RIFF_WriteFourCC(chunkfourcc);
763         SCR_CaptureVideo_RIFF_Write32(0);
764         SCR_CaptureVideo_RIFF_Flush();
765         cls.capturevideo.riffstackstartoffset[cls.capturevideo.riffstacklevel++] = SCR_CaptureVideo_RIFF_GetPosition();
766         if (listtypefourcc)
767                 SCR_CaptureVideo_RIFF_WriteFourCC(listtypefourcc);
768 }
769
770 static void SCR_CaptureVideo_RIFF_Pop(void)
771 {
772         fs_offset_t offset;
773         int x;
774         unsigned char sizebytes[4];
775         // write out the chunk size and then return to the current file position
776         cls.capturevideo.riffstacklevel--;
777         offset = SCR_CaptureVideo_RIFF_GetPosition();
778         x = (int)(offset - (cls.capturevideo.riffstackstartoffset[cls.capturevideo.riffstacklevel]));
779         sizebytes[0] = (x) & 0xff;sizebytes[1] = (x >> 8) & 0xff;sizebytes[2] = (x >> 16) & 0xff;sizebytes[3] = (x >> 24) & 0xff;
780         FS_Seek(cls.capturevideo.videofile, -(x + 4), SEEK_END);
781         FS_Write(cls.capturevideo.videofile, sizebytes, 4);
782         FS_Seek(cls.capturevideo.videofile, 0, SEEK_END);
783         if (offset & 1)
784         {
785                 unsigned char c = 0;
786                 FS_Write(cls.capturevideo.videofile, &c, 1);
787         }
788 }
789
790 static void SCR_CaptureVideo_RIFF_IndexEntry(const char *chunkfourcc, int chunksize, int flags)
791 {
792         if (cls.capturevideo.riffstacklevel != 2)
793                 Sys_Error("SCR_Capturevideo_RIFF_IndexEntry: RIFF stack level is %i (should be 2)\n", cls.capturevideo.riffstacklevel);
794         if (cls.capturevideo.riffindexbuffer.cursize + 16 > cls.capturevideo.riffindexbuffer.maxsize)
795         {
796                 int oldsize = cls.capturevideo.riffindexbuffer.maxsize;
797                 unsigned char *olddata;
798                 olddata = cls.capturevideo.riffindexbuffer.data;
799                 cls.capturevideo.riffindexbuffer.maxsize = max(cls.capturevideo.riffindexbuffer.maxsize * 2, 4096);
800                 cls.capturevideo.riffindexbuffer.data = Mem_Alloc(tempmempool, cls.capturevideo.riffindexbuffer.maxsize);
801                 if (olddata)
802                 {
803                         memcpy(cls.capturevideo.riffindexbuffer.data, olddata, oldsize);
804                         Mem_Free(olddata);
805                 }
806         }
807         MSG_WriteUnterminatedString(&cls.capturevideo.riffindexbuffer, chunkfourcc);
808         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, flags);
809         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, (int)FS_Tell(cls.capturevideo.videofile) - cls.capturevideo.riffstackstartoffset[1]);
810         MSG_WriteLong(&cls.capturevideo.riffindexbuffer, chunksize);
811 }
812
813 static void SCR_CaptureVideo_RIFF_Finish(void)
814 {
815         // close the "movi" list
816         SCR_CaptureVideo_RIFF_Pop();
817         // write the idx1 chunk that we've been building while saving the frames
818         SCR_CaptureVideo_RIFF_Push("idx1", NULL);
819         SCR_CaptureVideo_RIFF_WriteBytes(cls.capturevideo.riffindexbuffer.data, cls.capturevideo.riffindexbuffer.cursize);
820         SCR_CaptureVideo_RIFF_Pop();
821         cls.capturevideo.riffindexbuffer.cursize = 0;
822         // pop the RIFF chunk itself
823         while (cls.capturevideo.riffstacklevel > 0)
824                 SCR_CaptureVideo_RIFF_Pop();
825         SCR_CaptureVideo_RIFF_Flush();
826 }
827
828 static void SCR_CaptureVideo_RIFF_OverflowCheck(int framesize)
829 {
830         fs_offset_t cursize;
831         if (cls.capturevideo.riffstacklevel != 2)
832                 Sys_Error("SCR_CaptureVideo_RIFF_OverflowCheck: chunk stack leakage!\n");
833         // check where we are in the file
834         SCR_CaptureVideo_RIFF_Flush();
835         cursize = SCR_CaptureVideo_RIFF_GetPosition() - cls.capturevideo.riffstackstartoffset[0];
836         // if this would overflow the windows limit of 1GB per RIFF chunk, we need
837         // to close the current RIFF chunk and open another for future frames
838         if (8 + cursize + framesize + cls.capturevideo.riffindexbuffer.cursize + 8 > 1<<30)
839         {
840                 SCR_CaptureVideo_RIFF_Finish();
841                 // begin a new 1GB extended section of the AVI
842                 SCR_CaptureVideo_RIFF_Push("RIFF", "AVIX");
843                 SCR_CaptureVideo_RIFF_Push("LIST", "movi");
844         }
845 }
846
847 void SCR_CaptureVideo_BeginVideo(void)
848 {
849         double gamma, g;
850         int width = vid.width, height = vid.height, x;
851         unsigned int i;
852         if (cls.capturevideo.active)
853                 return;
854         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
855         // soundrate is figured out on the first SoundFrame
856         cls.capturevideo.active = true;
857         cls.capturevideo.starttime = realtime;
858         cls.capturevideo.framerate = bound(1, cl_capturevideo_fps.value, 1000);
859         cls.capturevideo.soundrate = S_GetSoundRate();
860         cls.capturevideo.frame = 0;
861         cls.capturevideo.soundsampleframe = 0;
862         cls.capturevideo.realtime = cl_capturevideo_realtime.integer != 0;
863         cls.capturevideo.buffer = (unsigned char *)Mem_Alloc(tempmempool, vid.width * vid.height * (3+3+3) + 18);
864         gamma = 1.0/scr_screenshot_gammaboost.value;
865         dpsnprintf(cls.capturevideo.basename, sizeof(cls.capturevideo.basename), "video/dpvideo%03i", cl_capturevideo_number.integer);
866         Cvar_SetValueQuick(&cl_capturevideo_number, cl_capturevideo_number.integer + 1);
867
868         /*
869         for (i = 0;i < 256;i++)
870         {
871                 unsigned char j = (unsigned char)bound(0, 255*pow(i/255.0, gamma), 255);
872                 cls.capturevideo.rgbgammatable[0][i] = j;
873                 cls.capturevideo.rgbgammatable[1][i] = j;
874                 cls.capturevideo.rgbgammatable[2][i] = j;
875         }
876         */
877 /*
878 R = Y + 1.4075 * (Cr - 128);
879 G = Y + -0.3455 * (Cb - 128) + -0.7169 * (Cr - 128);
880 B = Y + 1.7790 * (Cb - 128);
881 Y = R *  .299 + G *  .587 + B *  .114;
882 Cb = R * -.169 + G * -.332 + B *  .500 + 128.;
883 Cr = R *  .500 + G * -.419 + B * -.0813 + 128.;
884 */
885         for (i = 0;i < 256;i++)
886         {
887                 g = 255*pow(i/255.0, gamma);
888                 // Y weights from RGB
889                 cls.capturevideo.rgbtoyuvscaletable[0][0][i] = (short)(g *  0.299);
890                 cls.capturevideo.rgbtoyuvscaletable[0][1][i] = (short)(g *  0.587);
891                 cls.capturevideo.rgbtoyuvscaletable[0][2][i] = (short)(g *  0.114);
892                 // Cb weights from RGB
893                 cls.capturevideo.rgbtoyuvscaletable[1][0][i] = (short)(g * -0.169);
894                 cls.capturevideo.rgbtoyuvscaletable[1][1][i] = (short)(g * -0.332);
895                 cls.capturevideo.rgbtoyuvscaletable[1][2][i] = (short)(g *  0.500);
896                 // Cr weights from RGB
897                 cls.capturevideo.rgbtoyuvscaletable[2][0][i] = (short)(g *  0.500);
898                 cls.capturevideo.rgbtoyuvscaletable[2][1][i] = (short)(g * -0.419);
899                 cls.capturevideo.rgbtoyuvscaletable[2][2][i] = (short)(g * -0.0813);
900                 // range reduction of YCbCr to valid signal range
901                 cls.capturevideo.yuvnormalizetable[0][i] = 16 + i * (236-16) / 256;
902                 cls.capturevideo.yuvnormalizetable[1][i] = 16 + i * (240-16) / 256;
903                 cls.capturevideo.yuvnormalizetable[2][i] = 16 + i * (240-16) / 256;
904         }
905
906         //if (cl_capturevideo_)
907         //{
908         //}
909         //else
910         {
911                 cls.capturevideo.format = CAPTUREVIDEOFORMAT_AVI_I420;
912                 cls.capturevideo.videofile = FS_Open (va("%s.avi", cls.capturevideo.basename), "wb", false, true);
913                 SCR_CaptureVideo_RIFF_Start();
914                 // enclosing RIFF chunk (there can be multiple of these in >1GB files, the later ones are "AVIX" instead of "AVI " and have no header/stream info)
915                 SCR_CaptureVideo_RIFF_Push("RIFF", "AVI ");
916                 // AVI main header
917                 SCR_CaptureVideo_RIFF_Push("LIST", "hdrl");
918                 SCR_CaptureVideo_RIFF_Push("avih", NULL);
919                 SCR_CaptureVideo_RIFF_Write32((int)(1000000.0 / cls.capturevideo.framerate)); // microseconds per frame
920                 SCR_CaptureVideo_RIFF_Write32(0); // max bytes per second
921                 SCR_CaptureVideo_RIFF_Write32(0); // padding granularity
922                 SCR_CaptureVideo_RIFF_Write32(0x910); // flags (AVIF_HASINDEX | AVIF_ISINTERLEAVED | AVIF_TRUSTCKTYPE)
923                 cls.capturevideo.videofile_totalframes_offset1 = SCR_CaptureVideo_RIFF_GetPosition();
924                 SCR_CaptureVideo_RIFF_Write32(0); // total frames
925                 SCR_CaptureVideo_RIFF_Write32(0); // initial frames
926                 if (cls.capturevideo.soundrate)
927                         SCR_CaptureVideo_RIFF_Write32(2); // number of streams
928                 else
929                         SCR_CaptureVideo_RIFF_Write32(1); // number of streams
930                 SCR_CaptureVideo_RIFF_Write32(0); // suggested buffer size
931                 SCR_CaptureVideo_RIFF_Write32(width); // width
932                 SCR_CaptureVideo_RIFF_Write32(height); // height
933                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[0]
934                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[1]
935                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[2]
936                 SCR_CaptureVideo_RIFF_Write32(0); // reserved[3]
937                 SCR_CaptureVideo_RIFF_Pop();
938                 // video stream info
939                 SCR_CaptureVideo_RIFF_Push("LIST", "strl");
940                 SCR_CaptureVideo_RIFF_Push("strh", "vids");
941                 SCR_CaptureVideo_RIFF_WriteFourCC("I420"); // stream fourcc (I420 colorspace, uncompressed)
942                 SCR_CaptureVideo_RIFF_Write32(0); // flags
943                 SCR_CaptureVideo_RIFF_Write16(0); // priority
944                 SCR_CaptureVideo_RIFF_Write16(0); // language
945                 SCR_CaptureVideo_RIFF_Write32(0); // initial frames
946                 // find an ideal divisor for the framerate
947                 for (x = 1;x < 1000;x++)
948                         if (cls.capturevideo.framerate * x == floor(cls.capturevideo.framerate * x))
949                                 break;
950                 SCR_CaptureVideo_RIFF_Write32(x); // samples/second divisor
951                 SCR_CaptureVideo_RIFF_Write32((int)(cls.capturevideo.framerate * x)); // samples/second multiplied by divisor
952                 SCR_CaptureVideo_RIFF_Write32(0); // start
953                 cls.capturevideo.videofile_totalframes_offset2 = SCR_CaptureVideo_RIFF_GetPosition();
954                 SCR_CaptureVideo_RIFF_Write32(0); // length
955                 SCR_CaptureVideo_RIFF_Write32(width*height+(width/2)*(height/2)*2); // suggested buffer size
956                 SCR_CaptureVideo_RIFF_Write32(0); // quality
957                 SCR_CaptureVideo_RIFF_Write32(0); // sample size
958                 SCR_CaptureVideo_RIFF_Write16(0); // frame left
959                 SCR_CaptureVideo_RIFF_Write16(0); // frame top
960                 SCR_CaptureVideo_RIFF_Write16(width); // frame right
961                 SCR_CaptureVideo_RIFF_Write16(height); // frame bottom
962                 SCR_CaptureVideo_RIFF_Pop();
963                 // video stream format
964                 SCR_CaptureVideo_RIFF_Push("strf", NULL);
965                 SCR_CaptureVideo_RIFF_Write32(40); // BITMAPINFO struct size
966                 SCR_CaptureVideo_RIFF_Write32(width); // width
967                 SCR_CaptureVideo_RIFF_Write32(height); // height
968                 SCR_CaptureVideo_RIFF_Write16(3); // planes
969                 SCR_CaptureVideo_RIFF_Write16(12); // bitcount
970                 SCR_CaptureVideo_RIFF_WriteFourCC("I420"); // compression
971                 SCR_CaptureVideo_RIFF_Write32(width*height+(width/2)*(height/2)*2); // size of image
972                 SCR_CaptureVideo_RIFF_Write32(0); // x pixels per meter
973                 SCR_CaptureVideo_RIFF_Write32(0); // y pixels per meter
974                 SCR_CaptureVideo_RIFF_Write32(0); // color used
975                 SCR_CaptureVideo_RIFF_Write32(0); // color important
976                 SCR_CaptureVideo_RIFF_Pop();
977                 SCR_CaptureVideo_RIFF_Pop();
978                 if (cls.capturevideo.soundrate)
979                 {
980                         // audio stream info
981                         SCR_CaptureVideo_RIFF_Push("LIST", "strl");
982                         SCR_CaptureVideo_RIFF_Push("strh", "auds");
983                         SCR_CaptureVideo_RIFF_Write32(1); // stream fourcc (PCM audio, uncompressed)
984                         SCR_CaptureVideo_RIFF_Write32(0); // flags
985                         SCR_CaptureVideo_RIFF_Write16(0); // priority
986                         SCR_CaptureVideo_RIFF_Write16(0); // language
987                         SCR_CaptureVideo_RIFF_Write32(0); // initial frames
988                         SCR_CaptureVideo_RIFF_Write32(1); // samples/second divisor
989                         SCR_CaptureVideo_RIFF_Write32((int)(cls.capturevideo.soundrate)); // samples/second multiplied by divisor
990                         SCR_CaptureVideo_RIFF_Write32(0); // start
991                         cls.capturevideo.videofile_totalsampleframes_offset = SCR_CaptureVideo_RIFF_GetPosition();
992                         SCR_CaptureVideo_RIFF_Write32(0); // length
993                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate * 2); // suggested buffer size (this is a half second)
994                         SCR_CaptureVideo_RIFF_Write32(0); // quality
995                         SCR_CaptureVideo_RIFF_Write32(4); // sample size
996                         SCR_CaptureVideo_RIFF_Write16(0); // frame left
997                         SCR_CaptureVideo_RIFF_Write16(0); // frame top
998                         SCR_CaptureVideo_RIFF_Write16(0); // frame right
999                         SCR_CaptureVideo_RIFF_Write16(0); // frame bottom
1000                         SCR_CaptureVideo_RIFF_Pop();
1001                         // audio stream format
1002                         SCR_CaptureVideo_RIFF_Push("strf", NULL);
1003                         SCR_CaptureVideo_RIFF_Write16(1); // format (uncompressed PCM?)
1004                         SCR_CaptureVideo_RIFF_Write16(2); // channels (stereo)
1005                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate); // sampleframes per second
1006                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundrate * 4); // average bytes per second
1007                         SCR_CaptureVideo_RIFF_Write16(4); // block align
1008                         SCR_CaptureVideo_RIFF_Write16(16); // bits per sample
1009                         SCR_CaptureVideo_RIFF_Write16(0); // size
1010                         SCR_CaptureVideo_RIFF_Pop();
1011                         SCR_CaptureVideo_RIFF_Pop();
1012                 }
1013                 // close the AVI header list
1014                 SCR_CaptureVideo_RIFF_Pop();
1015                 // software that produced this AVI video file
1016                 SCR_CaptureVideo_RIFF_Push("LIST", "INFO");
1017                 SCR_CaptureVideo_RIFF_Push("ISFT", NULL);
1018                 SCR_CaptureVideo_RIFF_WriteTerminatedString(engineversion);
1019                 SCR_CaptureVideo_RIFF_Pop();
1020                 // enable this junk filler if you like the LIST movi to always begin at 4KB in the file (why?)
1021 #if 0
1022                 SCR_CaptureVideo_RIFF_Push("JUNK", NULL);
1023                 x = 4096 - SCR_CaptureVideo_RIFF_GetPosition();
1024                 while (x > 0)
1025                 {
1026                         const char *junkfiller = "[ DarkPlaces junk data ]";
1027                         int i = min(x, (int)strlen(junkfiller));
1028                         SCR_CaptureVideo_RIFF_WriteBytes((const unsigned char *)junkfiller, i);
1029                         x -= i;
1030                 }
1031                 SCR_CaptureVideo_RIFF_Pop();
1032 #endif
1033                 SCR_CaptureVideo_RIFF_Pop();
1034                 // begin the actual video section now
1035                 SCR_CaptureVideo_RIFF_Push("LIST", "movi");
1036                 // we're done with the headers now...
1037                 SCR_CaptureVideo_RIFF_Flush();
1038                 if (cls.capturevideo.riffstacklevel != 2)
1039                         Sys_Error("SCR_CaptureVideo_BeginVideo: broken AVI writing code (stack level is %i (should be 2) at end of headers)\n", cls.capturevideo.riffstacklevel);
1040         }
1041
1042         switch(cls.capturevideo.format)
1043         {
1044         case CAPTUREVIDEOFORMAT_AVI_I420:
1045                 break;
1046         default:
1047                 break;
1048         }
1049 }
1050
1051 void SCR_CaptureVideo_EndVideo(void)
1052 {
1053         if (!cls.capturevideo.active)
1054                 return;
1055         cls.capturevideo.active = false;
1056         if (cls.capturevideo.videofile)
1057         {
1058                 switch(cls.capturevideo.format)
1059                 {
1060                 case CAPTUREVIDEOFORMAT_AVI_I420:
1061                         // close any open chunks
1062                         SCR_CaptureVideo_RIFF_Finish();
1063                         // go back and fix the video frames and audio samples fields
1064                         FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalframes_offset1, SEEK_SET);
1065                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.frame);
1066                         SCR_CaptureVideo_RIFF_Flush();
1067                         FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalframes_offset2, SEEK_SET);
1068                         SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.frame);
1069                         SCR_CaptureVideo_RIFF_Flush();
1070                         if (cls.capturevideo.soundrate)
1071                         {
1072                                 FS_Seek(cls.capturevideo.videofile, cls.capturevideo.videofile_totalsampleframes_offset, SEEK_SET);
1073                                 SCR_CaptureVideo_RIFF_Write32(cls.capturevideo.soundsampleframe);
1074                                 SCR_CaptureVideo_RIFF_Flush();
1075                         }
1076                         break;
1077                 default:
1078                         break;
1079                 }
1080                 FS_Close(cls.capturevideo.videofile);
1081                 cls.capturevideo.videofile = NULL;
1082         }
1083
1084         if (cls.capturevideo.buffer)
1085         {
1086                 Mem_Free (cls.capturevideo.buffer);
1087                 cls.capturevideo.buffer = NULL;
1088         }
1089
1090         if (cls.capturevideo.riffindexbuffer.data)
1091         {
1092                 Mem_Free(cls.capturevideo.riffindexbuffer.data);
1093                 cls.capturevideo.riffindexbuffer.data = NULL;
1094         }
1095
1096         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1097 }
1098
1099 // converts from RGB24 to I420 colorspace (identical to YV12 except chroma plane order is reversed), this colorspace is handled by the Intel(r) 4:2:0 codec on Windows
1100 void SCR_CaptureVideo_ConvertFrame_RGB_to_I420_flip(int width, int height, unsigned char *instart, unsigned char *outstart)
1101 {
1102         int x, y;
1103         int outoffset = (width/2)*(height/2);
1104         unsigned char *b, *out;
1105         // process one line at a time, and CbCr every other line at 2 pixel intervals
1106         for (y = 0;y < height;y++)
1107         {
1108                 // 1x1 Y
1109                 for (b = instart + (height-1-y)*width*3, out = outstart + y*width, x = 0;x < width;x++, b += 3, out++)
1110                         *out = cls.capturevideo.yuvnormalizetable[0][cls.capturevideo.rgbtoyuvscaletable[0][0][b[0]] + cls.capturevideo.rgbtoyuvscaletable[0][1][b[1]] + cls.capturevideo.rgbtoyuvscaletable[0][2][b[2]]];
1111                 if ((y & 1) == 0)
1112                 {
1113                         // 2x2 Cr and Cb planes
1114 #if 0
1115                         // low quality, no averaging
1116                         for (b = instart + (height-2-y)*width*3, out = outstart + width*height + (y/2)*(width/2), x = 0;x < width/2;x++, b += 6, out++)
1117                         {
1118                                 // Cr
1119                                 out[0        ] = cls.capturevideo.yuvnormalizetable[1][cls.capturevideo.rgbtoyuvscaletable[1][0][b[0]] + cls.capturevideo.rgbtoyuvscaletable[1][1][b[1]] + cls.capturevideo.rgbtoyuvscaletable[1][2][b[2]] + 128];
1120                                 // Cb
1121                                 out[outoffset] = cls.capturevideo.yuvnormalizetable[2][cls.capturevideo.rgbtoyuvscaletable[2][0][b[0]] + cls.capturevideo.rgbtoyuvscaletable[2][1][b[1]] + cls.capturevideo.rgbtoyuvscaletable[2][2][b[2]] + 128];
1122                         }
1123 #else
1124                         // high quality, averaging
1125                         int inpitch = width*3;
1126                         for (b = instart + (height-2-y)*width*3, out = outstart + width*height + (y/2)*(width/2), x = 0;x < width/2;x++, b += 6, out++)
1127                         {
1128                                 int blockr, blockg, blockb;
1129                                 blockr = (b[0] + b[3] + b[inpitch+0] + b[inpitch+3]) >> 2;
1130                                 blockg = (b[1] + b[4] + b[inpitch+1] + b[inpitch+4]) >> 2;
1131                                 blockb = (b[2] + b[5] + b[inpitch+2] + b[inpitch+5]) >> 2;
1132                                 // Cr
1133                                 out[0        ] = cls.capturevideo.yuvnormalizetable[1][cls.capturevideo.rgbtoyuvscaletable[1][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[1][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[1][2][blockb] + 128];
1134                                 // Cb
1135                                 out[outoffset] = cls.capturevideo.yuvnormalizetable[2][cls.capturevideo.rgbtoyuvscaletable[2][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[2][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[2][2][blockb] + 128];
1136                         }
1137 #endif
1138                 }
1139         }
1140 }
1141
1142 qboolean SCR_CaptureVideo_VideoFrame(int newframenum)
1143 {
1144         int x = 0, y = 0, width = vid.width, height = vid.height;
1145         unsigned char *in, *out;
1146         CHECKGLERROR
1147         //return SCR_ScreenShot(filename, cls.capturevideo.buffer, cls.capturevideo.buffer + vid.width * vid.height * 3, cls.capturevideo.buffer + vid.width * vid.height * 6, 0, 0, vid.width, vid.height, false, false, false, jpeg, true);
1148         // speed is critical here, so do saving as directly as possible
1149         switch (cls.capturevideo.format)
1150         {
1151         case CAPTUREVIDEOFORMAT_AVI_I420:
1152                 // if there's no videofile we have to just give up, and abort saving
1153                 if (!cls.capturevideo.videofile)
1154                         return false;
1155                 // FIXME: width/height must be multiple of 2, enforce this?
1156                 qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, cls.capturevideo.buffer);CHECKGLERROR
1157                 in = cls.capturevideo.buffer;
1158                 out = cls.capturevideo.buffer + width*height*3;
1159                 SCR_CaptureVideo_ConvertFrame_RGB_to_I420_flip(width, height, in, out);
1160                 x = width*height+(width/2)*(height/2)*2;
1161                 SCR_CaptureVideo_RIFF_OverflowCheck(8 + x);
1162                 for (;cls.capturevideo.frame < newframenum;cls.capturevideo.frame++)
1163                 {
1164                         SCR_CaptureVideo_RIFF_IndexEntry("00dc", x, 0x10); // AVIIF_KEYFRAME
1165                         SCR_CaptureVideo_RIFF_Push("00dc", NULL);
1166                         SCR_CaptureVideo_RIFF_WriteBytes(out, x);
1167                         SCR_CaptureVideo_RIFF_Pop();
1168                 }
1169                 return true;
1170         default:
1171                 return false;
1172         }
1173 }
1174
1175 void SCR_CaptureVideo_SoundFrame(unsigned char *bufstereo16le, size_t length, int rate)
1176 {
1177         int x;
1178         cls.capturevideo.soundrate = rate;
1179         cls.capturevideo.soundsampleframe += length;
1180         switch (cls.capturevideo.format)
1181         {
1182         case CAPTUREVIDEOFORMAT_AVI_I420:
1183                 x = length*4;
1184                 SCR_CaptureVideo_RIFF_OverflowCheck(8 + x);
1185                 SCR_CaptureVideo_RIFF_IndexEntry("01wb", x, 0x10); // AVIIF_KEYFRAME
1186                 SCR_CaptureVideo_RIFF_Push("01wb", NULL);
1187                 SCR_CaptureVideo_RIFF_WriteBytes(bufstereo16le, x);
1188                 SCR_CaptureVideo_RIFF_Pop();
1189                 break;
1190         default:
1191                 break;
1192         }
1193 }
1194
1195 void SCR_CaptureVideo(void)
1196 {
1197         int newframenum;
1198         if (cl_capturevideo.integer && r_render.integer)
1199         {
1200                 if (!cls.capturevideo.active)
1201                         SCR_CaptureVideo_BeginVideo();
1202                 if (cls.capturevideo.framerate != cl_capturevideo_fps.value)
1203                 {
1204                         Con_Printf("You can not change the video framerate while recording a video.\n");
1205                         Cvar_SetValueQuick(&cl_capturevideo_fps, cls.capturevideo.framerate);
1206                 }
1207                 // for AVI saving we have to make sure that sound is saved before video
1208                 if (cls.capturevideo.soundrate && !cls.capturevideo.soundsampleframe)
1209                         return;
1210                 if (cls.capturevideo.realtime)
1211                 {
1212                         // preserve sound sync by duplicating frames when running slow
1213                         newframenum = (int)((realtime - cls.capturevideo.starttime) * cls.capturevideo.framerate);
1214                 }
1215                 else
1216                         newframenum = cls.capturevideo.frame + 1;
1217                 // if falling behind more than one second, stop
1218                 if (newframenum - cls.capturevideo.frame > (int)ceil(cls.capturevideo.framerate))
1219                 {
1220                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1221                         Con_Printf("video saving failed on frame %i, your machine is too slow for this capture speed.\n", cls.capturevideo.frame);
1222                         SCR_CaptureVideo_EndVideo();
1223                         return;
1224                 }
1225                 // write frames
1226                 SCR_CaptureVideo_VideoFrame(newframenum);
1227                 if (cls.capturevideo.error)
1228                 {
1229                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1230                         Con_Printf("video saving failed on frame %i, out of disk space? stopping video capture.\n", cls.capturevideo.frame);
1231                         SCR_CaptureVideo_EndVideo();
1232                 }
1233         }
1234         else if (cls.capturevideo.active)
1235                 SCR_CaptureVideo_EndVideo();
1236 }
1237
1238 /*
1239 ===============
1240 R_Envmap_f
1241
1242 Grab six views for environment mapping tests
1243 ===============
1244 */
1245 struct envmapinfo_s
1246 {
1247         float angles[3];
1248         char *name;
1249         qboolean flipx, flipy, flipdiagonaly;
1250 }
1251 envmapinfo[12] =
1252 {
1253         {{  0,   0, 0}, "rt", false, false, false},
1254         {{  0, 270, 0}, "ft", false, false, false},
1255         {{  0, 180, 0}, "lf", false, false, false},
1256         {{  0,  90, 0}, "bk", false, false, false},
1257         {{-90, 180, 0}, "up",  true,  true, false},
1258         {{ 90, 180, 0}, "dn",  true,  true, false},
1259
1260         {{  0,   0, 0}, "px",  true,  true,  true},
1261         {{  0,  90, 0}, "py", false,  true, false},
1262         {{  0, 180, 0}, "nx", false, false,  true},
1263         {{  0, 270, 0}, "ny",  true, false, false},
1264         {{-90, 180, 0}, "pz", false, false,  true},
1265         {{ 90, 180, 0}, "nz", false, false,  true}
1266 };
1267
1268 static void R_Envmap_f (void)
1269 {
1270         int j, size;
1271         char filename[MAX_QPATH], basename[MAX_QPATH];
1272         unsigned char *buffer1;
1273         unsigned char *buffer2;
1274         unsigned char *buffer3;
1275
1276         if (Cmd_Argc() != 3)
1277         {
1278                 Con_Print("envmap <basename> <size>: save out 6 cubic environment map images, usable with loadsky, note that size must one of 128, 256, 512, or 1024 and can't be bigger than your current resolution\n");
1279                 return;
1280         }
1281
1282         strlcpy (basename, Cmd_Argv(1), sizeof (basename));
1283         size = atoi(Cmd_Argv(2));
1284         if (size != 128 && size != 256 && size != 512 && size != 1024)
1285         {
1286                 Con_Print("envmap: size must be one of 128, 256, 512, or 1024\n");
1287                 return;
1288         }
1289         if (size > vid.width || size > vid.height)
1290         {
1291                 Con_Print("envmap: your resolution is not big enough to render that size\n");
1292                 return;
1293         }
1294
1295         r_refdef.envmap = true;
1296
1297         R_UpdateVariables();
1298
1299         r_view.x = 0;
1300         r_view.y = 0;
1301         r_view.z = 0;
1302         r_view.width = size;
1303         r_view.height = size;
1304         r_view.depth = 1;
1305
1306         r_view.frustum_x = tan(90 * M_PI / 360.0);
1307         r_view.frustum_y = tan(90 * M_PI / 360.0);
1308
1309         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1310         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1311         buffer3 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3 + 18);
1312
1313         for (j = 0;j < 12;j++)
1314         {
1315                 sprintf(filename, "env/%s%s.tga", basename, envmapinfo[j].name);
1316                 Matrix4x4_CreateFromQuakeEntity(&r_view.matrix, r_view.origin[0], r_view.origin[1], r_view.origin[2], envmapinfo[j].angles[0], envmapinfo[j].angles[1], envmapinfo[j].angles[2], 1);
1317                 R_ClearScreen();
1318                 R_Mesh_Start();
1319                 R_RenderView();
1320                 R_Mesh_Finish();
1321                 SCR_ScreenShot(filename, buffer1, buffer2, buffer3, 0, vid.height - (r_view.y + r_view.height), size, size, envmapinfo[j].flipx, envmapinfo[j].flipy, envmapinfo[j].flipdiagonaly, false, false);
1322         }
1323
1324         Mem_Free (buffer1);
1325         Mem_Free (buffer2);
1326         Mem_Free (buffer3);
1327
1328         r_refdef.envmap = false;
1329 }
1330
1331 //=============================================================================
1332
1333 // LordHavoc: SHOWLMP stuff
1334 #define SHOWLMP_MAXLABELS 256
1335 typedef struct showlmp_s
1336 {
1337         qboolean        isactive;
1338         float           x;
1339         float           y;
1340         char            label[32];
1341         char            pic[128];
1342 }
1343 showlmp_t;
1344
1345 showlmp_t showlmp[SHOWLMP_MAXLABELS];
1346
1347 void SHOWLMP_decodehide(void)
1348 {
1349         int i;
1350         char *lmplabel;
1351         lmplabel = MSG_ReadString();
1352         for (i = 0;i < SHOWLMP_MAXLABELS;i++)
1353                 if (showlmp[i].isactive && strcmp(showlmp[i].label, lmplabel) == 0)
1354                 {
1355                         showlmp[i].isactive = false;
1356                         return;
1357                 }
1358 }
1359
1360 void SHOWLMP_decodeshow(void)
1361 {
1362         int i, k;
1363         char lmplabel[256], picname[256];
1364         float x, y;
1365         strlcpy (lmplabel,MSG_ReadString(), sizeof (lmplabel));
1366         strlcpy (picname, MSG_ReadString(), sizeof (picname));
1367         if (gamemode == GAME_NEHAHRA) // LordHavoc: nasty old legacy junk
1368         {
1369                 x = MSG_ReadByte();
1370                 y = MSG_ReadByte();
1371         }
1372         else
1373         {
1374                 x = MSG_ReadShort();
1375                 y = MSG_ReadShort();
1376         }
1377         k = -1;
1378         for (i = 0;i < SHOWLMP_MAXLABELS;i++)
1379                 if (showlmp[i].isactive)
1380                 {
1381                         if (strcmp(showlmp[i].label, lmplabel) == 0)
1382                         {
1383                                 k = i;
1384                                 break; // drop out to replace it
1385                         }
1386                 }
1387                 else if (k < 0) // find first empty one to replace
1388                         k = i;
1389         if (k < 0)
1390                 return; // none found to replace
1391         // change existing one
1392         showlmp[k].isactive = true;
1393         strlcpy (showlmp[k].label, lmplabel, sizeof (showlmp[k].label));
1394         strlcpy (showlmp[k].pic, picname, sizeof (showlmp[k].pic));
1395         showlmp[k].x = x;
1396         showlmp[k].y = y;
1397 }
1398
1399 void SHOWLMP_drawall(void)
1400 {
1401         int i;
1402         for (i = 0;i < SHOWLMP_MAXLABELS;i++)
1403                 if (showlmp[i].isactive)
1404                         DrawQ_Pic(showlmp[i].x, showlmp[i].y, Draw_CachePic(showlmp[i].pic, true), 0, 0, 1, 1, 1, 1, 0);
1405 }
1406
1407 void SHOWLMP_clear(void)
1408 {
1409         int i;
1410         for (i = 0;i < SHOWLMP_MAXLABELS;i++)
1411                 showlmp[i].isactive = false;
1412 }
1413
1414 /*
1415 ==============================================================================
1416
1417                                                 SCREEN SHOTS
1418
1419 ==============================================================================
1420 */
1421
1422 qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, unsigned char *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg, qboolean gammacorrect)
1423 {
1424         int     indices[3] = {0,1,2};
1425         qboolean ret;
1426
1427         if (!r_render.integer)
1428                 return false;
1429
1430         CHECKGLERROR
1431         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer1);CHECKGLERROR
1432
1433         if (scr_screenshot_gammaboost.value != 1 && gammacorrect)
1434         {
1435                 int i;
1436                 double igamma = 1.0 / scr_screenshot_gammaboost.value;
1437                 unsigned char ramp[256];
1438                 for (i = 0;i < 256;i++)
1439                         ramp[i] = (unsigned char) (pow(i * (1.0 / 255.0), igamma) * 255.0);
1440                 for (i = 0;i < width*height*3;i++)
1441                         buffer1[i] = ramp[buffer1[i]];
1442         }
1443
1444         Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 3, indices);
1445
1446         if (jpeg)
1447                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1448         else
1449                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer2, buffer3);
1450
1451         return ret;
1452 }
1453
1454 //=============================================================================
1455
1456 void R_ClearScreen(void)
1457 {
1458         // clear to black
1459         CHECKGLERROR
1460         if (r_refdef.fogenabled)
1461         {
1462                 qglClearColor(r_refdef.fogcolor[0],r_refdef.fogcolor[1],r_refdef.fogcolor[2],0);CHECKGLERROR
1463         }
1464         else
1465         {
1466                 qglClearColor(0,0,0,0);CHECKGLERROR
1467         }
1468         qglClearDepth(1);CHECKGLERROR
1469         if (gl_stencil)
1470         {
1471                 // LordHavoc: we use a stencil centered around 128 instead of 0,
1472                 // to avoid clamping interfering with strange shadow volume
1473                 // drawing orders
1474                 qglClearStencil(128);CHECKGLERROR
1475         }
1476         // clear the screen
1477         if (r_render.integer)
1478                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1479         // set dithering mode
1480         if (gl_dither.integer)
1481         {
1482                 qglEnable(GL_DITHER);CHECKGLERROR
1483         }
1484         else
1485         {
1486                 qglDisable(GL_DITHER);CHECKGLERROR
1487         }
1488 }
1489
1490 qboolean CL_VM_UpdateView (void);
1491 void SCR_DrawConsole (void);
1492 void R_Shadow_EditLights_DrawSelectedLightProperties(void);
1493
1494 int r_stereo_side;
1495
1496 void SCR_DrawScreen (void)
1497 {
1498         R_Mesh_Start();
1499
1500         if (r_timereport_active)
1501                 R_TimeReport("setup");
1502
1503         R_UpdateVariables();
1504
1505         if (cls.signon == SIGNONS)
1506         {
1507                 float size;
1508
1509                 size = scr_viewsize.value * (1.0 / 100.0);
1510                 size = min(size, 1);
1511
1512                 if (r_stereo_sidebyside.integer)
1513                 {
1514                         r_view.width = (int)(vid.width * size / 2.5);
1515                         r_view.height = (int)(vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100));
1516                         r_view.depth = 1;
1517                         r_view.x = (int)((vid.width - r_view.width * 2.5) * 0.5);
1518                         r_view.y = (int)((vid.height - r_view.height)/2);
1519                         r_view.z = 0;
1520                         if (r_stereo_side)
1521                                 r_view.x += (int)(r_view.width * 1.5);
1522                 }
1523                 else
1524                 {
1525                         r_view.width = (int)(vid.width * size);
1526                         r_view.height = (int)(vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1527                         r_view.depth = 1;
1528                         r_view.x = (int)((vid.width - r_view.width)/2);
1529                         r_view.y = (int)((vid.height - r_view.height)/2);
1530                         r_view.z = 0;
1531                 }
1532
1533                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1534                 // LordHavoc: this is designed to produce widescreen fov values
1535                 // when the screen is wider than 4/3 width/height aspect, to do
1536                 // this it simply assumes the requested fov is the vertical fov
1537                 // for a 4x3 display, if the ratio is not 4x3 this makes the fov
1538                 // higher/lower according to the ratio
1539                 r_view.frustum_y = tan(scr_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
1540                 r_view.frustum_x = r_view.frustum_y * (float)r_view.width / (float)r_view.height / vid_pixelheight.value;
1541
1542                 r_view.frustum_x *= r_refdef.frustumscale_x;
1543                 r_view.frustum_y *= r_refdef.frustumscale_y;
1544
1545                 if(!CL_VM_UpdateView())
1546                         R_RenderView();
1547
1548                 if (scr_zoomwindow.integer)
1549                 {
1550                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1551                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1552                         r_view.width = (int)(vid.width * sizex);
1553                         r_view.height = (int)(vid.height * sizey);
1554                         r_view.depth = 1;
1555                         r_view.x = (int)((vid.width - r_view.width)/2);
1556                         r_view.y = 0;
1557                         r_view.z = 0;
1558
1559                         r_view.frustum_y = tan(scr_zoomwindow_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
1560                         r_view.frustum_x = r_view.frustum_y * vid_pixelheight.value * (float)r_view.width / (float)r_view.height;
1561
1562                         r_view.frustum_x *= r_refdef.frustumscale_x;
1563                         r_view.frustum_y *= r_refdef.frustumscale_y;
1564
1565                         if(!CL_VM_UpdateView())
1566                                 R_RenderView();
1567                 }
1568         }
1569
1570         if (!r_stereo_sidebyside.integer)
1571         {
1572                 r_view.width = vid.width;
1573                 r_view.height = vid.height;
1574                 r_view.depth = 1;
1575                 r_view.x = 0;
1576                 r_view.y = 0;
1577                 r_view.z = 0;
1578         }
1579
1580         // draw 2D stuff
1581
1582         if (cls.signon == SIGNONS)
1583         {
1584                 SCR_DrawNet ();
1585                 SCR_DrawTurtle ();
1586                 SCR_DrawPause ();
1587                 if (!r_letterbox.value)
1588                         Sbar_Draw();
1589                 SHOWLMP_drawall();
1590                 SCR_CheckDrawCenterString();
1591         }
1592         MR_Draw();
1593         CL_DrawVideo();
1594         R_Shadow_EditLights_DrawSelectedLightProperties();
1595
1596         SCR_DrawConsole();
1597
1598         SCR_DrawBrand();
1599
1600         SCR_DrawDownload();
1601
1602         if (r_timereport_active)
1603                 R_TimeReport("2d");
1604
1605         if (cls.signon == SIGNONS)
1606                 R_TimeReport_Frame();
1607
1608         DrawQ_Finish();
1609
1610         R_DrawGamma();
1611
1612         R_Mesh_Finish();
1613
1614         if (r_timereport_active)
1615                 R_TimeReport("meshfinish");
1616 }
1617
1618 void SCR_UpdateLoadingScreen (qboolean clear)
1619 {
1620         float x, y;
1621         cachepic_t *pic;
1622         float vertex3f[12];
1623         float texcoord2f[8];
1624         // don't do anything if not initialized yet
1625         if (vid_hidden || !scr_refresh.integer)
1626                 return;
1627         CHECKGLERROR
1628         qglViewport(0, 0, vid.width, vid.height);CHECKGLERROR
1629         //qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
1630         //qglDepthMask(1);CHECKGLERROR
1631         qglColorMask(1,1,1,1);CHECKGLERROR
1632         qglClearColor(0,0,0,0);CHECKGLERROR
1633         // when starting up a new video mode, make sure the screen is cleared to black
1634         if (clear)
1635         {
1636                 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
1637         }
1638         //qglDisable(GL_CULL_FACE);CHECKGLERROR
1639         //R_ClearScreen();
1640         R_Textures_Frame();
1641         GL_SetupView_Mode_Ortho(0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100);
1642         R_Mesh_Start();
1643         R_Mesh_Matrix(&identitymatrix);
1644         // draw the loading plaque
1645         pic = Draw_CachePic("gfx/loading", true);
1646         x = (vid_conwidth.integer - pic->width)/2;
1647         y = (vid_conheight.integer - pic->height)/2;
1648         GL_Color(1,1,1,1);
1649         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1650         GL_DepthTest(false);
1651         R_Mesh_VertexPointer(vertex3f, 0, 0);
1652         R_Mesh_ColorPointer(NULL, 0, 0);
1653         R_Mesh_ResetTextureState();
1654         R_Mesh_TexBind(0, R_GetTexture(pic->tex));
1655         R_Mesh_TexCoordPointer(0, 2, texcoord2f, 0, 0);
1656         vertex3f[2] = vertex3f[5] = vertex3f[8] = vertex3f[11] = 0;
1657         vertex3f[0] = vertex3f[9] = x;
1658         vertex3f[1] = vertex3f[4] = y;
1659         vertex3f[3] = vertex3f[6] = x + pic->width;
1660         vertex3f[7] = vertex3f[10] = y + pic->height;
1661         texcoord2f[0] = 0;texcoord2f[1] = 0;
1662         texcoord2f[2] = 1;texcoord2f[3] = 0;
1663         texcoord2f[4] = 1;texcoord2f[5] = 1;
1664         texcoord2f[6] = 0;texcoord2f[7] = 1;
1665         if (vid.stereobuffer)
1666         {
1667                 qglDrawBuffer(GL_FRONT_LEFT);
1668                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
1669                 qglDrawBuffer(GL_FRONT_RIGHT);
1670                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
1671         }
1672         else
1673         {
1674                 qglDrawBuffer(GL_FRONT);
1675                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
1676         }
1677         R_Mesh_Finish();
1678         // refresh
1679         // not necessary when rendering to GL_FRONT buffers
1680         //VID_Finish(false);
1681         // however this IS necessary on Windows Vista
1682         qglFinish();
1683 }
1684
1685 void CL_UpdateScreen(void)
1686 {
1687         float conwidth, conheight;
1688
1689         if (vid_hidden || !scr_refresh.integer)
1690                 return;
1691
1692         if (!scr_initialized || !con_initialized)
1693                 return;                         // not initialized yet
1694
1695         conwidth = bound(320, vid_conwidth.value, 2048);
1696         conheight = bound(200, vid_conheight.value, 1536);
1697         if (vid_conwidth.value != conwidth)
1698                 Cvar_SetValue("vid_conwidth", conwidth);
1699         if (vid_conheight.value != conheight)
1700                 Cvar_SetValue("vid_conheight", conheight);
1701
1702         // bound viewsize
1703         if (scr_viewsize.value < 30)
1704                 Cvar_Set ("viewsize","30");
1705         if (scr_viewsize.value > 120)
1706                 Cvar_Set ("viewsize","120");
1707
1708         // bound field of view
1709         if (scr_fov.value < 1)
1710                 Cvar_Set ("fov","1");
1711         if (scr_fov.value > 170)
1712                 Cvar_Set ("fov","170");
1713
1714         // validate r_textureunits cvar
1715         if (r_textureunits.integer > gl_textureunits)
1716                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1717         if (r_textureunits.integer < 1)
1718                 Cvar_SetValueQuick(&r_textureunits, 1);
1719
1720         // validate gl_combine cvar
1721         if (gl_combine.integer && !gl_combine_extension)
1722                 Cvar_SetValueQuick(&gl_combine, 0);
1723
1724         // intermission is always full screen
1725         if (cl.intermission)
1726                 sb_lines = 0;
1727         else
1728         {
1729                 if (scr_viewsize.value >= 120)
1730                         sb_lines = 0;           // no status bar at all
1731                 else if (scr_viewsize.value >= 110)
1732                         sb_lines = 24;          // no inventory
1733                 else
1734                         sb_lines = 24+16+8;
1735         }
1736
1737         r_view.colormask[0] = 1;
1738         r_view.colormask[1] = 1;
1739         r_view.colormask[2] = 1;
1740
1741         if (r_timereport_active)
1742                 R_TimeReport("other");
1743
1744         SCR_SetUpToDrawConsole();
1745
1746         if (r_timereport_active)
1747                 R_TimeReport("start");
1748
1749         CHECKGLERROR
1750         qglViewport(0, 0, vid.width, vid.height);CHECKGLERROR
1751         qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
1752         qglDepthMask(1);CHECKGLERROR
1753         qglColorMask(1,1,1,1);CHECKGLERROR
1754         qglClearColor(0,0,0,0);CHECKGLERROR
1755         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
1756
1757         if(scr_stipple.integer)
1758         {
1759                 GLubyte stipple[128];
1760                 int i, s, width, parts;
1761                 static int frame = 0;
1762                 ++frame;
1763
1764                 s = scr_stipple.integer;
1765                 parts = (s & 007);
1766                 width = (s & 070) >> 3;
1767
1768                 qglEnable(GL_POLYGON_STIPPLE); // 0x0B42
1769                 for(i = 0; i < 128; ++i)
1770                 {
1771                         int line = i/4;
1772                         stipple[i] = (((line >> width) + frame) & ((1 << parts) - 1)) ? 0x00 : 0xFF;
1773                 }
1774                 qglPolygonStipple(stipple);
1775         }
1776         else
1777                 qglDisable(GL_POLYGON_STIPPLE);
1778
1779         if (r_timereport_active)
1780                 R_TimeReport("clear");
1781
1782         if (vid.stereobuffer || r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer || r_stereo_sidebyside.integer)
1783         {
1784                 matrix4x4_t originalmatrix = r_view.matrix;
1785                 matrix4x4_t offsetmatrix;
1786                 Matrix4x4_CreateTranslate(&offsetmatrix, 0, r_stereo_separation.value * -0.5f, 0);
1787                 Matrix4x4_Concat(&r_view.matrix, &originalmatrix, &offsetmatrix);
1788
1789                 if (r_stereo_sidebyside.integer)
1790                         r_stereo_side = 0;
1791
1792                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1793                 {
1794                         r_view.colormask[0] = 1;
1795                         r_view.colormask[1] = 0;
1796                         r_view.colormask[2] = 0;
1797                 }
1798
1799                 if (vid.stereobuffer)
1800                         qglDrawBuffer(GL_BACK_RIGHT);
1801
1802                 SCR_DrawScreen();
1803
1804                 Matrix4x4_CreateTranslate(&offsetmatrix, 0, r_stereo_separation.value * 0.5f, 0);
1805                 Matrix4x4_Concat(&r_view.matrix, &originalmatrix, &offsetmatrix);
1806
1807                 if (r_stereo_sidebyside.integer)
1808                         r_stereo_side = 1;
1809
1810                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1811                 {
1812                         r_view.colormask[0] = 0;
1813                         r_view.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
1814                         r_view.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
1815                 }
1816
1817                 if (vid.stereobuffer)
1818                         qglDrawBuffer(GL_BACK_LEFT);
1819
1820                 SCR_DrawScreen();
1821
1822                 r_view.matrix = originalmatrix;
1823         }
1824         else
1825         {
1826                 qglDrawBuffer(GL_BACK);
1827                 SCR_DrawScreen();
1828         }
1829
1830         SCR_CaptureVideo();
1831
1832         VID_Finish(true);
1833         if (r_timereport_active)
1834                 R_TimeReport("finish");
1835 }
1836
1837 void CL_Screen_NewMap(void)
1838 {
1839         SHOWLMP_clear();
1840 }