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