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