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