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