]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - cl_screen.c
Merge PR 'Use the text from modinfo.txt as the mod menu entry'
[xonotic/darkplaces.git] / cl_screen.c
1
2 #include "quakedef.h"
3 #include "cl_video.h"
4 #include "image.h"
5 #include "jpeg.h"
6 #include "image_png.h"
7 #include "cl_collision.h"
8 #include "libcurl.h"
9 #include "csprogs.h"
10 #include "r_stats.h"
11 #ifdef CONFIG_VIDEO_CAPTURE
12 #include "cap_avi.h"
13 #include "cap_ogg.h"
14 #endif
15
16 // we have to include snd_main.h here only to get access to snd_renderbuffer->format.speed when writing the AVI headers
17 #include "snd_main.h"
18
19 cvar_t scr_viewsize = {CF_CLIENT | CF_ARCHIVE, "viewsize","100", "how large the view should be, 110 disables inventory bar, 120 disables status bar"};
20 cvar_t scr_fov = {CF_CLIENT | CF_ARCHIVE, "fov","90", "field of vision, 1-170 degrees, default 90, some players use 110-130"};
21 cvar_t scr_conalpha = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha", "1", "opacity of console background gfx/conback"};
22 cvar_t scr_conalphafactor = {CF_CLIENT | CF_ARCHIVE, "scr_conalphafactor", "1", "opacity of console background gfx/conback relative to scr_conalpha; when 0, gfx/conback is not drawn"};
23 cvar_t scr_conalpha2factor = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha2factor", "0", "opacity of console background gfx/conback2 relative to scr_conalpha; when 0, gfx/conback2 is not drawn"};
24 cvar_t scr_conalpha3factor = {CF_CLIENT | CF_ARCHIVE, "scr_conalpha3factor", "0", "opacity of console background gfx/conback3 relative to scr_conalpha; when 0, gfx/conback3 is not drawn"};
25 cvar_t scr_conbrightness = {CF_CLIENT | CF_ARCHIVE, "scr_conbrightness", "1", "brightness of console background (0 = black, 1 = image)"};
26 cvar_t scr_conforcewhiledisconnected = {CF_CLIENT, "scr_conforcewhiledisconnected", "1", "1 forces fullscreen console while disconnected, 2 also forces it when the listen server has started but the client is still loading"};
27 cvar_t scr_conheight = {CF_CLIENT | CF_ARCHIVE, "scr_conheight", "0.5", "fraction of screen height occupied by console (reduced as necessary for visibility of loading progress and infobar)"};
28 cvar_t scr_conscroll_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll_x", "0", "scroll speed of gfx/conback in x direction"};
29 cvar_t scr_conscroll_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll_y", "0", "scroll speed of gfx/conback in y direction"};
30 cvar_t scr_conscroll2_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll2_x", "0", "scroll speed of gfx/conback2 in x direction"};
31 cvar_t scr_conscroll2_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll2_y", "0", "scroll speed of gfx/conback2 in y direction"};
32 cvar_t scr_conscroll3_x = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll3_x", "0", "scroll speed of gfx/conback3 in x direction"};
33 cvar_t scr_conscroll3_y = {CF_CLIENT | CF_ARCHIVE, "scr_conscroll3_y", "0", "scroll speed of gfx/conback3 in y direction"};
34 #ifdef CONFIG_MENU
35 cvar_t scr_menuforcewhiledisconnected = {CF_CLIENT, "scr_menuforcewhiledisconnected", "0", "forces menu while disconnected"};
36 #endif
37 cvar_t scr_centertime = {CF_CLIENT, "scr_centertime","2", "how long centerprint messages show"};
38 cvar_t scr_showram = {CF_CLIENT | CF_ARCHIVE, "showram","1", "show ram icon if low on surface cache memory (not used)"};
39 cvar_t scr_showturtle = {CF_CLIENT | CF_ARCHIVE, "showturtle","0", "show turtle icon when framerate is too low"};
40 cvar_t scr_showpause = {CF_CLIENT | CF_ARCHIVE, "showpause","1", "show pause icon when game is paused"};
41 cvar_t scr_showbrand = {CF_CLIENT, "showbrand","0", "shows gfx/brand.tga in a corner of the screen (different values select different positions, including centered)"};
42 cvar_t scr_printspeed = {CF_CLIENT, "scr_printspeed","0", "speed of intermission printing (episode end texts), a value of 0 disables the slow printing"};
43 cvar_t scr_loadingscreen_background = {CF_CLIENT, "scr_loadingscreen_background","0", "show the last visible background during loading screen (costs one screenful of video memory)"};
44 cvar_t scr_loadingscreen_scale = {CF_CLIENT, "scr_loadingscreen_scale","1", "scale factor of the background"};
45 cvar_t scr_loadingscreen_scale_base = {CF_CLIENT, "scr_loadingscreen_scale_base","0", "0 = console pixels, 1 = video pixels"};
46 cvar_t scr_loadingscreen_scale_limit = {CF_CLIENT, "scr_loadingscreen_scale_limit","0", "0 = no limit, 1 = until first edge hits screen edge, 2 = until last edge hits screen edge, 3 = until width hits screen width, 4 = until height hits screen height"};
47 cvar_t scr_loadingscreen_picture = {CF_CLIENT, "scr_loadingscreen_picture", "gfx/loading", "picture shown during loading"};
48 cvar_t scr_loadingscreen_count = {CF_CLIENT, "scr_loadingscreen_count","1", "number of loading screen files to use randomly (named loading.tga, loading2.tga, loading3.tga, ...)"};
49 cvar_t scr_loadingscreen_firstforstartup = {CF_CLIENT, "scr_loadingscreen_firstforstartup","0", "remove loading.tga from random scr_loadingscreen_count selection and only display it on client startup, 0 = normal, 1 = firstforstartup"};
50 cvar_t scr_loadingscreen_barcolor = {CF_CLIENT, "scr_loadingscreen_barcolor", "0 0 1", "rgb color of loadingscreen progress bar"};
51 cvar_t scr_loadingscreen_barheight = {CF_CLIENT, "scr_loadingscreen_barheight", "8", "the height of the loadingscreen progress bar"};
52 cvar_t scr_loadingscreen_maxfps = {CF_CLIENT, "scr_loadingscreen_maxfps", "20", "maximum FPS for loading screen so it will not update very often (this reduces loading time with lots of models)"};
53 cvar_t scr_infobar_height = {CF_CLIENT, "scr_infobar_height", "8", "the height of the infobar items"};
54 cvar_t vid_conwidthauto = {CF_CLIENT | CF_ARCHIVE, "vid_conwidthauto", "1", "automatically update vid_conwidth to match aspect ratio"};
55 cvar_t vid_conwidth = {CF_CLIENT | CF_ARCHIVE, "vid_conwidth", "640", "virtual width of 2D graphics system (note: changes may be overwritten, see vid_conwidthauto)"};
56 cvar_t vid_conheight = {CF_CLIENT | CF_ARCHIVE, "vid_conheight", "480", "virtual height of 2D graphics system"};
57 cvar_t vid_pixelheight = {CF_CLIENT | CF_ARCHIVE, "vid_pixelheight", "1", "adjusts vertical field of vision to account for non-square pixels (1280x1024 on a CRT monitor for example)"};
58 cvar_t scr_screenshot_jpeg = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_jpeg","1", "save jpeg instead of targa"};
59 cvar_t scr_screenshot_jpeg_quality = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_jpeg_quality","0.9", "image quality of saved jpeg"};
60 cvar_t scr_screenshot_png = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_png","0", "save png instead of targa"};
61 cvar_t scr_screenshot_gammaboost = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_gammaboost","1", "gamma correction on saved screenshots and videos, 1.0 saves unmodified images"};
62 cvar_t scr_screenshot_alpha = {CF_CLIENT, "scr_screenshot_alpha","0", "try to write an alpha channel to screenshots (debugging feature)"};
63 cvar_t scr_screenshot_timestamp = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_timestamp", "1", "use a timestamp based number of the type YYYYMMDDHHMMSSsss instead of sequential numbering"};
64 // scr_screenshot_name is defined in fs.c
65 #ifdef CONFIG_VIDEO_CAPTURE
66 cvar_t cl_capturevideo = {CF_CLIENT, "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)"};
67 cvar_t cl_capturevideo_demo_stop = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_demo_stop", "1", "automatically stops video recording when demo ends"};
68 cvar_t cl_capturevideo_printfps = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_printfps", "1", "prints the frames per second captured in capturevideo (is only written to the log file, not to the console, as that would be visible on the video)"};
69 cvar_t cl_capturevideo_width = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_width", "0", "scales all frames to this resolution before saving the video"};
70 cvar_t cl_capturevideo_height = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_height", "0", "scales all frames to this resolution before saving the video"};
71 cvar_t cl_capturevideo_realtime = {CF_CLIENT, "cl_capturevideo_realtime", "0", "causes video saving to operate in realtime (mostly useful while playing, not while capturing demos), this can produce a much lower quality video due to poor sound/video sync and will abort saving if your machine stalls for over a minute"};
72 cvar_t cl_capturevideo_fps = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_fps", "30", "how many frames per second to save (29.97 for NTSC, 30 for typical PC video, 15 can be useful)"};
73 cvar_t cl_capturevideo_nameformat = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_nameformat", "dpvideo", "prefix for saved videos (the date is encoded using strftime escapes)"};
74 cvar_t cl_capturevideo_number = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_number", "1", "number to append to video filename, incremented each time a capture begins"};
75 cvar_t cl_capturevideo_ogg = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_ogg", "1", "save captured video data as Ogg/Vorbis/Theora streams"};
76 cvar_t cl_capturevideo_framestep = {CF_CLIENT | CF_ARCHIVE, "cl_capturevideo_framestep", "1", "when set to n >= 1, render n frames to capture one (useful for motion blur like effects)"};
77 #endif
78 cvar_t r_letterbox = {CF_CLIENT, "r_letterbox", "0", "reduces vertical height of view to simulate a letterboxed movie effect (can be used by mods for cutscenes)"};
79 cvar_t r_stereo_separation = {CF_CLIENT, "r_stereo_separation", "4", "separation distance of eyes in the world (negative values are only useful for cross-eyed viewing)"};
80 cvar_t r_stereo_sidebyside = {CF_CLIENT, "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)"};
81 cvar_t r_stereo_horizontal = {CF_CLIENT, "r_stereo_horizontal", "0", "aspect skewed side by side view for special decoder/display hardware"};
82 cvar_t r_stereo_vertical = {CF_CLIENT, "r_stereo_vertical", "0", "aspect skewed top and bottom view for special decoder/display hardware"};
83 cvar_t r_stereo_redblue = {CF_CLIENT, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
84 cvar_t r_stereo_redcyan = {CF_CLIENT, "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"};
85 cvar_t r_stereo_redgreen = {CF_CLIENT, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
86 cvar_t r_stereo_angle = {CF_CLIENT, "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)"};
87 cvar_t scr_stipple = {CF_CLIENT, "scr_stipple", "0", "interlacing-like stippling of the display"};
88 cvar_t scr_refresh = {CF_CLIENT, "scr_refresh", "1", "allows you to completely shut off rendering for benchmarking purposes"};
89 cvar_t scr_screenshot_name_in_mapdir = {CF_CLIENT | CF_ARCHIVE, "scr_screenshot_name_in_mapdir", "0", "if set to 1, screenshots are placed in a subdirectory named like the map they are from"};
90 cvar_t net_graph = {CF_CLIENT | CF_ARCHIVE, "net_graph", "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)"};
91 cvar_t cl_demo_mousegrab = {CF_CLIENT, "cl_demo_mousegrab", "0", "Allows reading the mouse input while playing demos. Useful for camera mods developed in csqc. (0: never, 1: always)"};
92 cvar_t timedemo_screenshotframelist = {CF_CLIENT, "timedemo_screenshotframelist", "", "when performing a timedemo, take screenshots of each frame in this space-separated list - example: 1 201 401"};
93 cvar_t vid_touchscreen_outlinealpha = {CF_CLIENT, "vid_touchscreen_outlinealpha", "0", "opacity of touchscreen area outlines"};
94 cvar_t vid_touchscreen_overlayalpha = {CF_CLIENT, "vid_touchscreen_overlayalpha", "0.25", "opacity of touchscreen area icons"};
95
96 extern cvar_t sbar_info_pos;
97 extern cvar_t r_fog_clear;
98
99 int jpeg_supported = false;
100
101 qbool   scr_initialized;                // ready to draw
102
103 qbool scr_loading = false;  // we are in a loading screen
104
105 unsigned int        scr_con_current;
106 static unsigned int scr_con_margin_bottom;
107
108 extern int      con_vislines;
109
110 extern int cl_punchangle_applied;
111
112 static void SCR_ScreenShot_f(cmd_state_t *cmd);
113 static void R_Envmap_f(cmd_state_t *cmd);
114
115 // backend
116 void R_ClearScreen(qbool fogcolor);
117
118 /*
119 ===============================================================================
120
121 CENTER PRINTING
122
123 ===============================================================================
124 */
125
126 char            scr_centerstring[MAX_INPUTLINE];
127 float           scr_centertime_start;   // for slow victory printing
128 float           scr_centertime_off;
129 int                     scr_center_lines;
130 int                     scr_erase_lines;
131 int                     scr_erase_center;
132 char        scr_infobarstring[MAX_INPUTLINE];
133 float       scr_infobartime_off;
134
135 /*
136 ==============
137 SCR_CenterPrint
138
139 Called for important messages that should stay in the center of the screen
140 for a few moments
141 ==============
142 */
143 void SCR_CenterPrint(const char *str)
144 {
145         dp_strlcpy (scr_centerstring, str, sizeof (scr_centerstring));
146         scr_centertime_off = scr_centertime.value;
147         scr_centertime_start = cl.time;
148
149 // count the number of lines for centering
150         scr_center_lines = 1;
151         while (*str)
152         {
153                 if (*str == '\n')
154                         scr_center_lines++;
155                 str++;
156         }
157 }
158
159 /*
160 ============
161 SCR_Centerprint_f
162
163 Print something to the center of the screen using SCR_Centerprint
164 ============
165 */
166 static void SCR_Centerprint_f (cmd_state_t *cmd)
167 {
168         char msg[MAX_INPUTLINE];
169         unsigned int i, c, p;
170         c = Cmd_Argc(cmd);
171         if(c >= 2)
172         {
173                 dp_strlcpy(msg, Cmd_Argv(cmd,1), sizeof(msg));
174                 for(i = 2; i < c; ++i)
175                 {
176                         dp_strlcat(msg, " ", sizeof(msg));
177                         dp_strlcat(msg, Cmd_Argv(cmd, i), sizeof(msg));
178                 }
179                 c = (unsigned int)strlen(msg);
180                 for(p = 0, i = 0; i < c; ++i)
181                 {
182                         if(msg[i] == '\\')
183                         {
184                                 if(msg[i+1] == 'n')
185                                         msg[p++] = '\n';
186                                 else if(msg[i+1] == '\\')
187                                         msg[p++] = '\\';
188                                 else {
189                                         msg[p++] = '\\';
190                                         msg[p++] = msg[i+1];
191                                 }
192                                 ++i;
193                         } else {
194                                 msg[p++] = msg[i];
195                         }
196                 }
197                 msg[p] = '\0';
198                 SCR_CenterPrint(msg);
199         }
200 }
201
202 static void SCR_DrawCenterString (void)
203 {
204         char    *start;
205         int             x, y;
206         int             remaining;
207         int             color;
208
209         if(cl.intermission == 2) // in finale,
210                 if(sb_showscores) // make TAB hide the finale message (sb_showscores overrides finale in sbar.c)
211                         return;
212
213         if(scr_centertime.value <= 0 && !cl.intermission)
214                 return;
215
216 // the finale prints the characters one at a time, except if printspeed is an absurdly high value
217         if (cl.intermission && scr_printspeed.value > 0 && scr_printspeed.value < 1000000)
218                 remaining = (int)(scr_printspeed.value * (cl.time - scr_centertime_start));
219         else
220                 remaining = 9999;
221
222         scr_erase_center = 0;
223         start = scr_centerstring;
224
225         if (remaining < 1)
226                 return;
227
228         if (scr_center_lines <= 4)
229                 y = (int)(vid_conheight.integer*0.35);
230         else
231                 y = 48;
232
233         color = -1;
234         do
235         {
236                 // scan the number of characters on the line, not counting color codes
237                 char *newline = strchr(start, '\n');
238                 int l = newline ? (newline - start) : (int)strlen(start);
239                 float width = DrawQ_TextWidth(start, l, 8, 8, false, FONT_CENTERPRINT);
240
241                 x = (int) (vid_conwidth.integer - width)/2;
242                 if (l > 0)
243                 {
244                         if (remaining < l)
245                                 l = remaining;
246                         DrawQ_String(x, y, start, l, 8, 8, 1, 1, 1, 1, 0, &color, false, FONT_CENTERPRINT);
247                         remaining -= l;
248                         if (remaining <= 0)
249                                 return;
250                 }
251                 y += 8;
252
253                 if (!newline)
254                         break;
255                 start = newline + 1; // skip the \n
256         } while (1);
257 }
258
259 static void SCR_CheckDrawCenterString (void)
260 {
261         if (scr_center_lines > scr_erase_lines)
262                 scr_erase_lines = scr_center_lines;
263
264         if (cl.time > cl.oldtime)
265                 scr_centertime_off -= cl.time - cl.oldtime;
266
267         // don't draw if this is a normal stats-screen intermission,
268         // only if it is not an intermission, or a finale intermission
269         if (cl.intermission == 1)
270                 return;
271         if (scr_centertime_off <= 0 && !cl.intermission)
272                 return;
273         if (key_dest != key_game)
274                 return;
275
276         SCR_DrawCenterString ();
277 }
278
279 static void SCR_DrawNetGraph_DrawGraph (int graphx, int graphy, int graphwidth, int graphheight, float graphscale, int graphlimit, const char *label, float textsize, int packetcounter, netgraphitem_t *netgraph)
280 {
281         netgraphitem_t *graph;
282         int j, x, y;
283         int totalbytes = 0;
284         char bytesstring[128];
285         float g[NETGRAPH_PACKETS][7];
286         float *a;
287         float *b;
288         DrawQ_Fill(graphx, graphy, graphwidth, graphheight + textsize * 2, 0, 0, 0, 0.5, 0);
289         // draw the bar graph itself
290         memset(g, 0, sizeof(g));
291         for (j = 0;j < NETGRAPH_PACKETS;j++)
292         {
293                 graph = netgraph + j;
294                 g[j][0] = 1.0f - 0.25f * (host.realtime - graph->time);
295                 g[j][1] = 1.0f;
296                 g[j][2] = 1.0f;
297                 g[j][3] = 1.0f;
298                 g[j][4] = 1.0f;
299                 g[j][5] = 1.0f;
300                 g[j][6] = 1.0f;
301                 if (graph->unreliablebytes == NETGRAPH_LOSTPACKET)
302                         g[j][1] = 0.00f;
303                 else if (graph->unreliablebytes == NETGRAPH_CHOKEDPACKET)
304                         g[j][2] = 0.90f;
305                 else
306                 {
307                         if(netgraph[j].time >= netgraph[(j+NETGRAPH_PACKETS-1)%NETGRAPH_PACKETS].time)
308                                 if(graph->unreliablebytes + graph->reliablebytes + graph->ackbytes >= graphlimit * (netgraph[j].time - netgraph[(j+NETGRAPH_PACKETS-1)%NETGRAPH_PACKETS].time))
309                                         g[j][2] = 0.98f;
310                         g[j][3] = 1.0f    - graph->unreliablebytes * graphscale;
311                         g[j][4] = g[j][3] - graph->reliablebytes   * graphscale;
312                         g[j][5] = g[j][4] - graph->ackbytes        * graphscale;
313                         // count bytes in the last second
314                         if (host.realtime - graph->time < 1.0f)
315                                 totalbytes += graph->unreliablebytes + graph->reliablebytes + graph->ackbytes;
316                 }
317                 if(graph->cleartime >= 0)
318                         g[j][6] = 0.5f + 0.5f * (2.0 / M_PI) * atan((M_PI / 2.0) * (graph->cleartime - graph->time));
319                 g[j][1] = bound(0.0f, g[j][1], 1.0f);
320                 g[j][2] = bound(0.0f, g[j][2], 1.0f);
321                 g[j][3] = bound(0.0f, g[j][3], 1.0f);
322                 g[j][4] = bound(0.0f, g[j][4], 1.0f);
323                 g[j][5] = bound(0.0f, g[j][5], 1.0f);
324                 g[j][6] = bound(0.0f, g[j][6], 1.0f);
325         }
326         // render the lines for the graph
327         for (j = 0;j < NETGRAPH_PACKETS;j++)
328         {
329                 a = g[j];
330                 b = g[(j+1)%NETGRAPH_PACKETS];
331                 if (a[0] < 0.0f || b[0] > 1.0f || b[0] < a[0])
332                         continue;
333                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[2], graphx + graphwidth * b[0], graphy + graphheight * b[2], 1.0f, 1.0f, 1.0f, 1.0f, 0);
334                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[1], graphx + graphwidth * b[0], graphy + graphheight * b[1], 1.0f, 0.0f, 0.0f, 1.0f, 0);
335                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[5], graphx + graphwidth * b[0], graphy + graphheight * b[5], 0.0f, 1.0f, 0.0f, 1.0f, 0);
336                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[4], graphx + graphwidth * b[0], graphy + graphheight * b[4], 1.0f, 1.0f, 1.0f, 1.0f, 0);
337                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[3], graphx + graphwidth * b[0], graphy + graphheight * b[3], 1.0f, 0.5f, 0.0f, 1.0f, 0);
338                 DrawQ_Line(1, graphx + graphwidth * a[0], graphy + graphheight * a[6], graphx + graphwidth * b[0], graphy + graphheight * b[6], 0.0f, 0.0f, 1.0f, 1.0f, 0);
339         }
340         x = graphx;
341         y = graphy + graphheight;
342         dpsnprintf(bytesstring, sizeof(bytesstring), "%i", totalbytes);
343         DrawQ_String(x, y, label      , 0, textsize, textsize, 1.0f, 1.0f, 1.0f, 1.0f, 0, NULL, false, FONT_DEFAULT);y += textsize;
344         DrawQ_String(x, y, bytesstring, 0, textsize, textsize, 1.0f, 1.0f, 1.0f, 1.0f, 0, NULL, false, FONT_DEFAULT);y += textsize;
345 }
346
347 /*
348 ==============
349 SCR_DrawNetGraph
350 ==============
351 */
352 static void SCR_DrawNetGraph (void)
353 {
354         int i, separator1, separator2, graphwidth, graphheight, netgraph_x, netgraph_y, textsize, index, netgraphsperrow, graphlimit;
355         float graphscale;
356         netconn_t *c;
357         char vabuf[1024];
358
359         if (cls.state != ca_connected)
360                 return;
361         if (!cls.netcon)
362                 return;
363         if (!net_graph.integer)
364                 return;
365
366         separator1 = 2;
367         separator2 = 4;
368         textsize = 8;
369         graphwidth = 120;
370         graphheight = 70;
371         graphscale = 1.0f / 1500.0f;
372         graphlimit = cl_rate.integer;
373
374         netgraphsperrow = (vid_conwidth.integer + separator2) / (graphwidth * 2 + separator1 + separator2);
375         netgraphsperrow = max(netgraphsperrow, 1);
376
377         index = 0;
378         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (graphwidth * 2 + separator1 + separator2);
379         netgraph_y = (vid_conheight.integer - 48 - sbar_info_pos.integer + separator2) - (1 + (index / netgraphsperrow)) * (graphheight + textsize + separator2);
380         c = cls.netcon;
381         SCR_DrawNetGraph_DrawGraph(netgraph_x                          , netgraph_y, graphwidth, graphheight, graphscale, graphlimit, "incoming", textsize, c->incoming_packetcounter, c->incoming_netgraph);
382         SCR_DrawNetGraph_DrawGraph(netgraph_x + graphwidth + separator1, netgraph_y, graphwidth, graphheight, graphscale, graphlimit, "outgoing", textsize, c->outgoing_packetcounter, c->outgoing_netgraph);
383         index++;
384
385         if (sv.active && net_graph.integer >= 2)
386         {
387                 for (i = 0;i < svs.maxclients;i++)
388                 {
389                         c = svs.clients[i].netconnection;
390                         if (!c)
391                                 continue;
392                         netgraph_x = (vid_conwidth.integer + separator2) - (1 + (index % netgraphsperrow)) * (graphwidth * 2 + separator1 + separator2);
393                         netgraph_y = (vid_conheight.integer - 48 + separator2) - (1 + (index / netgraphsperrow)) * (graphheight + textsize + separator2);
394                         SCR_DrawNetGraph_DrawGraph(netgraph_x                          , netgraph_y, graphwidth, graphheight, graphscale, graphlimit, va(vabuf, sizeof(vabuf), "%s", svs.clients[i].name), textsize, c->outgoing_packetcounter, c->outgoing_netgraph);
395                         SCR_DrawNetGraph_DrawGraph(netgraph_x + graphwidth + separator1, netgraph_y, graphwidth, graphheight, graphscale, graphlimit, ""                           , textsize, c->incoming_packetcounter, c->incoming_netgraph);
396                         index++;
397                 }
398         }
399 }
400
401 /*
402 ==============
403 SCR_DrawTurtle
404 ==============
405 */
406 static void SCR_DrawTurtle (void)
407 {
408         static int      count;
409
410         if (cls.state != ca_connected)
411                 return;
412
413         if (!scr_showturtle.integer)
414                 return;
415
416         if (cl.realframetime < 0.1)
417         {
418                 count = 0;
419                 return;
420         }
421
422         count++;
423         if (count < 3)
424                 return;
425
426         DrawQ_Pic (0, 0, Draw_CachePic ("gfx/turtle"), 0, 0, 1, 1, 1, 1, 0);
427 }
428
429 /*
430 ==============
431 SCR_DrawNet
432 ==============
433 */
434 static void SCR_DrawNet (void)
435 {
436         if (cls.state != ca_connected)
437                 return;
438         if (host.realtime - cl.last_received_message < 0.3)
439                 return;
440         if (cls.demoplayback)
441                 return;
442
443         DrawQ_Pic (64, 0, Draw_CachePic ("gfx/net"), 0, 0, 1, 1, 1, 1, 0);
444 }
445
446 /*
447 ==============
448 DrawPause
449 ==============
450 */
451 static void SCR_DrawPause (void)
452 {
453         cachepic_t      *pic;
454
455         if (cls.state != ca_connected)
456                 return;
457
458         if (!scr_showpause.integer)             // turn off for screenshots
459                 return;
460
461         if (!cl.paused)
462                 return;
463
464         pic = Draw_CachePic ("gfx/pause");
465         DrawQ_Pic ((vid_conwidth.integer - Draw_GetPicWidth(pic))/2, (vid_conheight.integer - Draw_GetPicHeight(pic))/2, pic, 0, 0, 1, 1, 1, 1, 0);
466 }
467
468 /*
469 ==============
470 SCR_DrawBrand
471 ==============
472 */
473 static void SCR_DrawBrand (void)
474 {
475         cachepic_t      *pic;
476         float           x, y;
477
478         if (!scr_showbrand.value)
479                 return;
480
481         pic = Draw_CachePic ("gfx/brand");
482
483         switch ((int)scr_showbrand.value)
484         {
485         case 1: // bottom left
486                 x = 0;
487                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
488                 break;
489         case 2: // bottom centre
490                 x = (vid_conwidth.integer - Draw_GetPicWidth(pic)) / 2;
491                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
492                 break;
493         case 3: // bottom right
494                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
495                 y = vid_conheight.integer - Draw_GetPicHeight(pic);
496                 break;
497         case 4: // centre right
498                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
499                 y = (vid_conheight.integer - Draw_GetPicHeight(pic)) / 2;
500                 break;
501         case 5: // top right
502                 x = vid_conwidth.integer - Draw_GetPicWidth(pic);
503                 y = 0;
504                 break;
505         case 6: // top centre
506                 x = (vid_conwidth.integer - Draw_GetPicWidth(pic)) / 2;
507                 y = 0;
508                 break;
509         case 7: // top left
510                 x = 0;
511                 y = 0;
512                 break;
513         case 8: // centre left
514                 x = 0;
515                 y = (vid_conheight.integer - Draw_GetPicHeight(pic)) / 2;
516                 break;
517         default:
518                 return;
519         }
520
521         DrawQ_Pic (x, y, pic, 0, 0, 1, 1, 1, 1, 0);
522 }
523
524 /*
525 ==============
526 SCR_DrawQWDownload
527 ==============
528 */
529 static int SCR_DrawQWDownload(int offset)
530 {
531         // sync with SCR_InfobarHeight
532         int len;
533         float x, y;
534         float size = scr_infobar_height.value;
535         char temp[256];
536
537         if (!cls.qw_downloadname[0])
538         {
539                 cls.qw_downloadspeedrate = 0;
540                 cls.qw_downloadspeedtime = host.realtime;
541                 cls.qw_downloadspeedcount = 0;
542                 return 0;
543         }
544         if (host.realtime >= cls.qw_downloadspeedtime + 1)
545         {
546                 cls.qw_downloadspeedrate = cls.qw_downloadspeedcount;
547                 cls.qw_downloadspeedtime = host.realtime;
548                 cls.qw_downloadspeedcount = 0;
549         }
550         if (cls.protocol == PROTOCOL_QUAKEWORLD)
551                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i) at %i bytes/s", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadspeedrate);
552         else
553                 dpsnprintf(temp, sizeof(temp), "Downloading %s %3i%% (%i/%i) at %i bytes/s", cls.qw_downloadname, cls.qw_downloadpercent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize, cls.qw_downloadspeedrate);
554         len = (int)strlen(temp);
555         x = (vid_conwidth.integer - DrawQ_TextWidth(temp, len, size, size, true, FONT_INFOBAR)) / 2;
556         y = vid_conheight.integer - size - offset;
557         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
558         DrawQ_String(x, y, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
559         return size;
560 }
561 /*
562 ==============
563 SCR_DrawInfobarString
564 ==============
565 */
566 static int SCR_DrawInfobarString(int offset)
567 {
568         int len;
569         float x, y;
570         float size = scr_infobar_height.value;
571
572         len = (int)strlen(scr_infobarstring);
573         x = (vid_conwidth.integer - DrawQ_TextWidth(scr_infobarstring, len, size, size, false, FONT_INFOBAR)) / 2;
574         y = vid_conheight.integer - size - offset;
575         DrawQ_Fill(0, y, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
576         DrawQ_String(x, y, scr_infobarstring, len, size, size, 1, 1, 1, 1, 0, NULL, false, FONT_INFOBAR);
577         return size;
578 }
579
580 /*
581 ==============
582 SCR_DrawCurlDownload
583 ==============
584 */
585 static int SCR_DrawCurlDownload(int offset)
586 {
587         // sync with SCR_InfobarHeight
588         int len;
589         int nDownloads;
590         int i;
591         float x, y;
592         float size = scr_infobar_height.value;
593         Curl_downloadinfo_t *downinfo;
594         char temp[256];
595         char addinfobuf[128];
596         const char *addinfo;
597
598         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo, addinfobuf, sizeof(addinfobuf));
599         if(!downinfo)
600                 return 0;
601
602         y = vid_conheight.integer - size * nDownloads - offset;
603
604         if(addinfo)
605         {
606                 len = (int)strlen(addinfo);
607                 x = (vid_conwidth.integer - DrawQ_TextWidth(addinfo, len, size, size, true, FONT_INFOBAR)) / 2;
608                 DrawQ_Fill(0, y - size, vid_conwidth.integer, size, 1, 1, 1, cls.signon == SIGNONS ? 0.8 : 1, 0);
609                 DrawQ_String(x, y - size, addinfo, len, size, size, 0, 0, 0, 1, 0, NULL, true, FONT_INFOBAR);
610         }
611
612         for(i = 0; i != nDownloads; ++i)
613         {
614                 if(downinfo[i].queued)
615                         dpsnprintf(temp, sizeof(temp), "Still in queue: %s", downinfo[i].filename);
616                 else if(downinfo[i].progress <= 0)
617                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  ???.?%% @ %.1f KiB/s", downinfo[i].filename, downinfo[i].speed / 1024.0);
618                 else
619                         dpsnprintf(temp, sizeof(temp), "Downloading %s ...  %5.1f%% @ %.1f KiB/s", downinfo[i].filename, 100.0 * downinfo[i].progress, downinfo[i].speed / 1024.0);
620                 len = (int)strlen(temp);
621                 x = (vid_conwidth.integer - DrawQ_TextWidth(temp, len, size, size, true, FONT_INFOBAR)) / 2;
622                 DrawQ_Fill(0, y + i * size, vid_conwidth.integer, size, 0, 0, 0, cls.signon == SIGNONS ? 0.5 : 1, 0);
623                 DrawQ_String(x, y + i * size, temp, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
624         }
625
626         Z_Free(downinfo);
627
628         return size * (nDownloads + (addinfo ? 1 : 0));
629 }
630
631 /*
632 ==============
633 SCR_DrawInfobar
634 ==============
635 */
636 static void SCR_DrawInfobar(void)
637 {
638         unsigned int offset = 0;
639         offset += SCR_DrawQWDownload(offset);
640         offset += SCR_DrawCurlDownload(offset);
641         if(scr_infobartime_off > 0)
642                 offset += SCR_DrawInfobarString(offset);
643         if(!offset && scr_loading)
644                 offset = scr_loadingscreen_barheight.integer;
645         if(offset != scr_con_margin_bottom)
646                 Con_DPrintf("broken console margin calculation: %d != %d\n", offset, scr_con_margin_bottom);
647 }
648
649 static int SCR_InfobarHeight(void)
650 {
651         int offset = 0;
652         Curl_downloadinfo_t *downinfo;
653         const char *addinfo;
654         int nDownloads;
655         char addinfobuf[128];
656
657         if (cl.time > cl.oldtime)
658                 scr_infobartime_off -= cl.time - cl.oldtime;
659         if(scr_infobartime_off > 0)
660                 offset += 1;
661         if(cls.qw_downloadname[0])
662                 offset += 1;
663
664         downinfo = Curl_GetDownloadInfo(&nDownloads, &addinfo, addinfobuf, sizeof(addinfobuf));
665         if(downinfo)
666         {
667                 offset += (nDownloads + (addinfo ? 1 : 0));
668                 Z_Free(downinfo);
669         }
670         offset *= scr_infobar_height.value;
671
672         return offset;
673 }
674
675 /*
676 ==============
677 SCR_InfoBar_f
678 ==============
679 */
680 static void SCR_InfoBar_f(cmd_state_t *cmd)
681 {
682         if(Cmd_Argc(cmd) == 3)
683         {
684                 scr_infobartime_off = atof(Cmd_Argv(cmd, 1));
685                 dp_strlcpy(scr_infobarstring, Cmd_Argv(cmd, 2), sizeof(scr_infobarstring));
686         }
687         else
688         {
689                 Con_Printf("usage:\ninfobar expiretime \"string\"\n");
690         }
691 }
692 //=============================================================================
693
694 /*
695 ==================
696 SCR_SetUpToDrawConsole
697 ==================
698 */
699 static void SCR_SetUpToDrawConsole (void)
700 {
701 #ifdef CONFIG_MENU
702         static int framecounter = 0;
703 #endif
704
705         Con_CheckResize ();
706
707 #ifdef CONFIG_MENU
708         if (scr_menuforcewhiledisconnected.integer && key_dest == key_game && cls.state == ca_disconnected)
709         {
710                 if (framecounter >= 2)
711                         MR_ToggleMenu(1);
712                 else
713                         framecounter++;
714         }
715         else
716                 framecounter = 0;
717 #endif
718
719         if (scr_conforcewhiledisconnected.integer >= 2 && key_dest == key_game && cls.signon != SIGNONS)
720                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
721         else if (scr_conforcewhiledisconnected.integer >= 1 && key_dest == key_game && cls.signon != SIGNONS && !sv.active)
722                 key_consoleactive |= KEY_CONSOLEACTIVE_FORCED;
723         else
724                 key_consoleactive &= ~KEY_CONSOLEACTIVE_FORCED;
725
726         // decide on the height of the console
727         if (key_consoleactive & KEY_CONSOLEACTIVE_USER)
728                 scr_con_current = vid_conheight.integer * scr_conheight.value;
729         else
730                 scr_con_current = 0; // none visible
731 }
732
733 /*
734 ==================
735 SCR_DrawConsole
736 ==================
737 */
738 void SCR_DrawConsole (void)
739 {
740         // infobar and loading progress are not drawn simultaneously
741         scr_con_margin_bottom = SCR_InfobarHeight();
742         if (!scr_con_margin_bottom && scr_loading)
743                 scr_con_margin_bottom = scr_loadingscreen_barheight.integer;
744         if (key_consoleactive & KEY_CONSOLEACTIVE_FORCED)
745         {
746                 // full screen
747                 Con_DrawConsole (vid_conheight.integer - scr_con_margin_bottom);
748         }
749         else if (scr_con_current)
750                 Con_DrawConsole (min(scr_con_current, vid_conheight.integer - scr_con_margin_bottom));
751         else
752                 con_vislines = 0;
753 }
754
755 //=============================================================================
756
757 /*
758 =================
759 SCR_SizeUp_f
760
761 Keybinding command
762 =================
763 */
764 static void SCR_SizeUp_f(cmd_state_t *cmd)
765 {
766         Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value + 10);
767 }
768
769
770 /*
771 =================
772 SCR_SizeDown_f
773
774 Keybinding command
775 =================
776 */
777 static void SCR_SizeDown_f(cmd_state_t *cmd)
778 {
779         Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value - 10);
780 }
781
782 #ifdef CONFIG_VIDEO_CAPTURE
783 void SCR_CaptureVideo_EndVideo(void);
784 #endif
785 void CL_Screen_Shutdown(void)
786 {
787 #ifdef CONFIG_VIDEO_CAPTURE
788         SCR_CaptureVideo_EndVideo();
789 #endif
790 }
791
792 void CL_Screen_Init(void)
793 {
794         int i;
795         Cvar_RegisterVariable (&scr_fov);
796         Cvar_RegisterVariable (&scr_viewsize);
797         Cvar_RegisterVariable (&scr_conalpha);
798         Cvar_RegisterVariable (&scr_conalphafactor);
799         Cvar_RegisterVariable (&scr_conalpha2factor);
800         Cvar_RegisterVariable (&scr_conalpha3factor);
801         Cvar_RegisterVariable (&scr_conscroll_x);
802         Cvar_RegisterVariable (&scr_conscroll_y);
803         Cvar_RegisterVariable (&scr_conscroll2_x);
804         Cvar_RegisterVariable (&scr_conscroll2_y);
805         Cvar_RegisterVariable (&scr_conscroll3_x);
806         Cvar_RegisterVariable (&scr_conscroll3_y);
807         Cvar_RegisterVariable (&scr_conbrightness);
808         Cvar_RegisterVariable (&scr_conforcewhiledisconnected);
809         Cvar_RegisterVariable (&scr_conheight);
810 #ifdef CONFIG_MENU
811         Cvar_RegisterVariable (&scr_menuforcewhiledisconnected);
812 #endif
813         Cvar_RegisterVariable (&scr_loadingscreen_background);
814         Cvar_RegisterVariable (&scr_loadingscreen_scale);
815         Cvar_RegisterVariable (&scr_loadingscreen_scale_base);
816         Cvar_RegisterVariable (&scr_loadingscreen_scale_limit);
817         Cvar_RegisterVariable (&scr_loadingscreen_picture);
818         Cvar_RegisterVariable (&scr_loadingscreen_count);
819         Cvar_RegisterVariable (&scr_loadingscreen_firstforstartup);
820         Cvar_RegisterVariable (&scr_loadingscreen_barcolor);
821         Cvar_RegisterVariable (&scr_loadingscreen_barheight);
822         Cvar_RegisterVariable (&scr_loadingscreen_maxfps);
823         Cvar_RegisterVariable (&scr_infobar_height);
824         Cvar_RegisterVariable (&scr_showram);
825         Cvar_RegisterVariable (&scr_showturtle);
826         Cvar_RegisterVariable (&scr_showpause);
827         Cvar_RegisterVariable (&scr_showbrand);
828         Cvar_RegisterVariable (&scr_centertime);
829         Cvar_RegisterVariable (&scr_printspeed);
830         Cvar_RegisterVariable (&vid_conwidth);
831         Cvar_RegisterVariable (&vid_conheight);
832         Cvar_RegisterVariable (&vid_pixelheight);
833         Cvar_RegisterVariable (&vid_conwidthauto);
834         Cvar_RegisterVariable (&scr_screenshot_jpeg);
835         Cvar_RegisterVariable (&scr_screenshot_jpeg_quality);
836         Cvar_RegisterVariable (&scr_screenshot_png);
837         Cvar_RegisterVariable (&scr_screenshot_gammaboost);
838         Cvar_RegisterVariable (&scr_screenshot_name_in_mapdir);
839         Cvar_RegisterVariable (&scr_screenshot_alpha);
840         Cvar_RegisterVariable (&scr_screenshot_timestamp);
841 #ifdef CONFIG_VIDEO_CAPTURE
842         Cvar_RegisterVariable (&cl_capturevideo);
843         Cvar_RegisterVariable (&cl_capturevideo_demo_stop);
844         Cvar_RegisterVariable (&cl_capturevideo_printfps);
845         Cvar_RegisterVariable (&cl_capturevideo_width);
846         Cvar_RegisterVariable (&cl_capturevideo_height);
847         Cvar_RegisterVariable (&cl_capturevideo_realtime);
848         Cvar_RegisterVariable (&cl_capturevideo_fps);
849         Cvar_RegisterVariable (&cl_capturevideo_nameformat);
850         Cvar_RegisterVariable (&cl_capturevideo_number);
851         Cvar_RegisterVariable (&cl_capturevideo_ogg);
852         Cvar_RegisterVariable (&cl_capturevideo_framestep);
853 #endif
854         Cvar_RegisterVariable (&r_letterbox);
855         Cvar_RegisterVariable(&r_stereo_separation);
856         Cvar_RegisterVariable(&r_stereo_sidebyside);
857         Cvar_RegisterVariable(&r_stereo_horizontal);
858         Cvar_RegisterVariable(&r_stereo_vertical);
859         Cvar_RegisterVariable(&r_stereo_redblue);
860         Cvar_RegisterVariable(&r_stereo_redcyan);
861         Cvar_RegisterVariable(&r_stereo_redgreen);
862         Cvar_RegisterVariable(&r_stereo_angle);
863         Cvar_RegisterVariable(&scr_stipple);
864         Cvar_RegisterVariable(&scr_refresh);
865         Cvar_RegisterVariable(&net_graph);
866         Cvar_RegisterVirtual(&net_graph, "shownetgraph");
867         Cvar_RegisterVariable(&cl_demo_mousegrab);
868         Cvar_RegisterVariable(&timedemo_screenshotframelist);
869         Cvar_RegisterVariable(&vid_touchscreen_outlinealpha);
870         Cvar_RegisterVariable(&vid_touchscreen_overlayalpha);
871         Cvar_RegisterVariable(&r_speeds_graph);
872         for (i = 0;i < (int)(sizeof(r_speeds_graph_filter)/sizeof(r_speeds_graph_filter[0]));i++)
873                 Cvar_RegisterVariable(&r_speeds_graph_filter[i]);
874         Cvar_RegisterVariable(&r_speeds_graph_length);
875         Cvar_RegisterVariable(&r_speeds_graph_seconds);
876         Cvar_RegisterVariable(&r_speeds_graph_x);
877         Cvar_RegisterVariable(&r_speeds_graph_y);
878         Cvar_RegisterVariable(&r_speeds_graph_width);
879         Cvar_RegisterVariable(&r_speeds_graph_height);
880         Cvar_RegisterVariable(&r_speeds_graph_maxtimedelta);
881         Cvar_RegisterVariable(&r_speeds_graph_maxdefault);
882
883         // if we want no console, turn it off here too
884         if (Sys_CheckParm ("-noconsole"))
885                 Cvar_SetQuick(&scr_conforcewhiledisconnected, "0");
886
887         Cmd_AddCommand(CF_CLIENT, "cprint", SCR_Centerprint_f, "print something at the screen center");
888         Cmd_AddCommand(CF_CLIENT, "sizeup",SCR_SizeUp_f, "increase view size (increases viewsize cvar)");
889         Cmd_AddCommand(CF_CLIENT, "sizedown",SCR_SizeDown_f, "decrease view size (decreases viewsize cvar)");
890         Cmd_AddCommand(CF_CLIENT, "screenshot",SCR_ScreenShot_f, "takes a screenshot of the next rendered frame");
891         Cmd_AddCommand(CF_CLIENT, "envmap", R_Envmap_f, "render a cubemap (skybox) of the current scene");
892         Cmd_AddCommand(CF_CLIENT, "infobar", SCR_InfoBar_f, "display a text in the infobar (usage: infobar expiretime string)");
893
894 #ifdef CONFIG_VIDEO_CAPTURE
895         SCR_CaptureVideo_Ogg_Init();
896 #endif
897
898         scr_initialized = true;
899 }
900
901 /*
902 ==================
903 SCR_ScreenShot_f
904 ==================
905 */
906 void SCR_ScreenShot_f(cmd_state_t *cmd)
907 {
908         static int shotnumber;
909         static char old_prefix_name[MAX_QPATH];
910         char prefix_name[MAX_QPATH];
911         char filename[MAX_QPATH];
912         unsigned char *buffer1;
913         unsigned char *buffer2;
914         qbool jpeg = (scr_screenshot_jpeg.integer != 0);
915         qbool png = (scr_screenshot_png.integer != 0) && !jpeg;
916         char vabuf[1024];
917
918         if (Cmd_Argc(cmd) == 2)
919         {
920                 const char *ext;
921                 dp_strlcpy(filename, Cmd_Argv(cmd, 1), sizeof(filename));
922                 ext = FS_FileExtension(filename);
923                 if (!strcasecmp(ext, "jpg"))
924                 {
925                         jpeg = true;
926                         png = false;
927                 }
928                 else if (!strcasecmp(ext, "tga"))
929                 {
930                         jpeg = false;
931                         png = false;
932                 }
933                 else if (!strcasecmp(ext, "png"))
934                 {
935                         jpeg = false;
936                         png = true;
937                 }
938                 else
939                 {
940                         Con_Printf("screenshot: supplied filename must end in .jpg or .tga or .png\n");
941                         return;
942                 }
943         }
944         else if (scr_screenshot_timestamp.integer)
945         {
946                 int shotnumber100;
947
948                 // TODO maybe make capturevideo and screenshot use similar name patterns?
949                 if (scr_screenshot_name_in_mapdir.integer && cl.worldbasename[0])
950                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s/%s%s", cl.worldbasename, scr_screenshot_name.string, Sys_TimeString("%Y%m%d%H%M%S"));
951                 else
952                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s%s", scr_screenshot_name.string, Sys_TimeString("%Y%m%d%H%M%S"));
953
954                 // find a file name to save it to
955                 for (shotnumber100 = 0;shotnumber100 < 100;shotnumber100++)
956                         if (!FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.tga", fs_gamedir, prefix_name, shotnumber100))
957                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.jpg", fs_gamedir, prefix_name, shotnumber100))
958                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s-%02d.png", fs_gamedir, prefix_name, shotnumber100)))
959                                 break;
960                 if (shotnumber100 >= 100)
961                 {
962                         Con_Print("Couldn't create the image file - already 100 shots taken this second!\n");
963                         return;
964                 }
965
966                 dpsnprintf(filename, sizeof(filename), "screenshots/%s-%02d.%s", prefix_name, shotnumber100, jpeg ? "jpg" : png ? "png" : "tga");
967         }
968         else
969         {
970                 // TODO maybe make capturevideo and screenshot use similar name patterns?
971                 if (scr_screenshot_name_in_mapdir.integer && cl.worldbasename[0])
972                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s/%s", cl.worldbasename, Sys_TimeString(scr_screenshot_name.string));
973                 else
974                         dpsnprintf(prefix_name, sizeof(prefix_name), "%s", Sys_TimeString(scr_screenshot_name.string));
975
976                 // if prefix changed, gamedir or map changed, reset the shotnumber so
977                 // we scan again
978                 // FIXME: should probably do this whenever FS_Rescan or something like that occurs?
979                 if (strcmp(old_prefix_name, prefix_name))
980                 {
981                         dpsnprintf(old_prefix_name, sizeof(old_prefix_name), "%s", prefix_name );
982                         shotnumber = 0;
983                 }
984
985                 // find a file name to save it to
986                 for (;shotnumber < 1000000;shotnumber++)
987                         if (!FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.tga", fs_gamedir, prefix_name, shotnumber))
988                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.jpg", fs_gamedir, prefix_name, shotnumber))
989                          && !FS_SysFileExists(va(vabuf, sizeof(vabuf), "%s/screenshots/%s%06d.png", fs_gamedir, prefix_name, shotnumber)))
990                                 break;
991                 if (shotnumber >= 1000000)
992                 {
993                         Con_Print("Couldn't create the image file - you already have 1000000 screenshots!\n");
994                         return;
995                 }
996
997                 dpsnprintf(filename, sizeof(filename), "screenshots/%s%06d.%s", prefix_name, shotnumber, jpeg ? "jpg" : png ? "png" : "tga");
998
999                 shotnumber++;
1000         }
1001
1002         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.mode.width * vid.mode.height * 4);
1003         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.mode.width * vid.mode.height * (scr_screenshot_alpha.integer ? 4 : 3));
1004
1005         if (SCR_ScreenShot (filename, buffer1, buffer2, 0, 0, vid.mode.width, vid.mode.height, false, false, false, jpeg, png, true, scr_screenshot_alpha.integer != 0))
1006                 Con_Printf("Wrote %s\n", filename);
1007         else
1008         {
1009                 Con_Printf(CON_ERROR "Unable to write %s\n", filename);
1010                 if(jpeg || png)
1011                 {
1012                         if(SCR_ScreenShot (filename, buffer1, buffer2, 0, 0, vid.mode.width, vid.mode.height, false, false, false, false, false, true, scr_screenshot_alpha.integer != 0))
1013                         {
1014                                 dp_strlcpy(filename + strlen(filename) - 3, "tga", 4);
1015                                 Con_Printf("Wrote %s\n", filename);
1016                         }
1017                 }
1018         }
1019
1020         Mem_Free (buffer1);
1021         Mem_Free (buffer2);
1022 }
1023
1024 #ifdef CONFIG_VIDEO_CAPTURE
1025 static void SCR_CaptureVideo_BeginVideo(void)
1026 {
1027         double r, g, b;
1028         unsigned int i;
1029         int width = cl_capturevideo_width.integer, height = cl_capturevideo_height.integer;
1030         if (cls.capturevideo.active)
1031                 return;
1032         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1033         // soundrate is figured out on the first SoundFrame
1034
1035         if(width == 0 && height != 0)
1036                 width = (int) (height * (double)vid.mode.width / ((double)vid.mode.height * vid_pixelheight.value)); // keep aspect
1037         if(width != 0 && height == 0)
1038                 height = (int) (width * ((double)vid.mode.height * vid_pixelheight.value) / (double)vid.mode.width); // keep aspect
1039
1040         if(width < 2 || width > vid.mode.width) // can't scale up
1041                 width = vid.mode.width;
1042         if(height < 2 || height > vid.mode.height) // can't scale up
1043                 height = vid.mode.height;
1044
1045         // ensure it's all even; if not, scale down a little
1046         if(width % 1)
1047                 --width;
1048         if(height % 1)
1049                 --height;
1050
1051         cls.capturevideo.width = width;
1052         cls.capturevideo.height = height;
1053         cls.capturevideo.active = true;
1054         cls.capturevideo.framerate = bound(1, cl_capturevideo_fps.value, 1001) * bound(1, cl_capturevideo_framestep.integer, 64);
1055         cls.capturevideo.framestep = cl_capturevideo_framestep.integer;
1056         cls.capturevideo.soundrate = S_GetSoundRate();
1057         cls.capturevideo.soundchannels = S_GetSoundChannels();
1058         cls.capturevideo.startrealtime = host.realtime;
1059         cls.capturevideo.frame = cls.capturevideo.lastfpsframe = 0;
1060         cls.capturevideo.starttime = cls.capturevideo.lastfpstime = host.realtime;
1061         cls.capturevideo.soundsampleframe = 0;
1062         cls.capturevideo.realtime = cl_capturevideo_realtime.integer != 0;
1063         cls.capturevideo.screenbuffer = (unsigned char *)Mem_Alloc(tempmempool, vid.mode.width * vid.mode.height * 4);
1064         cls.capturevideo.outbuffer = (unsigned char *)Mem_Alloc(tempmempool, width * height * (4+4) + 18);
1065         dpsnprintf(cls.capturevideo.basename, sizeof(cls.capturevideo.basename), "video/%s%03i", Sys_TimeString(cl_capturevideo_nameformat.string), cl_capturevideo_number.integer);
1066         Cvar_SetValueQuick(&cl_capturevideo_number, cl_capturevideo_number.integer + 1);
1067
1068         /*
1069         for (i = 0;i < 256;i++)
1070         {
1071                 unsigned char j = (unsigned char)bound(0, 255*pow(i/255.0, gamma), 255);
1072                 cls.capturevideo.rgbgammatable[0][i] = j;
1073                 cls.capturevideo.rgbgammatable[1][i] = j;
1074                 cls.capturevideo.rgbgammatable[2][i] = j;
1075         }
1076         */
1077 /*
1078 R = Y + 1.4075 * (Cr - 128);
1079 G = Y + -0.3455 * (Cb - 128) + -0.7169 * (Cr - 128);
1080 B = Y + 1.7790 * (Cb - 128);
1081 Y = R *  .299 + G *  .587 + B *  .114;
1082 Cb = R * -.169 + G * -.332 + B *  .500 + 128.;
1083 Cr = R *  .500 + G * -.419 + B * -.0813 + 128.;
1084 */
1085
1086         // identity gamma table
1087         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp, 256);
1088         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp + 256, 256);
1089         BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, cls.capturevideo.vidramp + 256*2, 256);
1090         if(scr_screenshot_gammaboost.value != 1)
1091         {
1092                 double igamma = 1 / scr_screenshot_gammaboost.value;
1093                 for (i = 0;i < 256 * 3;i++)
1094                         cls.capturevideo.vidramp[i] = (unsigned short) (0.5 + pow(cls.capturevideo.vidramp[i] * (1.0 / 65535.0), igamma) * 65535.0);
1095         }
1096
1097         for (i = 0;i < 256;i++)
1098         {
1099                 r = 255*cls.capturevideo.vidramp[i]/65535.0;
1100                 g = 255*cls.capturevideo.vidramp[i+256]/65535.0;
1101                 b = 255*cls.capturevideo.vidramp[i+512]/65535.0;
1102                 // NOTE: we have to round DOWN here, or integer overflows happen. Sorry for slightly wrong looking colors sometimes...
1103                 // Y weights from RGB
1104                 cls.capturevideo.rgbtoyuvscaletable[0][0][i] = (short)(r *  0.299);
1105                 cls.capturevideo.rgbtoyuvscaletable[0][1][i] = (short)(g *  0.587);
1106                 cls.capturevideo.rgbtoyuvscaletable[0][2][i] = (short)(b *  0.114);
1107                 // Cb weights from RGB
1108                 cls.capturevideo.rgbtoyuvscaletable[1][0][i] = (short)(r * -0.169);
1109                 cls.capturevideo.rgbtoyuvscaletable[1][1][i] = (short)(g * -0.332);
1110                 cls.capturevideo.rgbtoyuvscaletable[1][2][i] = (short)(b *  0.500);
1111                 // Cr weights from RGB
1112                 cls.capturevideo.rgbtoyuvscaletable[2][0][i] = (short)(r *  0.500);
1113                 cls.capturevideo.rgbtoyuvscaletable[2][1][i] = (short)(g * -0.419);
1114                 cls.capturevideo.rgbtoyuvscaletable[2][2][i] = (short)(b * -0.0813);
1115                 // range reduction of YCbCr to valid signal range
1116                 cls.capturevideo.yuvnormalizetable[0][i] = 16 + i * (236-16) / 256;
1117                 cls.capturevideo.yuvnormalizetable[1][i] = 16 + i * (240-16) / 256;
1118                 cls.capturevideo.yuvnormalizetable[2][i] = 16 + i * (240-16) / 256;
1119         }
1120
1121         if (cl_capturevideo_ogg.integer)
1122         {
1123                 if(SCR_CaptureVideo_Ogg_Available())
1124                 {
1125                         SCR_CaptureVideo_Ogg_BeginVideo();
1126                         return;
1127                 }
1128                 else
1129                         Con_Print("cl_capturevideo_ogg: libraries not available. Capturing in AVI instead.\n");
1130         }
1131
1132         SCR_CaptureVideo_Avi_BeginVideo();
1133 }
1134
1135 void SCR_CaptureVideo_EndVideo(void)
1136 {
1137         if (!cls.capturevideo.active)
1138                 return;
1139         cls.capturevideo.active = false;
1140
1141         Con_Printf("Finishing capture of %s.%s (%d frames, %d audio frames)\n", cls.capturevideo.basename, cls.capturevideo.formatextension, cls.capturevideo.frame, cls.capturevideo.soundsampleframe);
1142
1143         if (cls.capturevideo.videofile)
1144         {
1145                 cls.capturevideo.endvideo();
1146         }
1147
1148         if (cls.capturevideo.screenbuffer)
1149         {
1150                 Mem_Free (cls.capturevideo.screenbuffer);
1151                 cls.capturevideo.screenbuffer = NULL;
1152         }
1153
1154         if (cls.capturevideo.outbuffer)
1155         {
1156                 Mem_Free (cls.capturevideo.outbuffer);
1157                 cls.capturevideo.outbuffer = NULL;
1158         }
1159
1160         memset(&cls.capturevideo, 0, sizeof(cls.capturevideo));
1161 }
1162
1163 static void SCR_ScaleDownBGRA(unsigned char *in, int inw, int inh, unsigned char *out, int outw, int outh)
1164 {
1165         // TODO optimize this function
1166
1167         int x, y;
1168         float area;
1169
1170         // memcpy is faster than me
1171         if(inw == outw && inh == outh)
1172         {
1173                 memcpy(out, in, 4 * inw * inh);
1174                 return;
1175         }
1176
1177         // otherwise: a box filter
1178         area = (float)outw * (float)outh / (float)inw / (float)inh;
1179         for(y = 0; y < outh; ++y)
1180         {
1181                 float iny0 =  y    / (float)outh * inh; int iny0_i = (int) floor(iny0);
1182                 float iny1 = (y+1) / (float)outh * inh; int iny1_i = (int) ceil(iny1);
1183                 for(x = 0; x < outw; ++x)
1184                 {
1185                         float inx0 =  x    / (float)outw * inw; int inx0_i = (int) floor(inx0);
1186                         float inx1 = (x+1) / (float)outw * inw; int inx1_i = (int) ceil(inx1);
1187                         float r = 0, g = 0, b = 0, alpha = 0;
1188                         int xx, yy;
1189
1190                         for(yy = iny0_i; yy < iny1_i; ++yy)
1191                         {
1192                                 float ya = min(yy+1, iny1) - max(iny0, yy);
1193                                 for(xx = inx0_i; xx < inx1_i; ++xx)
1194                                 {
1195                                         float a = ya * (min(xx+1, inx1) - max(inx0, xx));
1196                                         r += a * in[4*(xx + inw * yy)+0];
1197                                         g += a * in[4*(xx + inw * yy)+1];
1198                                         b += a * in[4*(xx + inw * yy)+2];
1199                                         alpha += a * in[4*(xx + inw * yy)+3];
1200                                 }
1201                         }
1202
1203                         out[4*(x + outw * y)+0] = (unsigned char) (r * area);
1204                         out[4*(x + outw * y)+1] = (unsigned char) (g * area);
1205                         out[4*(x + outw * y)+2] = (unsigned char) (b * area);
1206                         out[4*(x + outw * y)+3] = (unsigned char) (alpha * area);
1207                 }
1208         }
1209 }
1210
1211 static void SCR_CaptureVideo_VideoFrame(int newframestepframenum)
1212 {
1213         int x = 0, y = 0;
1214         int width = cls.capturevideo.width, height = cls.capturevideo.height;
1215
1216         if(newframestepframenum == cls.capturevideo.framestepframe)
1217                 return;
1218
1219         CHECKGLERROR
1220         // speed is critical here, so do saving as directly as possible
1221
1222         GL_ReadPixelsBGRA(x, y, vid.mode.width, vid.mode.height, cls.capturevideo.screenbuffer);
1223
1224         SCR_ScaleDownBGRA (cls.capturevideo.screenbuffer, vid.mode.width, vid.mode.height, cls.capturevideo.outbuffer, width, height);
1225
1226         cls.capturevideo.videoframes(newframestepframenum - cls.capturevideo.framestepframe);
1227         cls.capturevideo.framestepframe = newframestepframenum;
1228
1229         if(cl_capturevideo_printfps.integer && host.realtime > cls.capturevideo.lastfpstime + 1)
1230         {
1231                 double fps1 = (cls.capturevideo.frame - cls.capturevideo.lastfpsframe) / (host.realtime - cls.capturevideo.lastfpstime + 0.0000001);
1232                 double fps  = (cls.capturevideo.frame                                ) / (host.realtime - cls.capturevideo.starttime   + 0.0000001);
1233                 Sys_Printf("capturevideo: (%.1fs) last second %.3ffps, total %.3ffps\n", cls.capturevideo.frame / cls.capturevideo.framerate, fps1, fps);
1234                 cls.capturevideo.lastfpstime = host.realtime;
1235                 cls.capturevideo.lastfpsframe = cls.capturevideo.frame;
1236         }
1237 }
1238
1239 void SCR_CaptureVideo_SoundFrame(const portable_sampleframe_t *paintbuffer, size_t length)
1240 {
1241         cls.capturevideo.soundsampleframe += (int)length;
1242         cls.capturevideo.soundframe(paintbuffer, length);
1243 }
1244
1245 static void SCR_CaptureVideo(void)
1246 {
1247         int newframenum;
1248         if (cl_capturevideo.integer)
1249         {
1250                 if (!cls.capturevideo.active)
1251                         SCR_CaptureVideo_BeginVideo();
1252                 if (cls.capturevideo.framerate != cl_capturevideo_fps.value * cl_capturevideo_framestep.integer)
1253                 {
1254                         Con_Printf("You can not change the video framerate while recording a video.\n");
1255                         Cvar_SetValueQuick(&cl_capturevideo_fps, cls.capturevideo.framerate / (double) cl_capturevideo_framestep.integer);
1256                 }
1257                 // for AVI saving we have to make sure that sound is saved before video
1258                 if (cls.capturevideo.soundrate && !cls.capturevideo.soundsampleframe)
1259                         return;
1260                 if (cls.capturevideo.realtime)
1261                 {
1262                         // preserve sound sync by duplicating frames when running slow
1263                         newframenum = (int)((host.realtime - cls.capturevideo.startrealtime) * cls.capturevideo.framerate);
1264                 }
1265                 else
1266                         newframenum = cls.capturevideo.frame + 1;
1267                 // if falling behind more than one second, stop
1268                 if (newframenum - cls.capturevideo.frame > 60 * (int)ceil(cls.capturevideo.framerate))
1269                 {
1270                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1271                         Con_Printf("video saving failed on frame %i, your machine is too slow for this capture speed.\n", cls.capturevideo.frame);
1272                         SCR_CaptureVideo_EndVideo();
1273                         return;
1274                 }
1275                 // write frames
1276                 SCR_CaptureVideo_VideoFrame(newframenum / cls.capturevideo.framestep);
1277                 cls.capturevideo.frame = newframenum;
1278                 if (cls.capturevideo.error)
1279                 {
1280                         Cvar_SetValueQuick(&cl_capturevideo, 0);
1281                         Con_Printf("video saving failed on frame %i, out of disk space? stopping video capture.\n", cls.capturevideo.frame);
1282                         SCR_CaptureVideo_EndVideo();
1283                 }
1284         }
1285         else if (cls.capturevideo.active)
1286                 SCR_CaptureVideo_EndVideo();
1287 }
1288 #endif
1289
1290 /*
1291 ===============
1292 R_Envmap_f
1293
1294 Grab six views for environment mapping tests
1295 ===============
1296 */
1297 struct envmapinfo_s
1298 {
1299         float angles[3];
1300         const char *name;
1301         qbool flipx, flipy, flipdiagonaly;
1302 }
1303 envmapinfo[12] =
1304 {
1305         {{  0,   0, 0}, "rt", false, false, false},
1306         {{  0, 270, 0}, "ft", false, false, false},
1307         {{  0, 180, 0}, "lf", false, false, false},
1308         {{  0,  90, 0}, "bk", false, false, false},
1309         {{-90, 180, 0}, "up",  true,  true, false},
1310         {{ 90, 180, 0}, "dn",  true,  true, false},
1311
1312         {{  0,   0, 0}, "px",  true,  true,  true},
1313         {{  0,  90, 0}, "py", false,  true, false},
1314         {{  0, 180, 0}, "nx", false, false,  true},
1315         {{  0, 270, 0}, "ny",  true, false, false},
1316         {{-90, 180, 0}, "pz", false, false,  true},
1317         {{ 90, 180, 0}, "nz", false, false,  true}
1318 };
1319
1320 static void R_Envmap_f(cmd_state_t *cmd)
1321 {
1322         int j, size;
1323         char filename[MAX_QPATH], basename[MAX_QPATH];
1324         unsigned char *buffer1;
1325         unsigned char *buffer2;
1326         r_rendertarget_t *rt;
1327
1328         if (Cmd_Argc(cmd) != 3)
1329         {
1330                 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");
1331                 return;
1332         }
1333
1334         if(cls.state != ca_connected) {
1335                 Con_Printf("envmap: No map loaded\n");
1336                 return;
1337         }
1338
1339         dp_strlcpy (basename, Cmd_Argv(cmd, 1), sizeof (basename));
1340         size = atoi(Cmd_Argv(cmd, 2));
1341         if (size != 128 && size != 256 && size != 512 && size != 1024)
1342         {
1343                 Con_Print("envmap: size must be one of 128, 256, 512, or 1024\n");
1344                 return;
1345         }
1346         if (size > vid.mode.width || size > vid.mode.height)
1347         {
1348                 Con_Print("envmap: your resolution is not big enough to render that size\n");
1349                 return;
1350         }
1351
1352         r_refdef.envmap = true;
1353
1354         R_UpdateVariables();
1355
1356         r_refdef.view.x = 0;
1357         r_refdef.view.y = 0;
1358         r_refdef.view.z = 0;
1359         r_refdef.view.width = size;
1360         r_refdef.view.height = size;
1361         r_refdef.view.depth = 1;
1362         r_refdef.view.useperspective = true;
1363         r_refdef.view.isoverlay = false;
1364         r_refdef.view.ismain = true;
1365
1366         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
1367         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
1368         r_refdef.view.ortho_x = 90; // abused as angle by VM_CL_R_SetView
1369         r_refdef.view.ortho_y = 90; // abused as angle by VM_CL_R_SetView
1370
1371         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 4);
1372         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, size * size * 3);
1373
1374         // TODO: use TEXTYPE_COLORBUFFER16F and output to .exr files as well?
1375         rt = R_RenderTarget_Get(size, size, TEXTYPE_DEPTHBUFFER24STENCIL8, true, TEXTYPE_COLORBUFFER, TEXTYPE_UNUSED, TEXTYPE_UNUSED, TEXTYPE_UNUSED);
1376         CL_UpdateEntityShading();
1377         for (j = 0;j < 12;j++)
1378         {
1379                 dpsnprintf(filename, sizeof(filename), "env/%s%s.tga", basename, envmapinfo[j].name);
1380                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.view.matrix, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], envmapinfo[j].angles[0], envmapinfo[j].angles[1], envmapinfo[j].angles[2], 1);
1381                 r_refdef.view.quality = 1;
1382                 r_refdef.view.clear = true;
1383                 R_Mesh_Start();
1384                 R_RenderView(rt->fbo, rt->depthtexture, rt->colortexture[0], 0, 0, size, size);
1385                 R_Mesh_Finish();
1386                 SCR_ScreenShot(filename, buffer1, buffer2, 0, vid.mode.height - (r_refdef.view.y + r_refdef.view.height), size, size, envmapinfo[j].flipx, envmapinfo[j].flipy, envmapinfo[j].flipdiagonaly, false, false, false, false);
1387         }
1388
1389         Mem_Free (buffer1);
1390         Mem_Free (buffer2);
1391
1392         r_refdef.envmap = false;
1393 }
1394
1395 //=============================================================================
1396
1397 void SHOWLMP_decodehide(void)
1398 {
1399         int i;
1400         char *lmplabel;
1401         lmplabel = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1402         for (i = 0;i < cl.num_showlmps;i++)
1403                 if (cl.showlmps[i].isactive && strcmp(cl.showlmps[i].label, lmplabel) == 0)
1404                 {
1405                         cl.showlmps[i].isactive = false;
1406                         return;
1407                 }
1408 }
1409
1410 void SHOWLMP_decodeshow(void)
1411 {
1412         int k;
1413         char lmplabel[256], picname[256];
1414         float x, y;
1415         dp_strlcpy (lmplabel,MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof (lmplabel));
1416         dp_strlcpy (picname, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof (picname));
1417         if (gamemode == GAME_NEHAHRA) // LadyHavoc: nasty old legacy junk
1418         {
1419                 x = MSG_ReadByte(&cl_message);
1420                 y = MSG_ReadByte(&cl_message);
1421         }
1422         else
1423         {
1424                 x = MSG_ReadShort(&cl_message);
1425                 y = MSG_ReadShort(&cl_message);
1426         }
1427         if (!cl.showlmps || cl.num_showlmps >= cl.max_showlmps)
1428         {
1429                 showlmp_t *oldshowlmps = cl.showlmps;
1430                 cl.max_showlmps += 16;
1431                 cl.showlmps = (showlmp_t *) Mem_Alloc(cls.levelmempool, cl.max_showlmps * sizeof(showlmp_t));
1432                 if (oldshowlmps)
1433                 {
1434                         if (cl.num_showlmps)
1435                                 memcpy(cl.showlmps, oldshowlmps, cl.num_showlmps * sizeof(showlmp_t));
1436                         Mem_Free(oldshowlmps);
1437                 }
1438         }
1439         for (k = 0;k < cl.max_showlmps;k++)
1440                 if (cl.showlmps[k].isactive && !strcmp(cl.showlmps[k].label, lmplabel))
1441                         break;
1442         if (k == cl.max_showlmps)
1443                 for (k = 0;k < cl.max_showlmps;k++)
1444                         if (!cl.showlmps[k].isactive)
1445                                 break;
1446         cl.showlmps[k].isactive = true;
1447         dp_strlcpy (cl.showlmps[k].label, lmplabel, sizeof (cl.showlmps[k].label));
1448         dp_strlcpy (cl.showlmps[k].pic, picname, sizeof (cl.showlmps[k].pic));
1449         cl.showlmps[k].x = x;
1450         cl.showlmps[k].y = y;
1451         cl.num_showlmps = max(cl.num_showlmps, k + 1);
1452 }
1453
1454 void SHOWLMP_drawall(void)
1455 {
1456         int i;
1457         for (i = 0;i < cl.num_showlmps;i++)
1458                 if (cl.showlmps[i].isactive)
1459                         DrawQ_Pic(cl.showlmps[i].x, cl.showlmps[i].y, Draw_CachePic_Flags (cl.showlmps[i].pic, CACHEPICFLAG_NOTPERSISTENT), 0, 0, 1, 1, 1, 1, 0);
1460 }
1461
1462 /*
1463 ==============================================================================
1464
1465                                                 SCREEN SHOTS
1466
1467 ==============================================================================
1468 */
1469
1470 // buffer1: 4*w*h
1471 // buffer2: 3*w*h (or 4*w*h if screenshotting alpha too)
1472 qbool SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, int x, int y, int width, int height, qbool flipx, qbool flipy, qbool flipdiagonal, qbool jpeg, qbool png, qbool gammacorrect, qbool keep_alpha)
1473 {
1474         int     indices[4] = {0,1,2,3}; // BGRA
1475         qbool ret;
1476
1477         GL_ReadPixelsBGRA(x, y, width, height, buffer1);
1478
1479         if(gammacorrect && (scr_screenshot_gammaboost.value != 1))
1480         {
1481                 int i;
1482                 double igamma = 1.0 / scr_screenshot_gammaboost.value;
1483                 unsigned short vidramp[256 * 3];
1484                 // identity gamma table
1485                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp, 256);
1486                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp + 256, 256);
1487                 BuildGammaTable16(1.0f, 1.0f, 1.0f, 0.0f, 1.0f, vidramp + 256*2, 256);
1488                 if(scr_screenshot_gammaboost.value != 1)
1489                 {
1490                         for (i = 0;i < 256 * 3;i++)
1491                                 vidramp[i] = (unsigned short) (0.5 + pow(vidramp[i] * (1.0 / 65535.0), igamma) * 65535.0);
1492                 }
1493                 for (i = 0;i < width*height*4;i += 4)
1494                 {
1495                         buffer1[i] = (unsigned char) (vidramp[buffer1[i] + 512] * 255.0 / 65535.0 + 0.5); // B
1496                         buffer1[i+1] = (unsigned char) (vidramp[buffer1[i+1] + 256] * 255.0 / 65535.0 + 0.5); // G
1497                         buffer1[i+2] = (unsigned char) (vidramp[buffer1[i+2]] * 255.0 / 65535.0 + 0.5); // R
1498                         // A
1499                 }
1500         }
1501
1502         if(keep_alpha && !jpeg)
1503         {
1504                 if(!png)
1505                         flipy = !flipy; // TGA: not preflipped
1506                 Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 4, 4, indices);
1507                 if (png)
1508                         ret = PNG_SaveImage_preflipped (filename, width, height, true, buffer2);
1509                 else
1510                         ret = Image_WriteTGABGRA(filename, width, height, buffer2);
1511         }
1512         else
1513         {
1514                 if(jpeg)
1515                 {
1516                         indices[0] = 2;
1517                         indices[2] = 0; // RGB
1518                 }
1519                 Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 4, indices);
1520                 if (jpeg)
1521                         ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1522                 else if (png)
1523                         ret = PNG_SaveImage_preflipped (filename, width, height, false, buffer2);
1524                 else
1525                         ret = Image_WriteTGABGR_preflipped (filename, width, height, buffer2);
1526         }
1527
1528         return ret;
1529 }
1530
1531 //=============================================================================
1532
1533 int scr_numtouchscreenareas;
1534 scr_touchscreenarea_t scr_touchscreenareas[128];
1535
1536 static void SCR_DrawTouchscreenOverlay(void)
1537 {
1538         int i;
1539         scr_touchscreenarea_t *a;
1540         cachepic_t *pic;
1541         for (i = 0, a = scr_touchscreenareas;i < scr_numtouchscreenareas;i++, a++)
1542         {
1543                 if (vid_touchscreen_outlinealpha.value > 0 && a->rect[0] >= 0 && a->rect[1] >= 0 && a->rect[2] >= 4 && a->rect[3] >= 4)
1544                 {
1545                         DrawQ_Fill(a->rect[0] +              2, a->rect[1]                 , a->rect[2] - 4,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1546                         DrawQ_Fill(a->rect[0] +              1, a->rect[1] +              1, a->rect[2] - 2,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1547                         DrawQ_Fill(a->rect[0]                 , a->rect[1] +              2,          2    , a->rect[3] - 2, 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1548                         DrawQ_Fill(a->rect[0] + a->rect[2] - 2, a->rect[1] +              2,          2    , a->rect[3] - 2, 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1549                         DrawQ_Fill(a->rect[0] +              1, a->rect[1] + a->rect[3] - 2, a->rect[2] - 2,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1550                         DrawQ_Fill(a->rect[0] +              2, a->rect[1] + a->rect[3] - 1, a->rect[2] - 4,          1    , 1, 1, 1, vid_touchscreen_outlinealpha.value * (0.5f + 0.5f * a->active), 0);
1551                 }
1552                 pic = a->pic ? Draw_CachePic_Flags(a->pic, CACHEPICFLAG_FAILONMISSING) : NULL;
1553                 if (Draw_IsPicLoaded(pic))
1554                         DrawQ_Pic(a->rect[0], a->rect[1], pic, a->rect[2], a->rect[3], 1, 1, 1, vid_touchscreen_overlayalpha.value * (0.5f + 0.5f * a->active), 0);
1555                 if (a->text && a->text[0])
1556                 {
1557                         int textwidth = DrawQ_TextWidth(a->text, 0, a->textheight, a->textheight, false, FONT_CHAT);
1558                         DrawQ_String(a->rect[0] + (a->rect[2] - textwidth) * 0.5f, a->rect[1] + (a->rect[3] - a->textheight) * 0.5f, a->text, 0, a->textheight, a->textheight, 1.0f, 1.0f, 1.0f, vid_touchscreen_overlayalpha.value, 0, NULL, false, FONT_CHAT);
1559                 }
1560         }
1561 }
1562
1563 void R_ClearScreen(qbool fogcolor)
1564 {
1565         float clearcolor[4];
1566         if (scr_screenshot_alpha.integer)
1567                 // clear to transparency (so png screenshots can contain alpha channel, useful for building model pictures)
1568                 Vector4Set(clearcolor, 0.0f, 0.0f, 0.0f, 0.0f);
1569         else
1570                 // clear to opaque black (if we're being composited it might otherwise render as transparent)
1571                 Vector4Set(clearcolor, 0.0f, 0.0f, 0.0f, 1.0f);
1572         if (fogcolor && r_fog_clear.integer)
1573         {
1574                 R_UpdateFog();
1575                 VectorCopy(r_refdef.fogcolor, clearcolor);
1576         }
1577         // clear depth is 1.0
1578         // clear the screen
1579         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (vid.stencil ? GL_STENCIL_BUFFER_BIT : 0), clearcolor, 1.0f, 0);
1580 }
1581
1582 int r_stereo_side;
1583 extern cvar_t v_isometric;
1584 extern cvar_t v_isometric_verticalfov;
1585
1586 typedef struct loadingscreenstack_s
1587 {
1588         struct loadingscreenstack_s *prev;
1589         char msg[MAX_QPATH];
1590         float absolute_loading_amount_min; // this corresponds to relative completion 0 of this item
1591         float absolute_loading_amount_len; // this corresponds to relative completion 1 of this item
1592         float relative_completion; // 0 .. 1
1593 }
1594 loadingscreenstack_t;
1595 static loadingscreenstack_t *loadingscreenstack = NULL;
1596 rtexture_t *loadingscreentexture = NULL; // last framebuffer before loading screen, kept for the background
1597 static float loadingscreentexture_vertex3f[12];
1598 static float loadingscreentexture_texcoord2f[8];
1599 static int loadingscreenpic_number = 0;
1600 /// User-friendly connection status for the menu and/or loading screen,
1601 /// colours and \n not supported.
1602 char cl_connect_status[MAX_QPATH]; // should match size of loadingscreenstack_t msg[]
1603
1604 static void SCR_DrawLoadingScreen(void);
1605 static void SCR_DrawScreen (void)
1606 {
1607         Draw_Frame();
1608         DrawQ_Start();
1609         R_Mesh_Start();
1610         R_UpdateVariables();
1611
1612         // Quake uses clockwise winding, so these are swapped
1613         r_refdef.view.cullface_front = GL_BACK;
1614         r_refdef.view.cullface_back = GL_FRONT;
1615
1616         if (!scr_loading && cls.signon == SIGNONS)
1617         {
1618                 float size;
1619
1620                 size = scr_viewsize.value * (1.0 / 100.0);
1621                 size = min(size, 1);
1622
1623                 if (r_stereo_sidebyside.integer)
1624                 {
1625                         r_refdef.view.width = (int)(vid.mode.width * size / 2.5);
1626                         r_refdef.view.height = (int)(vid.mode.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100));
1627                         r_refdef.view.depth = 1;
1628                         r_refdef.view.x = (int)((vid.mode.width - r_refdef.view.width * 2.5) * 0.5);
1629                         r_refdef.view.y = (int)((vid.mode.height - r_refdef.view.height)/2);
1630                         r_refdef.view.z = 0;
1631                         if (r_stereo_side)
1632                                 r_refdef.view.x += (int)(r_refdef.view.width * 1.5);
1633                 }
1634                 else if (r_stereo_horizontal.integer)
1635                 {
1636                         r_refdef.view.width = (int)(vid.mode.width * size / 2);
1637                         r_refdef.view.height = (int)(vid.mode.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1638                         r_refdef.view.depth = 1;
1639                         r_refdef.view.x = (int)((vid.mode.width - r_refdef.view.width * 2.0)/2);
1640                         r_refdef.view.y = (int)((vid.mode.height - r_refdef.view.height)/2);
1641                         r_refdef.view.z = 0;
1642                         if (r_stereo_side)
1643                                 r_refdef.view.x += (int)(r_refdef.view.width);
1644                 }
1645                 else if (r_stereo_vertical.integer)
1646                 {
1647                         r_refdef.view.width = (int)(vid.mode.width * size);
1648                         r_refdef.view.height = (int)(vid.mode.height * size * (1 - bound(0, r_letterbox.value, 100) / 100) / 2);
1649                         r_refdef.view.depth = 1;
1650                         r_refdef.view.x = (int)((vid.mode.width - r_refdef.view.width)/2);
1651                         r_refdef.view.y = (int)((vid.mode.height - r_refdef.view.height * 2.0)/2);
1652                         r_refdef.view.z = 0;
1653                         if (r_stereo_side)
1654                                 r_refdef.view.y += (int)(r_refdef.view.height);
1655                 }
1656                 else
1657                 {
1658                         r_refdef.view.width = (int)(vid.mode.width * size);
1659                         r_refdef.view.height = (int)(vid.mode.height * size * (1 - bound(0, r_letterbox.value, 100) / 100));
1660                         r_refdef.view.depth = 1;
1661                         r_refdef.view.x = (int)((vid.mode.width - r_refdef.view.width)/2);
1662                         r_refdef.view.y = (int)((vid.mode.height - r_refdef.view.height)/2);
1663                         r_refdef.view.z = 0;
1664                 }
1665
1666                 // LadyHavoc: viewzoom (zoom in for sniper rifles, etc)
1667                 // LadyHavoc: this is designed to produce widescreen fov values
1668                 // when the screen is wider than 4/3 width/height aspect, to do
1669                 // this it simply assumes the requested fov is the vertical fov
1670                 // for a 4x3 display, if the ratio is not 4x3 this makes the fov
1671                 // higher/lower according to the ratio
1672                 r_refdef.view.useperspective = true;
1673                 r_refdef.view.frustum_y = tan(scr_fov.value * M_PI / 360.0) * (3.0 / 4.0) * cl.viewzoom;
1674                 r_refdef.view.frustum_x = r_refdef.view.frustum_y * (float)r_refdef.view.width / (float)r_refdef.view.height / vid_pixelheight.value;
1675
1676                 r_refdef.view.frustum_x *= r_refdef.frustumscale_x;
1677                 r_refdef.view.frustum_y *= r_refdef.frustumscale_y;
1678                 r_refdef.view.ortho_x = atan(r_refdef.view.frustum_x) * (360.0 / M_PI); // abused as angle by VM_CL_R_SetView
1679                 r_refdef.view.ortho_y = atan(r_refdef.view.frustum_y) * (360.0 / M_PI); // abused as angle by VM_CL_R_SetView
1680
1681                 r_refdef.view.ismain = true;
1682
1683                 // if CSQC is loaded, it is required to provide the CSQC_UpdateView function,
1684                 // and won't render a view if it does not call that.
1685                 if (CLVM_prog->loaded && !(CLVM_prog->flag & PRVM_CSQC_SIMPLE))
1686                         CL_VM_UpdateView(r_stereo_side ? 0.0 : max(0.0, cl.time - cl.oldtime));
1687                 else
1688                 {
1689                         // Prepare the scene mesh for rendering - this is lightning beams and other effects rendered as normal surfaces
1690                         CL_MeshEntities_Scene_FinalizeRenderEntity();
1691
1692                         CL_UpdateEntityShading();
1693                         R_RenderView(0, NULL, NULL, r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
1694                 }
1695         }
1696
1697         // Don't apply debugging stuff like r_showsurfaces to the UI
1698         r_refdef.view.showdebug = false;
1699
1700         if (!r_stereo_sidebyside.integer && !r_stereo_horizontal.integer && !r_stereo_vertical.integer)
1701         {
1702                 r_refdef.view.width = vid.mode.width;
1703                 r_refdef.view.height = vid.mode.height;
1704                 r_refdef.view.depth = 1;
1705                 r_refdef.view.x = 0;
1706                 r_refdef.view.y = 0;
1707                 r_refdef.view.z = 0;
1708                 r_refdef.view.useperspective = false;
1709         }
1710
1711         if (cls.timedemo && cls.td_frames > 0 && timedemo_screenshotframelist.string && timedemo_screenshotframelist.string[0])
1712         {
1713                 const char *t;
1714                 int framenum;
1715                 t = timedemo_screenshotframelist.string;
1716                 while (*t)
1717                 {
1718                         while (*t == ' ')
1719                                 t++;
1720                         if (!*t)
1721                                 break;
1722                         framenum = atof(t);
1723                         if (framenum == cls.td_frames)
1724                                 break;
1725                         while (*t && *t != ' ')
1726                                 t++;
1727                 }
1728                 if (*t)
1729                 {
1730                         // we need to take a screenshot of this frame...
1731                         char filename[MAX_QPATH];
1732                         unsigned char *buffer1;
1733                         unsigned char *buffer2;
1734                         dpsnprintf(filename, sizeof(filename), "timedemoscreenshots/%s%06d.tga", cls.demoname, cls.td_frames);
1735                         buffer1 = (unsigned char *)Mem_Alloc(tempmempool, vid.mode.width * vid.mode.height * 4);
1736                         buffer2 = (unsigned char *)Mem_Alloc(tempmempool, vid.mode.width * vid.mode.height * 3);
1737                         SCR_ScreenShot(filename, buffer1, buffer2, 0, 0, vid.mode.width, vid.mode.height, false, false, false, false, false, true, false);
1738                         Mem_Free(buffer1);
1739                         Mem_Free(buffer2);
1740                 }
1741         }
1742
1743         // draw 2D stuff
1744
1745         if(!scr_con_current && !(key_consoleactive & KEY_CONSOLEACTIVE_FORCED))
1746                 if ((key_dest == key_game || key_dest == key_message) && !r_letterbox.value && !scr_loading)
1747                         Con_DrawNotify ();      // only draw notify in game
1748
1749         if (cl.islocalgame && (key_dest != key_game || key_consoleactive))
1750                 host.paused = true;
1751         else
1752                 host.paused = false;
1753
1754         if (!scr_loading && cls.signon == SIGNONS)
1755         {
1756                 SCR_DrawNet ();
1757                 SCR_DrawTurtle ();
1758                 SCR_DrawPause ();
1759                 if (!r_letterbox.value)
1760                 {
1761                         Sbar_Draw();
1762                         if (CLVM_prog->loaded && CLVM_prog->flag & PRVM_CSQC_SIMPLE)
1763                                 CL_VM_DrawHud(r_stereo_side ? 0.0 : max(0.0, cl.time - cl.oldtime));
1764                 }
1765                 SHOWLMP_drawall();
1766                 SCR_CheckDrawCenterString();
1767         }
1768         SCR_DrawNetGraph ();
1769 #ifdef CONFIG_MENU
1770         if(!scr_loading)
1771                 MR_Draw();
1772 #endif
1773         CL_DrawVideo();
1774         R_Shadow_EditLights_DrawSelectedLightProperties();
1775
1776         if (scr_loading)
1777         {
1778                 // connect_status replaces any dummy_status
1779                 if ((!loadingscreenstack || loadingscreenstack->msg[0] == '\0') && cl_connect_status[0] != '\0')
1780                 {
1781                         loadingscreenstack_t connect_status, *og_ptr = loadingscreenstack;
1782
1783                         connect_status.absolute_loading_amount_min = 0;
1784                         dp_strlcpy(connect_status.msg, cl_connect_status, sizeof(cl_connect_status));
1785                         loadingscreenstack = &connect_status;
1786                         SCR_DrawLoadingScreen();
1787                         loadingscreenstack = og_ptr;
1788                 }
1789                 else
1790                         SCR_DrawLoadingScreen();
1791         }
1792
1793         SCR_DrawConsole();
1794         SCR_DrawInfobar();
1795
1796         if (!scr_loading)
1797         {
1798                 SCR_DrawBrand();
1799                 SCR_DrawTouchscreenOverlay();
1800         }
1801         if (r_timereport_active)
1802                 R_TimeReport("2d");
1803
1804         R_TimeReport_EndFrame();
1805         R_TimeReport_BeginFrame();
1806         
1807         if(!scr_loading)
1808                 Sbar_ShowFPS();
1809
1810         R_Mesh_Finish();
1811         DrawQ_Finish();
1812         R_RenderTarget_FreeUnused(false);
1813 }
1814
1815 static void SCR_ClearLoadingScreenTexture(void)
1816 {
1817         if(loadingscreentexture)
1818                 R_FreeTexture(loadingscreentexture);
1819         loadingscreentexture = NULL;
1820 }
1821
1822 extern rtexturepool_t *r_main_texturepool;
1823 static void SCR_SetLoadingScreenTexture(void)
1824 {
1825         int w, h;
1826         float loadingscreentexture_w;
1827         float loadingscreentexture_h;
1828
1829         SCR_ClearLoadingScreenTexture();
1830
1831         w = vid.mode.width; h = vid.mode.height;
1832         loadingscreentexture_w = loadingscreentexture_h = 1;
1833
1834         loadingscreentexture = R_LoadTexture2D(r_main_texturepool, "loadingscreentexture", w, h, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
1835         R_Mesh_CopyToTexture(loadingscreentexture, 0, 0, 0, 0, vid.mode.width, vid.mode.height);
1836
1837         loadingscreentexture_vertex3f[2] = loadingscreentexture_vertex3f[5] = loadingscreentexture_vertex3f[8] = loadingscreentexture_vertex3f[11] = 0;
1838         loadingscreentexture_vertex3f[0] = loadingscreentexture_vertex3f[9] = 0;
1839         loadingscreentexture_vertex3f[1] = loadingscreentexture_vertex3f[4] = 0;
1840         loadingscreentexture_vertex3f[3] = loadingscreentexture_vertex3f[6] = vid_conwidth.integer;
1841         loadingscreentexture_vertex3f[7] = loadingscreentexture_vertex3f[10] = vid_conheight.integer;
1842         loadingscreentexture_texcoord2f[0] = 0;loadingscreentexture_texcoord2f[1] = loadingscreentexture_h;
1843         loadingscreentexture_texcoord2f[2] = loadingscreentexture_w;loadingscreentexture_texcoord2f[3] = loadingscreentexture_h;
1844         loadingscreentexture_texcoord2f[4] = loadingscreentexture_w;loadingscreentexture_texcoord2f[5] = 0;
1845         loadingscreentexture_texcoord2f[6] = 0;loadingscreentexture_texcoord2f[7] = 0;
1846 }
1847
1848 static void SCR_ChooseLoadingPic(qbool startup)
1849 {
1850         if(startup && scr_loadingscreen_firstforstartup.integer)
1851                 loadingscreenpic_number = 0;
1852         else if(scr_loadingscreen_firstforstartup.integer)
1853                 if(scr_loadingscreen_count.integer > 1)
1854                         loadingscreenpic_number = rand() % (scr_loadingscreen_count.integer - 1) + 1;
1855                 else
1856                         loadingscreenpic_number = 0;
1857         else
1858                 loadingscreenpic_number = rand() % (scr_loadingscreen_count.integer > 1 ? scr_loadingscreen_count.integer : 1);
1859 }
1860
1861 /*
1862 ===============
1863 SCR_BeginLoadingPlaque
1864
1865 ================
1866 */
1867 void SCR_BeginLoadingPlaque(qbool startup)
1868 {
1869         loadingscreenstack_t dummy_status;
1870
1871         // we need to push a dummy status so CL_UpdateScreen knows we have things to load...
1872         if (!loadingscreenstack)
1873         {
1874                 dummy_status.msg[0] = '\0';
1875                 dummy_status.absolute_loading_amount_min = 0;
1876                 loadingscreenstack = &dummy_status;
1877         }
1878
1879         SCR_DeferLoadingPlaque(startup);
1880         if (scr_loadingscreen_background.integer)
1881                 SCR_SetLoadingScreenTexture();
1882         CL_UpdateScreen();
1883
1884         if (loadingscreenstack == &dummy_status)
1885                 loadingscreenstack = NULL;
1886 }
1887
1888 void SCR_DeferLoadingPlaque(qbool startup)
1889 {
1890         SCR_ChooseLoadingPic(startup);
1891         scr_loading = true;
1892 }
1893
1894 void SCR_EndLoadingPlaque(void)
1895 {
1896         scr_loading = false;
1897         SCR_ClearLoadingScreenTexture();
1898 }
1899
1900 //=============================================================================
1901
1902 void SCR_PushLoadingScreen (const char *msg, float len_in_parent)
1903 {
1904         loadingscreenstack_t *s = (loadingscreenstack_t *) Z_Malloc(sizeof(loadingscreenstack_t));
1905         s->prev = loadingscreenstack;
1906         loadingscreenstack = s;
1907
1908         dp_strlcpy(s->msg, msg, sizeof(s->msg));
1909         s->relative_completion = 0;
1910
1911         if(s->prev)
1912         {
1913                 s->absolute_loading_amount_min = s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len * s->prev->relative_completion;
1914                 s->absolute_loading_amount_len = s->prev->absolute_loading_amount_len * len_in_parent;
1915                 if(s->absolute_loading_amount_len > s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len - s->absolute_loading_amount_min)
1916                         s->absolute_loading_amount_len = s->prev->absolute_loading_amount_min + s->prev->absolute_loading_amount_len - s->absolute_loading_amount_min;
1917         }
1918         else
1919         {
1920                 s->absolute_loading_amount_min = 0;
1921                 s->absolute_loading_amount_len = 1;
1922         }
1923
1924         if (scr_loading)
1925                 CL_UpdateScreen();
1926 }
1927
1928 void SCR_PopLoadingScreen (qbool redraw)
1929 {
1930         loadingscreenstack_t *s = loadingscreenstack;
1931
1932         if(!s)
1933         {
1934                 Con_DPrintf("Popping a loading screen item from an empty stack!\n");
1935                 return;
1936         }
1937
1938         loadingscreenstack = s->prev;
1939         if(s->prev)
1940                 s->prev->relative_completion = (s->absolute_loading_amount_min + s->absolute_loading_amount_len - s->prev->absolute_loading_amount_min) / s->prev->absolute_loading_amount_len;
1941         Z_Free(s);
1942
1943         if (scr_loading && redraw)
1944                 CL_UpdateScreen();
1945 }
1946
1947 void SCR_ClearLoadingScreen (qbool redraw)
1948 {
1949         while(loadingscreenstack)
1950                 SCR_PopLoadingScreen(redraw && !loadingscreenstack->prev);
1951 }
1952
1953 static float SCR_DrawLoadingStack_r(loadingscreenstack_t *s, float y, float size)
1954 {
1955         float x;
1956         size_t len;
1957         float total;
1958
1959         total = 0;
1960 #if 0
1961         if(s)
1962         {
1963                 total += SCR_DrawLoadingStack_r(s->prev, y, 8);
1964                 y -= total;
1965                 if(!s->prev || strcmp(s->msg, s->prev->msg))
1966                 {
1967                         len = strlen(s->msg);
1968                         x = (vid_conwidth.integer - DrawQ_TextWidth(s->msg, len, size, size, true, FONT_INFOBAR)) / 2;
1969                         y -= size;
1970                         DrawQ_String(x, y, s->msg, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
1971                         total += size;
1972                 }
1973         }
1974 #else
1975         if(s)
1976         {
1977                 len = strlen(s->msg);
1978                 x = (vid_conwidth.integer - DrawQ_TextWidth(s->msg, len, size, size, true, FONT_INFOBAR)) / 2;
1979                 y -= size;
1980                 DrawQ_String(x, y, s->msg, len, size, size, 1, 1, 1, 1, 0, NULL, true, FONT_INFOBAR);
1981                 total += size;
1982         }
1983 #endif
1984         return total;
1985 }
1986
1987 static void SCR_DrawLoadingStack(void)
1988 {
1989         float verts[12];
1990         float colors[16];
1991
1992         SCR_DrawLoadingStack_r(loadingscreenstack, vid_conheight.integer, scr_loadingscreen_barheight.value);
1993         if(loadingscreenstack)
1994         {
1995                 // height = 32; // sorry, using the actual one is ugly
1996                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1997                 GL_DepthRange(0, 1);
1998                 GL_PolygonOffset(0, 0);
1999                 GL_DepthTest(false);
2000                 //R_Mesh_ResetTextureState();
2001                 verts[2] = verts[5] = verts[8] = verts[11] = 0;
2002                 verts[0] = verts[9] = 0;
2003                 verts[1] = verts[4] = vid_conheight.integer - scr_loadingscreen_barheight.value;
2004                 verts[3] = verts[6] = vid_conwidth.integer * loadingscreenstack->absolute_loading_amount_min;
2005                 verts[7] = verts[10] = vid_conheight.integer;
2006                 
2007 #if _MSC_VER >= 1400
2008 #define sscanf sscanf_s
2009 #endif
2010                 colors[0] = 0; colors[1] = 0; colors[2] = 0; colors[3] = 1;
2011                 colors[4] = 0; colors[5] = 0; colors[6] = 0; colors[7] = 1;
2012                 sscanf(scr_loadingscreen_barcolor.string, "%f %f %f", &colors[8], &colors[9], &colors[10]); colors[11] = 1;
2013                 sscanf(scr_loadingscreen_barcolor.string, "%f %f %f", &colors[12], &colors[13], &colors[14]);  colors[15] = 1;
2014
2015                 R_Mesh_PrepareVertices_Generic_Arrays(4, verts, colors, NULL);
2016                 R_SetupShader_Generic_NoTexture(true, true);
2017                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
2018         }
2019 }
2020
2021 static void SCR_DrawLoadingScreen (void)
2022 {
2023         cachepic_t *loadingscreenpic;
2024         float loadingscreenpic_vertex3f[12];
2025         float loadingscreenpic_texcoord2f[8];
2026         float x, y, w, h, sw, sh, f;
2027         char vabuf[1024];
2028
2029         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2030         GL_DepthRange(0, 1);
2031         GL_PolygonOffset(0, 0);
2032         GL_DepthTest(false);
2033         GL_Color(1,1,1,1);
2034
2035         if(loadingscreentexture)
2036         {
2037                 R_Mesh_PrepareVertices_Generic_Arrays(4, loadingscreentexture_vertex3f, NULL, loadingscreentexture_texcoord2f);
2038                 R_SetupShader_Generic(loadingscreentexture, false, true, true);
2039                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
2040         }
2041
2042         loadingscreenpic = Draw_CachePic_Flags(loadingscreenpic_number ? va(vabuf, sizeof(vabuf), "%s%d", scr_loadingscreen_picture.string, loadingscreenpic_number+1) : scr_loadingscreen_picture.string, loadingscreenpic_number ? CACHEPICFLAG_NOTPERSISTENT : 0);
2043         w = Draw_GetPicWidth(loadingscreenpic);
2044         h = Draw_GetPicHeight(loadingscreenpic);
2045
2046         // apply scale
2047         w *= scr_loadingscreen_scale.value;
2048         h *= scr_loadingscreen_scale.value;
2049
2050         // apply scale base
2051         if(scr_loadingscreen_scale_base.integer)
2052         {
2053                 w *= vid_conwidth.integer / (float) vid.mode.width;
2054                 h *= vid_conheight.integer / (float) vid.mode.height;
2055         }
2056
2057         // apply scale limit
2058         sw = w / vid_conwidth.integer;
2059         sh = h / vid_conheight.integer;
2060         f = 1;
2061         switch(scr_loadingscreen_scale_limit.integer)
2062         {
2063                 case 1:
2064                         f = max(sw, sh);
2065                         break;
2066                 case 2:
2067                         f = min(sw, sh);
2068                         break;
2069                 case 3:
2070                         f = sw;
2071                         break;
2072                 case 4:
2073                         f = sh;
2074                         break;
2075         }
2076         if(f > 1)
2077         {
2078                 w /= f;
2079                 h /= f;
2080         }
2081
2082         x = (vid_conwidth.integer - w)/2;
2083         y = (vid_conheight.integer - h)/2;
2084         loadingscreenpic_vertex3f[2] = loadingscreenpic_vertex3f[5] = loadingscreenpic_vertex3f[8] = loadingscreenpic_vertex3f[11] = 0;
2085         loadingscreenpic_vertex3f[0] = loadingscreenpic_vertex3f[9] = x;
2086         loadingscreenpic_vertex3f[1] = loadingscreenpic_vertex3f[4] = y;
2087         loadingscreenpic_vertex3f[3] = loadingscreenpic_vertex3f[6] = x + w;
2088         loadingscreenpic_vertex3f[7] = loadingscreenpic_vertex3f[10] = y + h;
2089         loadingscreenpic_texcoord2f[0] = 0;loadingscreenpic_texcoord2f[1] = 0;
2090         loadingscreenpic_texcoord2f[2] = 1;loadingscreenpic_texcoord2f[3] = 0;
2091         loadingscreenpic_texcoord2f[4] = 1;loadingscreenpic_texcoord2f[5] = 1;
2092         loadingscreenpic_texcoord2f[6] = 0;loadingscreenpic_texcoord2f[7] = 1;
2093
2094         R_Mesh_PrepareVertices_Generic_Arrays(4, loadingscreenpic_vertex3f, NULL, loadingscreenpic_texcoord2f);
2095         R_SetupShader_Generic(Draw_GetPicTexture(loadingscreenpic), true, true, false);
2096         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
2097
2098         SCR_DrawLoadingStack();
2099 }
2100
2101 qbool R_Stereo_ColorMasking(void)
2102 {
2103         return r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer;
2104 }
2105
2106 qbool R_Stereo_Active(void)
2107 {
2108         return (vid.mode.stereobuffer || r_stereo_sidebyside.integer || r_stereo_horizontal.integer || r_stereo_vertical.integer || R_Stereo_ColorMasking());
2109 }
2110
2111 static void SCR_UpdateVars(void)
2112 {
2113         float conwidth = bound(160, vid_conwidth.value, 32768);
2114         float conheight = bound(90, vid_conheight.value, 24576);
2115         if (vid_conwidthauto.integer)
2116                 conwidth = floor(conheight * vid.mode.width / (vid.mode.height * vid_pixelheight.value));
2117         if (vid_conwidth.value != conwidth)
2118                 Cvar_SetValueQuick(&vid_conwidth, conwidth);
2119         if (vid_conheight.value != conheight)
2120                 Cvar_SetValueQuick(&vid_conheight, conheight);
2121
2122         // bound viewsize
2123         if (scr_viewsize.value < 30)
2124                 Cvar_SetValueQuick(&scr_viewsize, 30);
2125         if (scr_viewsize.value > 120)
2126                 Cvar_SetValueQuick(&scr_viewsize, 120);
2127
2128         // bound field of view
2129         if (scr_fov.value < 1)
2130                 Cvar_SetValueQuick(&scr_fov, 1);
2131         if (scr_fov.value > 170)
2132                 Cvar_SetValueQuick(&scr_fov, 170);
2133
2134         // intermission is always full screen
2135         if (cl.intermission)
2136                 sb_lines = 0;
2137         else
2138         {
2139                 if (scr_viewsize.value >= 120)
2140                         sb_lines = 0;           // no status bar at all
2141                 else if (scr_viewsize.value >= 110)
2142                         sb_lines = 24;          // no inventory
2143                 else
2144                         sb_lines = 24 + 16 + 8;
2145         }
2146 }
2147
2148 extern cvar_t cl_minfps;
2149 extern cvar_t cl_minfps_fade;
2150 extern cvar_t cl_minfps_qualitymax;
2151 extern cvar_t cl_minfps_qualitymin;
2152 extern cvar_t cl_minfps_qualitymultiply;
2153 extern cvar_t cl_minfps_qualityhysteresis;
2154 extern cvar_t cl_minfps_qualitystepmax;
2155 extern cvar_t cl_minfps_force;
2156 void CL_UpdateScreen(void)
2157 {
2158         static double cl_updatescreen_quality = 1;
2159
2160         vec3_t vieworigin;
2161         static double drawscreenstart = 0.0;
2162         double drawscreendelta;
2163         r_viewport_t viewport;
2164
2165         // TODO: Move to a better place.
2166         cl_punchangle_applied = 0;
2167
2168         if(drawscreenstart)
2169         {
2170                 drawscreendelta = Sys_DirtyTime() - drawscreenstart;
2171 #ifdef CONFIG_VIDEO_CAPTURE
2172                 if (cl_minfps.value > 0 && (cl_minfps_force.integer || !(cls.timedemo || (cls.capturevideo.active && !cls.capturevideo.realtime))) && drawscreendelta >= 0 && drawscreendelta < 60)
2173 #else
2174                 if (cl_minfps.value > 0 && (cl_minfps_force.integer || !cls.timedemo) && drawscreendelta >= 0 && drawscreendelta < 60)
2175 #endif
2176                 {
2177                         // quality adjustment according to render time
2178                         double actualframetime;
2179                         double targetframetime;
2180                         double adjust;
2181                         double f;
2182                         double h;
2183
2184                         // fade lastdrawscreentime
2185                         r_refdef.lastdrawscreentime += (drawscreendelta - r_refdef.lastdrawscreentime) * cl_minfps_fade.value;
2186
2187                         // find actual and target frame times
2188                         actualframetime = r_refdef.lastdrawscreentime;
2189                         targetframetime = (1.0 / cl_minfps.value);
2190
2191                         // we scale hysteresis by quality
2192                         h = cl_updatescreen_quality * cl_minfps_qualityhysteresis.value;
2193
2194                         // calculate adjustment assuming linearity
2195                         f = cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value;
2196                         adjust = (targetframetime - actualframetime) * f;
2197
2198                         // one sided hysteresis
2199                         if(adjust > 0)
2200                                 adjust = max(0, adjust - h);
2201
2202                         // adjust > 0 if:
2203                         //   (targetframetime - actualframetime) * f > h
2204                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value) > (cl_updatescreen_quality * cl_minfps_qualityhysteresis.value)
2205                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_minfps_qualitymultiply.value / actualframetime) > cl_minfps_qualityhysteresis.value
2206                         //   (1.0 / cl_minfps.value) * (cl_minfps_qualitymultiply.value / actualframetime) - cl_minfps_qualitymultiply.value > cl_minfps_qualityhysteresis.value
2207                         //   (1.0 / cl_minfps.value) * (cl_minfps_qualitymultiply.value / actualframetime) > cl_minfps_qualityhysteresis.value + cl_minfps_qualitymultiply.value
2208                         //   (1.0 / cl_minfps.value) / actualframetime > (cl_minfps_qualityhysteresis.value + cl_minfps_qualitymultiply.value) / cl_minfps_qualitymultiply.value
2209                         //   (1.0 / cl_minfps.value) / actualframetime > 1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value
2210                         //   cl_minfps.value * actualframetime < 1.0 / (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2211                         //   actualframetime < 1.0 / cl_minfps.value / (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2212                         //   actualfps > cl_minfps.value * (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value)
2213
2214                         // adjust < 0 if:
2215                         //   (targetframetime - actualframetime) * f < 0
2216                         //   ((1.0 / cl_minfps.value) - actualframetime) * (cl_updatescreen_quality / actualframetime * cl_minfps_qualitymultiply.value) < 0
2217                         //   ((1.0 / cl_minfps.value) - actualframetime) < 0
2218                         //   -actualframetime) < -(1.0 / cl_minfps.value)
2219                         //   actualfps < cl_minfps.value
2220
2221                         /*
2222                         Con_Printf("adjust UP if fps > %f, adjust DOWN if fps < %f\n",
2223                                         cl_minfps.value * (1.0 + cl_minfps_qualityhysteresis.value / cl_minfps_qualitymultiply.value),
2224                                         cl_minfps.value);
2225                         */
2226
2227                         // don't adjust too much at once
2228                         adjust = bound(-cl_minfps_qualitystepmax.value, adjust, cl_minfps_qualitystepmax.value);
2229
2230                         // adjust!
2231                         cl_updatescreen_quality += adjust;
2232                         cl_updatescreen_quality = bound(max(0.01, cl_minfps_qualitymin.value), cl_updatescreen_quality, cl_minfps_qualitymax.value);
2233                 }
2234                 else
2235                 {
2236                         cl_updatescreen_quality = 1;
2237                         r_refdef.lastdrawscreentime = 0;
2238                 }
2239         }
2240
2241         drawscreenstart = Sys_DirtyTime();
2242
2243         Sbar_ShowFPS_Update();
2244
2245         if (!scr_initialized || !con_initialized || !scr_refresh.integer)
2246                 return;                         // not initialized yet
2247
2248         if(IS_NEXUIZ_DERIVED(gamemode))
2249         {
2250                 // play a bit with the palette (experimental)
2251                 palette_rgb_pantscolormap[15][0] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 0.0f*M_PI/3.0f));
2252                 palette_rgb_pantscolormap[15][1] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 2.0f*M_PI/3.0f));
2253                 palette_rgb_pantscolormap[15][2] = (unsigned char) (128 + 127 * sin(cl.time / exp(1.0f) + 4.0f*M_PI/3.0f));
2254                 palette_rgb_shirtcolormap[15][0] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 5.0f*M_PI/3.0f));
2255                 palette_rgb_shirtcolormap[15][1] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 3.0f*M_PI/3.0f));
2256                 palette_rgb_shirtcolormap[15][2] = (unsigned char) (128 + 127 * sin(cl.time /  M_PI  + 1.0f*M_PI/3.0f));
2257                 memcpy(palette_rgb_pantsscoreboard[15], palette_rgb_pantscolormap[15], sizeof(*palette_rgb_pantscolormap));
2258                 memcpy(palette_rgb_shirtscoreboard[15], palette_rgb_shirtcolormap[15], sizeof(*palette_rgb_shirtcolormap));
2259         }
2260
2261 #ifdef CONFIG_VIDEO_CAPTURE
2262         if (vid_hidden && !cls.capturevideo.active && !cl_capturevideo.integer)
2263 #else
2264         if (vid_hidden)
2265 #endif
2266         {
2267                 VID_Finish();
2268                 return;
2269         }
2270
2271         if (scr_loading)
2272         {
2273                 if(!loadingscreenstack && !cls.connect_trying && (cls.state != ca_connected || cls.signon == SIGNONS))
2274                         SCR_EndLoadingPlaque();
2275                 else if (scr_loadingscreen_maxfps.value > 0)
2276                 {
2277                         static float lastupdate;
2278                         float now = Sys_DirtyTime();
2279                         if (now - lastupdate < min(1.0f / scr_loadingscreen_maxfps.value, 0.1))
2280                                 return;
2281                         lastupdate = now;
2282                 }
2283         }
2284
2285         SCR_UpdateVars();
2286
2287         R_FrameData_NewFrame();
2288         R_BufferData_NewFrame();
2289
2290         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, vieworigin);
2291         R_HDR_UpdateIrisAdaptation(vieworigin);
2292
2293         r_refdef.view.colormask[0] = 1;
2294         r_refdef.view.colormask[1] = 1;
2295         r_refdef.view.colormask[2] = 1;
2296
2297         SCR_SetUpToDrawConsole();
2298
2299 #ifndef USE_GLES2
2300         CHECKGLERROR
2301         qglDrawBuffer(GL_BACK);CHECKGLERROR
2302 #endif
2303
2304         R_Viewport_InitOrtho(&viewport, &identitymatrix, 0, 0, vid.mode.width, vid.mode.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
2305         R_Mesh_SetRenderTargets(0, NULL, NULL, NULL, NULL, NULL);
2306         R_SetViewport(&viewport);
2307         GL_ScissorTest(false);
2308         GL_ColorMask(1,1,1,1);
2309         GL_DepthMask(true);
2310
2311         R_ClearScreen(false);
2312         r_refdef.view.clear = false;
2313         r_refdef.view.isoverlay = false;
2314
2315         // calculate r_refdef.view.quality
2316         r_refdef.view.quality = cl_updatescreen_quality;
2317
2318         if(scr_stipple.integer)
2319         {
2320                 Con_Print("FIXME: scr_stipple not implemented\n");
2321                 Cvar_SetValueQuick(&scr_stipple, 0);
2322         }
2323
2324 #ifndef USE_GLES2
2325         if (R_Stereo_Active())
2326         {
2327                 r_stereo_side = 0;
2328
2329                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2330                 {
2331                         r_refdef.view.colormask[0] = 1;
2332                         r_refdef.view.colormask[1] = 0;
2333                         r_refdef.view.colormask[2] = 0;
2334                 }
2335
2336                 if (vid.mode.stereobuffer)
2337                         qglDrawBuffer(GL_BACK_RIGHT);
2338
2339                 SCR_DrawScreen();
2340
2341                 r_stereo_side = 1;
2342                 r_refdef.view.clear = true;
2343
2344                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
2345                 {
2346                         r_refdef.view.colormask[0] = 0;
2347                         r_refdef.view.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
2348                         r_refdef.view.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
2349                 }
2350
2351                 if (vid.mode.stereobuffer)
2352                         qglDrawBuffer(GL_BACK_LEFT);
2353
2354                 SCR_DrawScreen();
2355                 r_stereo_side = 0;
2356         }
2357         else
2358 #endif
2359         {
2360                 r_stereo_side = 0;
2361                 SCR_DrawScreen();
2362         }
2363
2364 #ifdef CONFIG_VIDEO_CAPTURE
2365         SCR_CaptureVideo();
2366 #endif
2367
2368         qglFlush(); // ensure that the commands are submitted to the GPU before we do other things
2369         VID_Finish();
2370 }
2371
2372 void CL_Screen_NewMap(void)
2373 {
2374 }