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