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