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