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