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