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