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