]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rmain.c
use cl.worldmodel in r_editlights_reload code as it is invoked from the
[divverent/darkplaces.git] / gl_rmain.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_main.c
21
22 #include "quakedef.h"
23 #include "cl_dyntexture.h"
24 #include "r_shadow.h"
25 #include "polygon.h"
26 #include "image.h"
27
28 mempool_t *r_main_mempool;
29 rtexturepool_t *r_main_texturepool;
30
31 //
32 // screen size info
33 //
34 r_refdef_t r_refdef;
35
36 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "1", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
37 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
38 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
39 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
40 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
41 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
42 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
43 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
44 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
45 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
46 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
47 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
48 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
49 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
50 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
51 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
52 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
53 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
54 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
55 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
56 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
57 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
58 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
59 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
60 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this)"};
61 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
62 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
63 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
64 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "2", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
65 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
66
67 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
68 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
69 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
70 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
71 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
72 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
73 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
74 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
75
76 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of hardware texture units reported by driver (note: setting this to 1 turns off gl_combine)"};
77
78 cvar_t r_glsl = {CVAR_SAVE, "r_glsl", "1", "enables use of OpenGL 2.0 pixel shaders for lighting"};
79 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
80 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
81 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
82 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
83 cvar_t r_glsl_contrastboost = {CVAR_SAVE, "r_glsl_contrastboost", "1", "by how much to multiply the contrast in dark areas (1 is no change)"};
84
85 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
86 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
87 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
88 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
89 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
90
91 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites (requires r_lerpmodels 1)"};
92 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
93 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
94 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
95
96 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
97 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
98 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
99 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
100 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
101 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
102 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
103
104 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
105 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
106 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
107 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
108
109 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
110
111 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
112
113 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
114
115 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
116 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
117 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
118 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
119 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
120 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
121
122 extern qboolean v_flipped_state;
123
124 typedef struct r_glsl_bloomshader_s
125 {
126         int program;
127         int loc_Texture_Bloom;
128 }
129 r_glsl_bloomshader_t;
130
131 static struct r_bloomstate_s
132 {
133         qboolean enabled;
134         qboolean hdr;
135
136         int bloomwidth, bloomheight;
137
138         int screentexturewidth, screentextureheight;
139         rtexture_t *texture_screen;
140
141         int bloomtexturewidth, bloomtextureheight;
142         rtexture_t *texture_bloom;
143
144         r_glsl_bloomshader_t *shader;
145
146         // arrays for rendering the screen passes
147         float screentexcoord2f[8];
148         float bloomtexcoord2f[8];
149         float offsettexcoord2f[8];
150 }
151 r_bloomstate;
152
153 typedef struct r_waterstate_waterplane_s
154 {
155         rtexture_t *texture_refraction;
156         rtexture_t *texture_reflection;
157         mplane_t plane;
158         int materialflags; // combined flags of all water surfaces on this plane
159         unsigned char pvsbits[(32768+7)>>3]; // FIXME: buffer overflow on huge maps
160         qboolean pvsvalid;
161 }
162 r_waterstate_waterplane_t;
163
164 #define MAX_WATERPLANES 16
165
166 static struct r_waterstate_s
167 {
168         qboolean enabled;
169
170         qboolean renderingscene; // true while rendering a refraction or reflection texture, disables water surfaces
171
172         int waterwidth, waterheight;
173         int texturewidth, textureheight;
174
175         int maxwaterplanes; // same as MAX_WATERPLANES
176         int numwaterplanes;
177         r_waterstate_waterplane_t waterplanes[MAX_WATERPLANES];
178
179         float screenscale[2];
180         float screencenter[2];
181 }
182 r_waterstate;
183
184 // shadow volume bsp struct with automatically growing nodes buffer
185 svbsp_t r_svbsp;
186
187 rtexture_t *r_texture_blanknormalmap;
188 rtexture_t *r_texture_white;
189 rtexture_t *r_texture_grey128;
190 rtexture_t *r_texture_black;
191 rtexture_t *r_texture_notexture;
192 rtexture_t *r_texture_whitecube;
193 rtexture_t *r_texture_normalizationcube;
194 rtexture_t *r_texture_fogattenuation;
195 //rtexture_t *r_texture_fogintensity;
196
197 char r_qwskincache[MAX_SCOREBOARD][MAX_QPATH];
198 skinframe_t *r_qwskincache_skinframe[MAX_SCOREBOARD];
199
200 // vertex coordinates for a quad that covers the screen exactly
201 const static float r_screenvertex3f[12] =
202 {
203         0, 0, 0,
204         1, 0, 0,
205         1, 1, 0,
206         0, 1, 0
207 };
208
209 extern void R_DrawModelShadows(void);
210
211 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
212 {
213         int i;
214         for (i = 0;i < verts;i++)
215         {
216                 out[0] = in[0] * r;
217                 out[1] = in[1] * g;
218                 out[2] = in[2] * b;
219                 out[3] = in[3];
220                 in += 4;
221                 out += 4;
222         }
223 }
224
225 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
226 {
227         int i;
228         for (i = 0;i < verts;i++)
229         {
230                 out[0] = r;
231                 out[1] = g;
232                 out[2] = b;
233                 out[3] = a;
234                 out += 4;
235         }
236 }
237
238 // FIXME: move this to client?
239 void FOG_clear(void)
240 {
241         if (gamemode == GAME_NEHAHRA)
242         {
243                 Cvar_Set("gl_fogenable", "0");
244                 Cvar_Set("gl_fogdensity", "0.2");
245                 Cvar_Set("gl_fogred", "0.3");
246                 Cvar_Set("gl_foggreen", "0.3");
247                 Cvar_Set("gl_fogblue", "0.3");
248         }
249         r_refdef.fog_density = 0;
250         r_refdef.fog_red = 0;
251         r_refdef.fog_green = 0;
252         r_refdef.fog_blue = 0;
253         r_refdef.fog_alpha = 1;
254         r_refdef.fog_start = 0;
255         r_refdef.fog_end = 0;
256 }
257
258 float FogForDistance(vec_t dist)
259 {
260         unsigned int fogmasktableindex = (unsigned int)(dist * r_refdef.fogmasktabledistmultiplier);
261         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
262 }
263
264 float FogPoint_World(const vec3_t p)
265 {
266         return FogForDistance(VectorDistance((p), r_refdef.view.origin));
267 }
268
269 float FogPoint_Model(const vec3_t p)
270 {
271         return FogForDistance(VectorDistance((p), rsurface.modelorg));
272 }
273
274 static void R_BuildBlankTextures(void)
275 {
276         unsigned char data[4];
277         data[2] = 128; // normal X
278         data[1] = 128; // normal Y
279         data[0] = 255; // normal Z
280         data[3] = 128; // height
281         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
282         data[0] = 255;
283         data[1] = 255;
284         data[2] = 255;
285         data[3] = 255;
286         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
287         data[0] = 128;
288         data[1] = 128;
289         data[2] = 128;
290         data[3] = 255;
291         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
292         data[0] = 0;
293         data[1] = 0;
294         data[2] = 0;
295         data[3] = 255;
296         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
297 }
298
299 static void R_BuildNoTexture(void)
300 {
301         int x, y;
302         unsigned char pix[16][16][4];
303         // this makes a light grey/dark grey checkerboard texture
304         for (y = 0;y < 16;y++)
305         {
306                 for (x = 0;x < 16;x++)
307                 {
308                         if ((y < 8) ^ (x < 8))
309                         {
310                                 pix[y][x][0] = 128;
311                                 pix[y][x][1] = 128;
312                                 pix[y][x][2] = 128;
313                                 pix[y][x][3] = 255;
314                         }
315                         else
316                         {
317                                 pix[y][x][0] = 64;
318                                 pix[y][x][1] = 64;
319                                 pix[y][x][2] = 64;
320                                 pix[y][x][3] = 255;
321                         }
322                 }
323         }
324         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
325 }
326
327 static void R_BuildWhiteCube(void)
328 {
329         unsigned char data[6*1*1*4];
330         memset(data, 255, sizeof(data));
331         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
332 }
333
334 static void R_BuildNormalizationCube(void)
335 {
336         int x, y, side;
337         vec3_t v;
338         vec_t s, t, intensity;
339 #define NORMSIZE 64
340         unsigned char data[6][NORMSIZE][NORMSIZE][4];
341         for (side = 0;side < 6;side++)
342         {
343                 for (y = 0;y < NORMSIZE;y++)
344                 {
345                         for (x = 0;x < NORMSIZE;x++)
346                         {
347                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
348                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
349                                 switch(side)
350                                 {
351                                 default:
352                                 case 0:
353                                         v[0] = 1;
354                                         v[1] = -t;
355                                         v[2] = -s;
356                                         break;
357                                 case 1:
358                                         v[0] = -1;
359                                         v[1] = -t;
360                                         v[2] = s;
361                                         break;
362                                 case 2:
363                                         v[0] = s;
364                                         v[1] = 1;
365                                         v[2] = t;
366                                         break;
367                                 case 3:
368                                         v[0] = s;
369                                         v[1] = -1;
370                                         v[2] = -t;
371                                         break;
372                                 case 4:
373                                         v[0] = s;
374                                         v[1] = -t;
375                                         v[2] = 1;
376                                         break;
377                                 case 5:
378                                         v[0] = -s;
379                                         v[1] = -t;
380                                         v[2] = -1;
381                                         break;
382                                 }
383                                 intensity = 127.0f / sqrt(DotProduct(v, v));
384                                 data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[0]);
385                                 data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
386                                 data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[2]);
387                                 data[side][y][x][3] = 255;
388                         }
389                 }
390         }
391         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
392 }
393
394 static void R_BuildFogTexture(void)
395 {
396         int x, b;
397 #define FOGWIDTH 256
398         unsigned char data1[FOGWIDTH][4];
399         //unsigned char data2[FOGWIDTH][4];
400         double d, r, alpha;
401
402         r_refdef.fogmasktable_start = r_refdef.fog_start;
403         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
404         r_refdef.fogmasktable_range = r_refdef.fogrange;
405         r_refdef.fogmasktable_density = r_refdef.fog_density;
406
407         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
408         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
409         {
410                 d = (x * r - r_refdef.fogmasktable_start);
411                 if(developer.integer >= 100)
412                         Con_Printf("%f ", d);
413                 d = max(0, d);
414                 if (r_fog_exp2.integer)
415                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
416                 else
417                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
418                 if(developer.integer >= 100)
419                         Con_Printf(" : %f ", alpha);
420                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
421                 if(developer.integer >= 100)
422                         Con_Printf(" = %f\n", alpha);
423                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
424         }
425
426         for (x = 0;x < FOGWIDTH;x++)
427         {
428                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
429                 data1[x][0] = b;
430                 data1[x][1] = b;
431                 data1[x][2] = b;
432                 data1[x][3] = 255;
433                 //data2[x][0] = 255 - b;
434                 //data2[x][1] = 255 - b;
435                 //data2[x][2] = 255 - b;
436                 //data2[x][3] = 255;
437         }
438         if (r_texture_fogattenuation)
439         {
440                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
441                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
442         }
443         else
444         {
445                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
446                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
447         }
448 }
449
450 static const char *builtinshaderstring =
451 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
452 "// written by Forest 'LordHavoc' Hale\n"
453 "\n"
454 "// common definitions between vertex shader and fragment shader:\n"
455 "\n"
456 "#ifdef __GLSL_CG_DATA_TYPES\n"
457 "# define myhalf half\n"
458 "# define myhalf2 half2\n"
459 "# define myhalf3 half3\n"
460 "# define myhalf4 half4\n"
461 "#else\n"
462 "# define myhalf float\n"
463 "# define myhalf2 vec2\n"
464 "# define myhalf3 vec3\n"
465 "# define myhalf4 vec4\n"
466 "#endif\n"
467 "\n"
468 "varying vec2 TexCoord;\n"
469 "varying vec2 TexCoordLightmap;\n"
470 "\n"
471 "//#ifdef MODE_LIGHTSOURCE\n"
472 "varying vec3 CubeVector;\n"
473 "//#endif\n"
474 "\n"
475 "//#ifdef MODE_LIGHTSOURCE\n"
476 "varying vec3 LightVector;\n"
477 "//#else\n"
478 "//# ifdef MODE_LIGHTDIRECTION\n"
479 "//varying vec3 LightVector;\n"
480 "//# endif\n"
481 "//#endif\n"
482 "\n"
483 "varying vec3 EyeVector;\n"
484 "//#ifdef USEFOG\n"
485 "varying vec3 EyeVectorModelSpace;\n"
486 "//#endif\n"
487 "\n"
488 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
489 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
490 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
491 "\n"
492 "//#ifdef MODE_WATER\n"
493 "varying vec4 ModelViewProjectionPosition;\n"
494 "//#else\n"
495 "//# ifdef MODE_REFRACTION\n"
496 "//varying vec4 ModelViewProjectionPosition;\n"
497 "//# else\n"
498 "//#  ifdef USEREFLECTION\n"
499 "//varying vec4 ModelViewProjectionPosition;\n"
500 "//#  endif\n"
501 "//# endif\n"
502 "//#endif\n"
503 "\n"
504 "\n"
505 "\n"
506 "\n"
507 "\n"
508 "// vertex shader specific:\n"
509 "#ifdef VERTEX_SHADER\n"
510 "\n"
511 "uniform vec3 LightPosition;\n"
512 "uniform vec3 EyePosition;\n"
513 "uniform vec3 LightDir;\n"
514 "\n"
515 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3)\n"
516 "\n"
517 "void main(void)\n"
518 "{\n"
519 "       gl_FrontColor = gl_Color;\n"
520 "       // copy the surface texcoord\n"
521 "       TexCoord = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);\n"
522 "#ifndef MODE_LIGHTSOURCE\n"
523 "# ifndef MODE_LIGHTDIRECTION\n"
524 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
525 "# endif\n"
526 "#endif\n"
527 "\n"
528 "#ifdef MODE_LIGHTSOURCE\n"
529 "       // transform vertex position into light attenuation/cubemap space\n"
530 "       // (-1 to +1 across the light box)\n"
531 "       CubeVector = vec3(gl_TextureMatrix[3] * gl_Vertex);\n"
532 "\n"
533 "       // transform unnormalized light direction into tangent space\n"
534 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
535 "       //  normalize it per pixel)\n"
536 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
537 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
538 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
539 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
540 "#endif\n"
541 "\n"
542 "#ifdef MODE_LIGHTDIRECTION\n"
543 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
544 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
545 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
546 "#endif\n"
547 "\n"
548 "       // transform unnormalized eye direction into tangent space\n"
549 "#ifndef USEFOG\n"
550 "       vec3 EyeVectorModelSpace;\n"
551 "#endif\n"
552 "       EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
553 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
554 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
555 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
556 "\n"
557 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
558 "       VectorS = gl_MultiTexCoord1.xyz;\n"
559 "       VectorT = gl_MultiTexCoord2.xyz;\n"
560 "       VectorR = gl_MultiTexCoord3.xyz;\n"
561 "#endif\n"
562 "\n"
563 "//#if defined(MODE_WATER) || defined(MODE_REFRACTION) || defined(USEREFLECTION)\n"
564 "//     ModelViewProjectionPosition = gl_Vertex * gl_ModelViewProjectionMatrix;\n"
565 "//     //ModelViewProjectionPosition_svector = (gl_Vertex + vec4(gl_MultiTexCoord1.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
566 "//     //ModelViewProjectionPosition_tvector = (gl_Vertex + vec4(gl_MultiTexCoord2.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
567 "//#endif\n"
568 "\n"
569 "// transform vertex to camera space, using ftransform to match non-VS\n"
570 "       // rendering\n"
571 "       gl_Position = ftransform();\n"
572 "\n"
573 "#ifdef MODE_WATER\n"
574 "       ModelViewProjectionPosition = gl_Position;\n"
575 "#endif\n"
576 "#ifdef MODE_REFRACTION\n"
577 "       ModelViewProjectionPosition = gl_Position;\n"
578 "#endif\n"
579 "#ifdef USEREFLECTION\n"
580 "       ModelViewProjectionPosition = gl_Position;\n"
581 "#endif\n"
582 "}\n"
583 "\n"
584 "#endif // VERTEX_SHADER\n"
585 "\n"
586 "\n"
587 "\n"
588 "\n"
589 "// fragment shader specific:\n"
590 "#ifdef FRAGMENT_SHADER\n"
591 "\n"
592 "// 13 textures, we can only use up to 16 on DX9-class hardware\n"
593 "uniform sampler2D Texture_Normal;\n"
594 "uniform sampler2D Texture_Color;\n"
595 "uniform sampler2D Texture_Gloss;\n"
596 "uniform samplerCube Texture_Cube;\n"
597 "uniform sampler2D Texture_Attenuation;\n"
598 "uniform sampler2D Texture_FogMask;\n"
599 "uniform sampler2D Texture_Pants;\n"
600 "uniform sampler2D Texture_Shirt;\n"
601 "uniform sampler2D Texture_Lightmap;\n"
602 "uniform sampler2D Texture_Deluxemap;\n"
603 "uniform sampler2D Texture_Glow;\n"
604 "uniform sampler2D Texture_Reflection;\n"
605 "uniform sampler2D Texture_Refraction;\n"
606 "\n"
607 "uniform myhalf3 LightColor;\n"
608 "uniform myhalf3 AmbientColor;\n"
609 "uniform myhalf3 DiffuseColor;\n"
610 "uniform myhalf3 SpecularColor;\n"
611 "uniform myhalf3 Color_Pants;\n"
612 "uniform myhalf3 Color_Shirt;\n"
613 "uniform myhalf3 FogColor;\n"
614 "\n"
615 "uniform myhalf4 TintColor;\n"
616 "\n"
617 "\n"
618 "//#ifdef MODE_WATER\n"
619 "uniform vec4 DistortScaleRefractReflect;\n"
620 "uniform vec4 ScreenScaleRefractReflect;\n"
621 "uniform vec4 ScreenCenterRefractReflect;\n"
622 "uniform myhalf4 RefractColor;\n"
623 "uniform myhalf4 ReflectColor;\n"
624 "uniform myhalf ReflectFactor;\n"
625 "uniform myhalf ReflectOffset;\n"
626 "//#else\n"
627 "//# ifdef MODE_REFRACTION\n"
628 "//uniform vec4 DistortScaleRefractReflect;\n"
629 "//uniform vec4 ScreenScaleRefractReflect;\n"
630 "//uniform vec4 ScreenCenterRefractReflect;\n"
631 "//uniform myhalf4 RefractColor;\n"
632 "//#  ifdef USEREFLECTION\n"
633 "//uniform myhalf4 ReflectColor;\n"
634 "//#  endif\n"
635 "//# else\n"
636 "//#  ifdef USEREFLECTION\n"
637 "//uniform vec4 DistortScaleRefractReflect;\n"
638 "//uniform vec4 ScreenScaleRefractReflect;\n"
639 "//uniform vec4 ScreenCenterRefractReflect;\n"
640 "//uniform myhalf4 ReflectColor;\n"
641 "//#  endif\n"
642 "//# endif\n"
643 "//#endif\n"
644 "\n"
645 "uniform myhalf GlowScale;\n"
646 "uniform myhalf SceneBrightness;\n"
647 "#ifdef USECONTRASTBOOST\n"
648 "uniform myhalf ContrastBoostCoeff;\n"
649 "#endif\n"
650 "\n"
651 "uniform float OffsetMapping_Scale;\n"
652 "uniform float OffsetMapping_Bias;\n"
653 "uniform float FogRangeRecip;\n"
654 "\n"
655 "uniform myhalf AmbientScale;\n"
656 "uniform myhalf DiffuseScale;\n"
657 "uniform myhalf SpecularScale;\n"
658 "uniform myhalf SpecularPower;\n"
659 "\n"
660 "#ifdef USEOFFSETMAPPING\n"
661 "vec2 OffsetMapping(vec2 TexCoord)\n"
662 "{\n"
663 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
664 "       // 14 sample relief mapping: linear search and then binary search\n"
665 "       // this basically steps forward a small amount repeatedly until it finds\n"
666 "       // itself inside solid, then jitters forward and back using decreasing\n"
667 "       // amounts to find the impact\n"
668 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
669 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
670 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
671 "       vec3 RT = vec3(TexCoord, 1);\n"
672 "       OffsetVector *= 0.1;\n"
673 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
674 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
675 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
676 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
677 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
678 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
679 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
680 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
681 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
682 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
683 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
684 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
685 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
686 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
687 "       return RT.xy;\n"
688 "#else\n"
689 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
690 "       // this basically moves forward the full distance, and then backs up based\n"
691 "       // on height of samples\n"
692 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
693 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
694 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
695 "       TexCoord += OffsetVector;\n"
696 "       OffsetVector *= 0.333;\n"
697 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
698 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
699 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
700 "       return TexCoord;\n"
701 "#endif\n"
702 "}\n"
703 "#endif // USEOFFSETMAPPING\n"
704 "\n"
705 "#ifdef MODE_WATER\n"
706 "\n"
707 "// water pass\n"
708 "void main(void)\n"
709 "{\n"
710 "#ifdef USEOFFSETMAPPING\n"
711 "       // apply offsetmapping\n"
712 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
713 "#define TexCoord TexCoordOffset\n"
714 "#endif\n"
715 "\n"
716 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
717 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
718 "       vec4 ScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xyxy * DistortScaleRefractReflect;\n"
719 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 5.0) * ReflectFactor + ReflectOffset;\n"
720 "       gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
721 "}\n"
722 "\n"
723 "#else // MODE_WATER\n"
724 "#ifdef MODE_REFRACTION\n"
725 "\n"
726 "// refraction pass\n"
727 "void main(void)\n"
728 "{\n"
729 "#ifdef USEOFFSETMAPPING\n"
730 "       // apply offsetmapping\n"
731 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
732 "#define TexCoord TexCoordOffset\n"
733 "#endif\n"
734 "\n"
735 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
736 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
737 "       vec2 ScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
738 "       gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
739 "}\n"
740 "\n"
741 "#else // MODE_REFRACTION\n"
742 "void main(void)\n"
743 "{\n"
744 "#ifdef USEOFFSETMAPPING\n"
745 "       // apply offsetmapping\n"
746 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
747 "#define TexCoord TexCoordOffset\n"
748 "#endif\n"
749 "\n"
750 "       // combine the diffuse textures (base, pants, shirt)\n"
751 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
752 "#ifdef USECOLORMAPPING\n"
753 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
754 "#endif\n"
755 "\n"
756 "\n"
757 "\n"
758 "\n"
759 "#ifdef MODE_LIGHTSOURCE\n"
760 "       // light source\n"
761 "\n"
762 "       // calculate surface normal, light normal, and specular normal\n"
763 "       // compute color intensity for the two textures (colormap and glossmap)\n"
764 "       // scale by light color and attenuation as efficiently as possible\n"
765 "       // (do as much scalar math as possible rather than vector math)\n"
766 "# ifdef USESPECULAR\n"
767 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
768 "       myhalf3 diffusenormal = myhalf3(normalize(LightVector));\n"
769 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
770 "\n"
771 "       // calculate directional shading\n"
772 "       color.rgb = LightColor * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (color.rgb * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))) + (SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower)) * myhalf3(texture2D(Texture_Gloss, TexCoord)));\n"
773 "# else\n"
774 "#  ifdef USEDIFFUSE\n"
775 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
776 "       myhalf3 diffusenormal = myhalf3(normalize(LightVector));\n"
777 "\n"
778 "       // calculate directional shading\n"
779 "       color.rgb = color.rgb * LightColor * (myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))));\n"
780 "#  else\n"
781 "       // calculate directionless shading\n"
782 "       color.rgb = color.rgb * LightColor * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
783 "#  endif\n"
784 "# endif\n"
785 "\n"
786 "# ifdef USECUBEFILTER\n"
787 "       // apply light cubemap filter\n"
788 "       //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
789 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
790 "# endif\n"
791 "#endif // MODE_LIGHTSOURCE\n"
792 "\n"
793 "\n"
794 "\n"
795 "\n"
796 "#ifdef MODE_LIGHTDIRECTION\n"
797 "       // directional model lighting\n"
798 "# ifdef USESPECULAR\n"
799 "       // get the surface normal and light normal\n"
800 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
801 "       myhalf3 diffusenormal = myhalf3(LightVector);\n"
802 "\n"
803 "       // calculate directional shading\n"
804 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
805 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
806 "       color.rgb += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
807 "# else\n"
808 "#  ifdef USEDIFFUSE\n"
809 "       // get the surface normal and light normal\n"
810 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
811 "       myhalf3 diffusenormal = myhalf3(LightVector);\n"
812 "\n"
813 "       // calculate directional shading\n"
814 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
815 "#  else\n"
816 "       color.rgb *= AmbientColor;\n"
817 "#  endif\n"
818 "# endif\n"
819 "\n"
820 "       color.a *= TintColor.a;\n"
821 "#endif // MODE_LIGHTDIRECTION\n"
822 "\n"
823 "\n"
824 "\n"
825 "\n"
826 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
827 "       // deluxemap lightmapping using light vectors in modelspace (evil q3map2)\n"
828 "\n"
829 "       // get the surface normal and light normal\n"
830 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
831 "\n"
832 "       myhalf3 diffusenormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhalf3(0.5);\n"
833 "       myhalf3 diffusenormal = normalize(myhalf3(dot(diffusenormal_modelspace, myhalf3(VectorS)), dot(diffusenormal_modelspace, myhalf3(VectorT)), dot(diffusenormal_modelspace, myhalf3(VectorR))));\n"
834 "       // calculate directional shading\n"
835 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
836 "# ifdef USESPECULAR\n"
837 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
838 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
839 "# endif\n"
840 "\n"
841 "       // apply lightmap color\n"
842 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
843 "\n"
844 "       color *= TintColor;\n"
845 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
846 "\n"
847 "\n"
848 "\n"
849 "\n"
850 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
851 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
852 "\n"
853 "       // get the surface normal and light normal\n"
854 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
855 "\n"
856 "       myhalf3 diffusenormal = normalize(myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhalf3(0.5));\n"
857 "       // calculate directional shading\n"
858 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
859 "# ifdef USESPECULAR\n"
860 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
861 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
862 "# endif\n"
863 "\n"
864 "       // apply lightmap color\n"
865 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
866 "\n"
867 "       color *= TintColor;\n"
868 "#endif // MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
869 "\n"
870 "\n"
871 "\n"
872 "\n"
873 "#ifdef MODE_LIGHTMAP\n"
874 "       // apply lightmap color\n"
875 "       color.rgb = color.rgb * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + color.rgb * AmbientScale;\n"
876 "\n"
877 "       color *= TintColor;\n"
878 "#endif // MODE_LIGHTMAP\n"
879 "\n"
880 "\n"
881 "\n"
882 "\n"
883 "#ifdef MODE_VERTEXCOLOR\n"
884 "       // apply lightmap color\n"
885 "       color.rgb = color.rgb * myhalf3(gl_Color.rgb) * DiffuseScale + color.rgb * AmbientScale;\n"
886 "\n"
887 "       color *= TintColor;\n"
888 "#endif // MODE_VERTEXCOLOR\n"
889 "\n"
890 "\n"
891 "\n"
892 "\n"
893 "#ifdef MODE_FLATCOLOR\n"
894 "       color *= TintColor;\n"
895 "#endif // MODE_FLATCOLOR\n"
896 "\n"
897 "\n"
898 "\n"
899 "\n"
900 "\n"
901 "\n"
902 "\n"
903 "\n"
904 "#ifdef USEGLOW\n"
905 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * GlowScale;\n"
906 "#endif\n"
907 "\n"
908 "#ifdef USECONTRASTBOOST\n"
909 "       color.rgb = color.rgb / (ContrastBoostCoeff * color.rgb + myhalf3(1, 1, 1));\n"
910 "#endif\n"
911 "\n"
912 "       color.rgb *= SceneBrightness;\n"
913 "\n"
914 "       // apply fog after Contrastboost/SceneBrightness because its color is already modified appropriately\n"
915 "#ifdef USEFOG\n"
916 "       color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
917 "#endif\n"
918 "\n"
919 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
920 "#ifdef USEREFLECTION\n"
921 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
922 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
923 "       vec4 ScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xyxy * DistortScaleRefractReflect;\n"
924 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord.zw)) * ReflectColor.rgb, ReflectColor.a);\n"
925 "#endif\n"
926 "\n"
927 "       gl_FragColor = vec4(color);\n"
928 "}\n"
929 "#endif // MODE_REFRACTION\n"
930 "#endif // MODE_WATER\n"
931 "\n"
932 "#endif // FRAGMENT_SHADER\n"
933 ;
934
935 typedef struct shaderpermutationinfo_s
936 {
937         const char *pretext;
938         const char *name;
939 }
940 shaderpermutationinfo_t;
941
942 typedef struct shadermodeinfo_s
943 {
944         const char *vertexfilename;
945         const char *geometryfilename;
946         const char *fragmentfilename;
947         const char *pretext;
948         const char *name;
949         int allowedpermutations;
950 }
951 shadermodeinfo_t;
952
953 typedef enum shaderpermutation_e
954 {
955         SHADERPERMUTATION_COLORMAPPING = 1<<0, // indicates this is a colormapped skin
956         SHADERPERMUTATION_CONTRASTBOOST = 1<<1, // r_glsl_contrastboost boosts the contrast at low color levels (similar to gamma)
957         SHADERPERMUTATION_FOG = 1<<2, // tint the color by fog color or black if using additive blend mode
958         SHADERPERMUTATION_CUBEFILTER = 1<<3, // (lightsource) use cubemap light filter
959         SHADERPERMUTATION_GLOW = 1<<4, // (lightmap) blend in an additive glow texture
960         SHADERPERMUTATION_DIFFUSE = 1<<5, // (lightsource) whether to use directional shading
961         SHADERPERMUTATION_SPECULAR = 1<<6, // (lightsource or deluxemapping) render specular effects
962         SHADERPERMUTATION_REFLECTION = 1<<7, // normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
963         SHADERPERMUTATION_OFFSETMAPPING = 1<<8, // adjust texcoords to roughly simulate a displacement mapped surface
964         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<9, // adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
965         SHADERPERMUTATION_LIMIT = 1<<10, // size of permutations array
966         SHADERPERMUTATION_COUNT = 10 // size of shaderpermutationinfo array
967 }
968 shaderpermutation_t;
969
970 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
971 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
972 {
973         {"#define USECOLORMAPPING\n", " colormapping"},
974         {"#define USECONTRASTBOOST\n", " contrastboost"},
975         {"#define USEFOG\n", " fog"},
976         {"#define USECUBEFILTER\n", " cubefilter"},
977         {"#define USEGLOW\n", " glow"},
978         {"#define USEDIFFUSE\n", " diffuse"},
979         {"#define USESPECULAR\n", " specular"},
980         {"#define USEREFLECTION\n", " reflection"},
981         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
982         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
983 };
984
985 // this enum is multiplied by SHADERPERMUTATION_MODEBASE
986 typedef enum shadermode_e
987 {
988         SHADERMODE_FLATCOLOR, // (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
989         SHADERMODE_VERTEXCOLOR, // (lightmap) modulate texture by vertex colors (q3bsp)
990         SHADERMODE_LIGHTMAP, // (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
991         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, // (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
992         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, // (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
993         SHADERMODE_LIGHTDIRECTION, // (lightmap) use directional pixel shading from fixed light direction (q3bsp)
994         SHADERMODE_LIGHTSOURCE, // (lightsource) use directional pixel shading from light source (rtlight)
995         SHADERMODE_REFRACTION, // refract background (the material is rendered normally after this pass)
996         SHADERMODE_WATER, // refract background and reflection (the material is rendered normally after this pass)
997         SHADERMODE_COUNT
998 }
999 shadermode_t;
1000
1001 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
1002 shadermodeinfo_t shadermodeinfo[SHADERMODE_COUNT] =
1003 {
1004         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1005         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1006         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1007         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1008         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1009         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_GLOW | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_REFLECTION | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1010         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource", SHADERPERMUTATION_COLORMAPPING | SHADERPERMUTATION_CONTRASTBOOST | SHADERPERMUTATION_FOG | SHADERPERMUTATION_CUBEFILTER | SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1011         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction", SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1012         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water", SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING},
1013 };
1014
1015 typedef struct r_glsl_permutation_s
1016 {
1017         // indicates if we have tried compiling this permutation already
1018         qboolean compiled;
1019         // 0 if compilation failed
1020         int program;
1021         // locations of detected uniforms in program object, or -1 if not found
1022         int loc_Texture_Normal;
1023         int loc_Texture_Color;
1024         int loc_Texture_Gloss;
1025         int loc_Texture_Cube;
1026         int loc_Texture_Attenuation;
1027         int loc_Texture_FogMask;
1028         int loc_Texture_Pants;
1029         int loc_Texture_Shirt;
1030         int loc_Texture_Lightmap;
1031         int loc_Texture_Deluxemap;
1032         int loc_Texture_Glow;
1033         int loc_Texture_Refraction;
1034         int loc_Texture_Reflection;
1035         int loc_FogColor;
1036         int loc_LightPosition;
1037         int loc_EyePosition;
1038         int loc_LightColor;
1039         int loc_Color_Pants;
1040         int loc_Color_Shirt;
1041         int loc_FogRangeRecip;
1042         int loc_AmbientScale;
1043         int loc_DiffuseScale;
1044         int loc_SpecularScale;
1045         int loc_SpecularPower;
1046         int loc_GlowScale;
1047         int loc_SceneBrightness; // or: Scenebrightness * ContrastBoost
1048         int loc_OffsetMapping_Scale;
1049         int loc_TintColor;
1050         int loc_AmbientColor;
1051         int loc_DiffuseColor;
1052         int loc_SpecularColor;
1053         int loc_LightDir;
1054         int loc_ContrastBoostCoeff; // 1 - 1/ContrastBoost
1055         int loc_DistortScaleRefractReflect;
1056         int loc_ScreenScaleRefractReflect;
1057         int loc_ScreenCenterRefractReflect;
1058         int loc_RefractColor;
1059         int loc_ReflectColor;
1060         int loc_ReflectFactor;
1061         int loc_ReflectOffset;
1062 }
1063 r_glsl_permutation_t;
1064
1065 // information about each possible shader permutation
1066 r_glsl_permutation_t r_glsl_permutations[SHADERMODE_COUNT][SHADERPERMUTATION_LIMIT];
1067 // currently selected permutation
1068 r_glsl_permutation_t *r_glsl_permutation;
1069
1070 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
1071 {
1072         char *shaderstring;
1073         if (!filename || !filename[0])
1074                 return NULL;
1075         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1076         if (shaderstring)
1077         {
1078                 if (printfromdisknotice)
1079                         Con_DPrint("from disk... ");
1080                 return shaderstring;
1081         }
1082         else if (!strcmp(filename, "glsl/default.glsl"))
1083         {
1084                 shaderstring = Mem_Alloc(r_main_mempool, strlen(builtinshaderstring) + 1);
1085                 memcpy(shaderstring, builtinshaderstring, strlen(builtinshaderstring) + 1);
1086         }
1087         return shaderstring;
1088 }
1089
1090 static void R_GLSL_CompilePermutation(shadermode_t mode, shaderpermutation_t permutation)
1091 {
1092         int i;
1093         shadermodeinfo_t *modeinfo = shadermodeinfo + mode;
1094         r_glsl_permutation_t *p = &r_glsl_permutations[mode][permutation];
1095         int vertstrings_count = 0;
1096         int geomstrings_count = 0;
1097         int fragstrings_count = 0;
1098         char *vertexstring, *geometrystring, *fragmentstring;
1099         const char *vertstrings_list[32+3];
1100         const char *geomstrings_list[32+3];
1101         const char *fragstrings_list[32+3];
1102         char permutationname[256];
1103
1104         if (p->compiled)
1105                 return;
1106         p->compiled = true;
1107         p->program = 0;
1108
1109         permutationname[0] = 0;
1110         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
1111         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
1112         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
1113
1114         strlcat(permutationname, shadermodeinfo[mode].vertexfilename, sizeof(permutationname));
1115
1116         // the first pretext is which type of shader to compile as
1117         // (later these will all be bound together as a program object)
1118         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1119         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1120         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1121
1122         // the second pretext is the mode (for example a light source)
1123         vertstrings_list[vertstrings_count++] = shadermodeinfo[mode].pretext;
1124         geomstrings_list[geomstrings_count++] = shadermodeinfo[mode].pretext;
1125         fragstrings_list[fragstrings_count++] = shadermodeinfo[mode].pretext;
1126         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1127
1128         // now add all the permutation pretexts
1129         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1130         {
1131                 if (permutation & (1<<i))
1132                 {
1133                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1134                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1135                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1136                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1137                 }
1138                 else
1139                 {
1140                         // keep line numbers correct
1141                         vertstrings_list[vertstrings_count++] = "\n";
1142                         geomstrings_list[geomstrings_count++] = "\n";
1143                         fragstrings_list[fragstrings_count++] = "\n";
1144                 }
1145         }
1146
1147         // now append the shader text itself
1148         vertstrings_list[vertstrings_count++] = vertexstring;
1149         geomstrings_list[geomstrings_count++] = geometrystring;
1150         fragstrings_list[fragstrings_count++] = fragmentstring;
1151
1152         // if any sources were NULL, clear the respective list
1153         if (!vertexstring)
1154                 vertstrings_count = 0;
1155         if (!geometrystring)
1156                 geomstrings_count = 0;
1157         if (!fragmentstring)
1158                 fragstrings_count = 0;
1159
1160         // compile the shader program
1161         if (vertstrings_count + geomstrings_count + fragstrings_count)
1162                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
1163         if (p->program)
1164         {
1165                 CHECKGLERROR
1166                 qglUseProgramObjectARB(p->program);CHECKGLERROR
1167                 // look up all the uniform variable names we care about, so we don't
1168                 // have to look them up every time we set them
1169                 p->loc_Texture_Normal      = qglGetUniformLocationARB(p->program, "Texture_Normal");
1170                 p->loc_Texture_Color       = qglGetUniformLocationARB(p->program, "Texture_Color");
1171                 p->loc_Texture_Gloss       = qglGetUniformLocationARB(p->program, "Texture_Gloss");
1172                 p->loc_Texture_Cube        = qglGetUniformLocationARB(p->program, "Texture_Cube");
1173                 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
1174                 p->loc_Texture_FogMask     = qglGetUniformLocationARB(p->program, "Texture_FogMask");
1175                 p->loc_Texture_Pants       = qglGetUniformLocationARB(p->program, "Texture_Pants");
1176                 p->loc_Texture_Shirt       = qglGetUniformLocationARB(p->program, "Texture_Shirt");
1177                 p->loc_Texture_Lightmap    = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
1178                 p->loc_Texture_Deluxemap   = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
1179                 p->loc_Texture_Glow        = qglGetUniformLocationARB(p->program, "Texture_Glow");
1180                 p->loc_Texture_Refraction  = qglGetUniformLocationARB(p->program, "Texture_Refraction");
1181                 p->loc_Texture_Reflection  = qglGetUniformLocationARB(p->program, "Texture_Reflection");
1182                 p->loc_FogColor            = qglGetUniformLocationARB(p->program, "FogColor");
1183                 p->loc_LightPosition       = qglGetUniformLocationARB(p->program, "LightPosition");
1184                 p->loc_EyePosition         = qglGetUniformLocationARB(p->program, "EyePosition");
1185                 p->loc_LightColor          = qglGetUniformLocationARB(p->program, "LightColor");
1186                 p->loc_Color_Pants         = qglGetUniformLocationARB(p->program, "Color_Pants");
1187                 p->loc_Color_Shirt         = qglGetUniformLocationARB(p->program, "Color_Shirt");
1188                 p->loc_FogRangeRecip       = qglGetUniformLocationARB(p->program, "FogRangeRecip");
1189                 p->loc_AmbientScale        = qglGetUniformLocationARB(p->program, "AmbientScale");
1190                 p->loc_DiffuseScale        = qglGetUniformLocationARB(p->program, "DiffuseScale");
1191                 p->loc_SpecularPower       = qglGetUniformLocationARB(p->program, "SpecularPower");
1192                 p->loc_SpecularScale       = qglGetUniformLocationARB(p->program, "SpecularScale");
1193                 p->loc_GlowScale           = qglGetUniformLocationARB(p->program, "GlowScale");
1194                 p->loc_SceneBrightness     = qglGetUniformLocationARB(p->program, "SceneBrightness");
1195                 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
1196                 p->loc_TintColor       = qglGetUniformLocationARB(p->program, "TintColor");
1197                 p->loc_AmbientColor        = qglGetUniformLocationARB(p->program, "AmbientColor");
1198                 p->loc_DiffuseColor        = qglGetUniformLocationARB(p->program, "DiffuseColor");
1199                 p->loc_SpecularColor       = qglGetUniformLocationARB(p->program, "SpecularColor");
1200                 p->loc_LightDir            = qglGetUniformLocationARB(p->program, "LightDir");
1201                 p->loc_ContrastBoostCoeff  = qglGetUniformLocationARB(p->program, "ContrastBoostCoeff");
1202                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
1203                 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
1204                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
1205                 p->loc_RefractColor        = qglGetUniformLocationARB(p->program, "RefractColor");
1206                 p->loc_ReflectColor        = qglGetUniformLocationARB(p->program, "ReflectColor");
1207                 p->loc_ReflectFactor       = qglGetUniformLocationARB(p->program, "ReflectFactor");
1208                 p->loc_ReflectOffset       = qglGetUniformLocationARB(p->program, "ReflectOffset");
1209                 // initialize the samplers to refer to the texture units we use
1210                 if (p->loc_Texture_Normal >= 0)    qglUniform1iARB(p->loc_Texture_Normal, 0);
1211                 if (p->loc_Texture_Color >= 0)     qglUniform1iARB(p->loc_Texture_Color, 1);
1212                 if (p->loc_Texture_Gloss >= 0)     qglUniform1iARB(p->loc_Texture_Gloss, 2);
1213                 if (p->loc_Texture_Cube >= 0)      qglUniform1iARB(p->loc_Texture_Cube, 3);
1214                 if (p->loc_Texture_FogMask >= 0)   qglUniform1iARB(p->loc_Texture_FogMask, 4);
1215                 if (p->loc_Texture_Pants >= 0)     qglUniform1iARB(p->loc_Texture_Pants, 5);
1216                 if (p->loc_Texture_Shirt >= 0)     qglUniform1iARB(p->loc_Texture_Shirt, 6);
1217                 if (p->loc_Texture_Lightmap >= 0)  qglUniform1iARB(p->loc_Texture_Lightmap, 7);
1218                 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap, 8);
1219                 if (p->loc_Texture_Glow >= 0)      qglUniform1iARB(p->loc_Texture_Glow, 9);
1220                 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation, 10);
1221                 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction, 11);
1222                 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection, 12);
1223                 CHECKGLERROR
1224                 qglUseProgramObjectARB(0);CHECKGLERROR
1225                 if (developer.integer)
1226                         Con_Printf("GLSL shader %s compiled.\n", permutationname);
1227         }
1228         else
1229                 Con_Printf("GLSL shader %s failed!  some features may not work properly.\n", permutationname);
1230
1231         // free the strings
1232         if (vertexstring)
1233                 Mem_Free(vertexstring);
1234         if (geometrystring)
1235                 Mem_Free(geometrystring);
1236         if (fragmentstring)
1237                 Mem_Free(fragmentstring);
1238 }
1239
1240 void R_GLSL_Restart_f(void)
1241 {
1242         shadermode_t mode;
1243         shaderpermutation_t permutation;
1244         for (mode = 0;mode < SHADERMODE_COUNT;mode++)
1245                 for (permutation = 0;permutation < SHADERPERMUTATION_LIMIT;permutation++)
1246                         if (r_glsl_permutations[mode][permutation].program)
1247                                 GL_Backend_FreeProgram(r_glsl_permutations[mode][permutation].program);
1248         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1249 }
1250
1251 void R_GLSL_DumpShader_f(void)
1252 {
1253         int i;
1254
1255         qfile_t *file = FS_Open("glsl/default.glsl", "w", false, false);
1256         if(!file)
1257         {
1258                 Con_Printf("failed to write to glsl/default.glsl\n");
1259                 return;
1260         }
1261
1262         FS_Print(file, "// The engine may define the following macros:\n");
1263         FS_Print(file, "// #define VERTEX_SHADER\n// #define GEOMETRY_SHADER\n// #define FRAGMENT_SHADER\n");
1264         for (i = 0;i < SHADERMODE_COUNT;i++)
1265                 FS_Printf(file, "// %s", shadermodeinfo[i].pretext);
1266         for (i = 0;i < SHADERPERMUTATION_LIMIT;i++)
1267                 FS_Printf(file, "// %s", shaderpermutationinfo[i].pretext);
1268         FS_Print(file, "\n");
1269         FS_Print(file, builtinshaderstring);
1270         FS_Close(file);
1271
1272         Con_Printf("glsl/default.glsl written\n");
1273 }
1274
1275 extern rtexture_t *r_shadow_attenuationgradienttexture;
1276 extern rtexture_t *r_shadow_attenuation2dtexture;
1277 extern rtexture_t *r_shadow_attenuation3dtexture;
1278 int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass)
1279 {
1280         // select a permutation of the lighting shader appropriate to this
1281         // combination of texture, entity, light source, and fogging, only use the
1282         // minimum features necessary to avoid wasting rendering time in the
1283         // fragment shader on features that are not being used
1284         unsigned int permutation = 0;
1285         shadermode_t mode = 0;
1286         r_glsl_permutation = NULL;
1287         // TODO: implement geometry-shader based shadow volumes someday
1288         if (r_glsl_offsetmapping.integer)
1289         {
1290                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
1291                 if (r_glsl_offsetmapping_reliefmapping.integer)
1292                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
1293         }
1294         if (rsurfacepass == RSURFPASS_BACKGROUND)
1295         {
1296                 // distorted background
1297                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
1298                         mode = SHADERMODE_WATER;
1299                 else
1300                         mode = SHADERMODE_REFRACTION;
1301         }
1302         else if (rsurfacepass == RSURFPASS_RTLIGHT)
1303         {
1304                 // light source
1305                 mode = SHADERMODE_LIGHTSOURCE;
1306                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
1307                         permutation |= SHADERPERMUTATION_CUBEFILTER;
1308                 if (diffusescale > 0)
1309                         permutation |= SHADERPERMUTATION_DIFFUSE;
1310                 if (specularscale > 0)
1311                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1312                 if (r_refdef.fogenabled)
1313                         permutation |= SHADERPERMUTATION_FOG;
1314                 if (rsurface.texture->colormapping)
1315                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1316                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1317                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1318         }
1319         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
1320         {
1321                 // unshaded geometry (fullbright or ambient model lighting)
1322                 mode = SHADERMODE_FLATCOLOR;
1323                 if (rsurface.texture->currentskinframe->glow)
1324                         permutation |= SHADERPERMUTATION_GLOW;
1325                 if (r_refdef.fogenabled)
1326                         permutation |= SHADERPERMUTATION_FOG;
1327                 if (rsurface.texture->colormapping)
1328                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1329                 if (r_glsl_offsetmapping.integer)
1330                 {
1331                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
1332                         if (r_glsl_offsetmapping_reliefmapping.integer)
1333                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
1334                 }
1335                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1336                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1337                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1338                         permutation |= SHADERPERMUTATION_REFLECTION;
1339         }
1340         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
1341         {
1342                 // directional model lighting
1343                 mode = SHADERMODE_LIGHTDIRECTION;
1344                 if (rsurface.texture->currentskinframe->glow)
1345                         permutation |= SHADERPERMUTATION_GLOW;
1346                 permutation |= SHADERPERMUTATION_DIFFUSE;
1347                 if (specularscale > 0)
1348                         permutation |= SHADERPERMUTATION_SPECULAR;
1349                 if (r_refdef.fogenabled)
1350                         permutation |= SHADERPERMUTATION_FOG;
1351                 if (rsurface.texture->colormapping)
1352                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1353                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1354                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1355                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1356                         permutation |= SHADERPERMUTATION_REFLECTION;
1357         }
1358         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
1359         {
1360                 // ambient model lighting
1361                 mode = SHADERMODE_LIGHTDIRECTION;
1362                 if (rsurface.texture->currentskinframe->glow)
1363                         permutation |= SHADERPERMUTATION_GLOW;
1364                 if (r_refdef.fogenabled)
1365                         permutation |= SHADERPERMUTATION_FOG;
1366                 if (rsurface.texture->colormapping)
1367                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1368                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1369                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1370                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1371                         permutation |= SHADERPERMUTATION_REFLECTION;
1372         }
1373         else
1374         {
1375                 // lightmapped wall
1376                 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
1377                 {
1378                         // deluxemapping (light direction texture)
1379                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
1380                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
1381                         else
1382                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
1383                         if (specularscale > 0)
1384                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1385                 }
1386                 else if (r_glsl_deluxemapping.integer >= 2)
1387                 {
1388                         // fake deluxemapping (uniform light direction in tangentspace)
1389                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
1390                         if (specularscale > 0)
1391                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1392                 }
1393                 else if (rsurface.uselightmaptexture)
1394                 {
1395                         // ordinary lightmapping (q1bsp, q3bsp)
1396                         mode = SHADERMODE_LIGHTMAP;
1397                 }
1398                 else
1399                 {
1400                         // ordinary vertex coloring (q3bsp)
1401                         mode = SHADERMODE_VERTEXCOLOR;
1402                 }
1403                 if (rsurface.texture->currentskinframe->glow)
1404                         permutation |= SHADERPERMUTATION_GLOW;
1405                 if (r_refdef.fogenabled)
1406                         permutation |= SHADERPERMUTATION_FOG;
1407                 if (rsurface.texture->colormapping)
1408                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1409                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1410                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1411                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1412                         permutation |= SHADERPERMUTATION_REFLECTION;
1413         }
1414         r_glsl_permutation = &r_glsl_permutations[mode][permutation];
1415         if (!r_glsl_permutation->program)
1416         {
1417                 if (!r_glsl_permutation->compiled)
1418                         R_GLSL_CompilePermutation(mode, permutation);
1419                 if (!r_glsl_permutation->program)
1420                 {
1421                         // remove features until we find a valid permutation
1422                         int i;
1423                         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1424                         {
1425                                 // reduce i more quickly whenever it would not remove any bits
1426                                 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1427                                 if (!(permutation & j))
1428                                         continue;
1429                                 permutation -= j;
1430                                 r_glsl_permutation = &r_glsl_permutations[mode][permutation];
1431                                 if (!r_glsl_permutation->compiled)
1432                                         R_GLSL_CompilePermutation(mode, permutation);
1433                                 if (r_glsl_permutation->program)
1434                                         break;
1435                         }
1436                         if (i >= SHADERPERMUTATION_COUNT)
1437                         {
1438                                 Con_Printf("OpenGL 2.0 shaders disabled - unable to find a working shader permutation fallback on this driver (set r_glsl 1 if you want to try again)\n");
1439                                 Cvar_SetValueQuick(&r_glsl, 0);
1440                                 return 0; // no bit left to clear
1441                         }
1442                 }
1443         }
1444         CHECKGLERROR
1445         qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
1446         if (mode == SHADERMODE_LIGHTSOURCE)
1447         {
1448                 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
1449                 if (permutation & SHADERPERMUTATION_DIFFUSE)
1450                 {
1451                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
1452                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, ambientscale);
1453                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, diffusescale);
1454                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, specularscale);
1455                 }
1456                 else
1457                 {
1458                         // ambient only is simpler
1459                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0] * ambientscale, lightcolorbase[1] * ambientscale, lightcolorbase[2] * ambientscale);
1460                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, 1);
1461                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, 0);
1462                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, 0);
1463                 }
1464         }
1465         else if (mode == SHADERMODE_LIGHTDIRECTION)
1466         {
1467                 if (r_glsl_permutation->loc_AmbientColor >= 0)
1468                         qglUniform3fARB(r_glsl_permutation->loc_AmbientColor , rsurface.modellight_ambient[0] * ambientscale  * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_ambient[1] * ambientscale  * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_ambient[2] * ambientscale  * rsurface.texture->lightmapcolor[2] * 0.5f);
1469                 if (r_glsl_permutation->loc_DiffuseColor >= 0)
1470                         qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor , rsurface.modellight_diffuse[0] * diffusescale  * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_diffuse[1] * diffusescale  * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_diffuse[2] * diffusescale  * rsurface.texture->lightmapcolor[2] * 0.5f);
1471                 if (r_glsl_permutation->loc_SpecularColor >= 0)
1472                         qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface.modellight_diffuse[0] * specularscale * rsurface.texture->lightmapcolor[0] * 0.5f, rsurface.modellight_diffuse[1] * specularscale * rsurface.texture->lightmapcolor[1] * 0.5f, rsurface.modellight_diffuse[2] * specularscale * rsurface.texture->lightmapcolor[2] * 0.5f);
1473                 if (r_glsl_permutation->loc_LightDir >= 0)
1474                         qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
1475         }
1476         else
1477         {
1478                 if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 1.0f / 128.0f);
1479                 if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity);
1480                 if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale);
1481         }
1482         if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2], rsurface.texture->lightmapcolor[3]);
1483         if (r_glsl_permutation->loc_GlowScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_GlowScale, r_hdr_glowintensity.value);
1484         if (r_glsl_permutation->loc_ContrastBoostCoeff >= 0)
1485         {
1486                 // The formula used is actually:
1487                 //   color.rgb *= ContrastBoost / ((ContrastBoost - 1) * color.rgb + 1);
1488                 //   color.rgb *= SceneBrightness;
1489                 // simplified:
1490                 //   color.rgb = [[SceneBrightness * ContrastBoost]] * color.rgb / ([[ContrastBoost - 1]] * color.rgb + 1);
1491                 // and do [[calculations]] here in the engine
1492                 qglUniform1fARB(r_glsl_permutation->loc_ContrastBoostCoeff, r_glsl_contrastboost.value - 1);
1493                 if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_refdef.view.colorscale * r_glsl_contrastboost.value);
1494         }
1495         else
1496                 if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_refdef.view.colorscale);
1497         if (r_glsl_permutation->loc_FogColor >= 0)
1498         {
1499                 // additive passes are only darkened by fog, not tinted
1500                 if (rsurface.rtlight || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD))
1501                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
1502                 else
1503                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
1504         }
1505         if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.modelorg[0], rsurface.modelorg[1], rsurface.modelorg[2]);
1506         if (r_glsl_permutation->loc_Color_Pants >= 0)
1507         {
1508                 if (rsurface.texture->currentskinframe->pants)
1509                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
1510                 else
1511                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
1512         }
1513         if (r_glsl_permutation->loc_Color_Shirt >= 0)
1514         {
1515                 if (rsurface.texture->currentskinframe->shirt)
1516                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
1517                 else
1518                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
1519         }
1520         if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, r_refdef.fograngerecip);
1521         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower);
1522         if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
1523         if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
1524         if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
1525         if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
1526         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
1527         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
1528         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
1529         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
1530         CHECKGLERROR
1531         return permutation;
1532 }
1533
1534 #define SKINFRAME_HASH 1024
1535
1536 struct
1537 {
1538         int loadsequence; // incremented each level change
1539         memexpandablearray_t array;
1540         skinframe_t *hash[SKINFRAME_HASH];
1541 }
1542 r_skinframe;
1543
1544 void R_SkinFrame_PrepareForPurge(void)
1545 {
1546         r_skinframe.loadsequence++;
1547         // wrap it without hitting zero
1548         if (r_skinframe.loadsequence >= 200)
1549                 r_skinframe.loadsequence = 1;
1550 }
1551
1552 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
1553 {
1554         if (!skinframe)
1555                 return;
1556         // mark the skinframe as used for the purging code
1557         skinframe->loadsequence = r_skinframe.loadsequence;
1558 }
1559
1560 void R_SkinFrame_Purge(void)
1561 {
1562         int i;
1563         skinframe_t *s;
1564         for (i = 0;i < SKINFRAME_HASH;i++)
1565         {
1566                 for (s = r_skinframe.hash[i];s;s = s->next)
1567                 {
1568                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
1569                         {
1570                                 if (s->merged == s->base)
1571                                         s->merged = NULL;
1572                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
1573                                 R_PurgeTexture(s->stain );s->stain  = NULL;
1574                                 R_PurgeTexture(s->merged);s->merged = NULL;
1575                                 R_PurgeTexture(s->base  );s->base   = NULL;
1576                                 R_PurgeTexture(s->pants );s->pants  = NULL;
1577                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
1578                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
1579                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
1580                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
1581                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
1582                                 s->loadsequence = 0;
1583                         }
1584                 }
1585         }
1586 }
1587
1588 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
1589         skinframe_t *item;
1590         char basename[MAX_QPATH];
1591
1592         Image_StripImageExtension(name, basename, sizeof(basename));
1593
1594         if( last == NULL ) {
1595                 int hashindex;
1596                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1597                 item = r_skinframe.hash[hashindex];
1598         } else {
1599                 item = last->next;
1600         }
1601
1602         // linearly search through the hash bucket
1603         for( ; item ; item = item->next ) {
1604                 if( !strcmp( item->basename, basename ) ) {
1605                         return item;
1606                 }
1607         }
1608         return NULL;
1609 }
1610
1611 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
1612 {
1613         skinframe_t *item;
1614         int hashindex;
1615         char basename[MAX_QPATH];
1616
1617         Image_StripImageExtension(name, basename, sizeof(basename));
1618
1619         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1620         for (item = r_skinframe.hash[hashindex];item;item = item->next)
1621                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
1622                         break;
1623
1624         if (!item) {
1625                 rtexture_t *dyntexture;
1626                 // check whether its a dynamic texture
1627                 dyntexture = CL_GetDynTexture( basename );
1628                 if (!add && !dyntexture)
1629                         return NULL;
1630                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
1631                 memset(item, 0, sizeof(*item));
1632                 strlcpy(item->basename, basename, sizeof(item->basename));
1633                 item->base = dyntexture; // either NULL or dyntexture handle
1634                 item->textureflags = textureflags;
1635                 item->comparewidth = comparewidth;
1636                 item->compareheight = compareheight;
1637                 item->comparecrc = comparecrc;
1638                 item->next = r_skinframe.hash[hashindex];
1639                 r_skinframe.hash[hashindex] = item;
1640         }
1641         else if( item->base == NULL )
1642         {
1643                 rtexture_t *dyntexture;
1644                 // check whether its a dynamic texture
1645                 // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
1646                 dyntexture = CL_GetDynTexture( basename );
1647                 item->base = dyntexture; // either NULL or dyntexture handle
1648         }
1649
1650         R_SkinFrame_MarkUsed(item);
1651         return item;
1652 }
1653
1654 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
1655 {
1656         // FIXME: it should be possible to disable loading various layers using
1657         // cvars, to prevent wasted loading time and memory usage if the user does
1658         // not want them
1659         qboolean loadnormalmap = true;
1660         qboolean loadgloss = true;
1661         qboolean loadpantsandshirt = true;
1662         qboolean loadglow = true;
1663         int j;
1664         unsigned char *pixels;
1665         unsigned char *bumppixels;
1666         unsigned char *basepixels = NULL;
1667         int basepixels_width;
1668         int basepixels_height;
1669         skinframe_t *skinframe;
1670
1671         if (cls.state == ca_dedicated)
1672                 return NULL;
1673
1674         // return an existing skinframe if already loaded
1675         // if loading of the first image fails, don't make a new skinframe as it
1676         // would cause all future lookups of this to be missing
1677         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
1678         if (skinframe && skinframe->base)
1679                 return skinframe;
1680
1681         basepixels = loadimagepixelsbgra(name, complain, true);
1682         if (basepixels == NULL)
1683                 return NULL;
1684
1685         // we've got some pixels to store, so really allocate this new texture now
1686         if (!skinframe)
1687                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
1688         skinframe->stain = NULL;
1689         skinframe->merged = NULL;
1690         skinframe->base = r_texture_notexture;
1691         skinframe->pants = NULL;
1692         skinframe->shirt = NULL;
1693         skinframe->nmap = r_texture_blanknormalmap;
1694         skinframe->gloss = NULL;
1695         skinframe->glow = NULL;
1696         skinframe->fog = NULL;
1697
1698         basepixels_width = image_width;
1699         basepixels_height = image_height;
1700         skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1701
1702         if (textureflags & TEXF_ALPHA)
1703         {
1704                 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
1705                         if (basepixels[j] < 255)
1706                                 break;
1707                 if (j < basepixels_width * basepixels_height * 4)
1708                 {
1709                         // has transparent pixels
1710                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1711                         for (j = 0;j < image_width * image_height * 4;j += 4)
1712                         {
1713                                 pixels[j+0] = 255;
1714                                 pixels[j+1] = 255;
1715                                 pixels[j+2] = 255;
1716                                 pixels[j+3] = basepixels[j+3];
1717                         }
1718                         skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1719                         Mem_Free(pixels);
1720                 }
1721         }
1722
1723         // _norm is the name used by tenebrae and has been adopted as standard
1724         if (loadnormalmap)
1725         {
1726                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false)) != NULL)
1727                 {
1728                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1729                         Mem_Free(pixels);
1730                         pixels = NULL;
1731                 }
1732                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false)) != NULL)
1733                 {
1734                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1735                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
1736                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1737                         Mem_Free(pixels);
1738                         Mem_Free(bumppixels);
1739                 }
1740                 else if (r_shadow_bumpscale_basetexture.value > 0)
1741                 {
1742                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
1743                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
1744                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1745                         Mem_Free(pixels);
1746                 }
1747         }
1748         // _luma is supported for tenebrae compatibility
1749         // (I think it's a very stupid name, but oh well)
1750         // _glow is the preferred name
1751         if (loadglow          && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false)) != NULL || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1752         if (loadgloss         && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1753         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1754         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1755
1756         if (basepixels)
1757                 Mem_Free(basepixels);
1758
1759         return skinframe;
1760 }
1761
1762 static rtexture_t *R_SkinFrame_TextureForSkinLayer(const unsigned char *in, int width, int height, const char *name, const unsigned int *palette, int textureflags, qboolean force)
1763 {
1764         int i;
1765         if (!force)
1766         {
1767                 for (i = 0;i < width*height;i++)
1768                         if (((unsigned char *)&palette[in[i]])[3] > 0)
1769                                 break;
1770                 if (i == width*height)
1771                         return NULL;
1772         }
1773         return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
1774 }
1775
1776 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
1777 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
1778 {
1779         int i;
1780         unsigned char *temp1, *temp2;
1781         skinframe_t *skinframe;
1782
1783         if (cls.state == ca_dedicated)
1784                 return NULL;
1785
1786         // if already loaded just return it, otherwise make a new skinframe
1787         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
1788         if (skinframe && skinframe->base)
1789                 return skinframe;
1790
1791         skinframe->stain = NULL;
1792         skinframe->merged = NULL;
1793         skinframe->base = r_texture_notexture;
1794         skinframe->pants = NULL;
1795         skinframe->shirt = NULL;
1796         skinframe->nmap = r_texture_blanknormalmap;
1797         skinframe->gloss = NULL;
1798         skinframe->glow = NULL;
1799         skinframe->fog = NULL;
1800
1801         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1802         if (!skindata)
1803                 return NULL;
1804
1805         if (r_shadow_bumpscale_basetexture.value > 0)
1806         {
1807                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1808                 temp2 = temp1 + width * height * 4;
1809                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1810                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
1811                 Mem_Free(temp1);
1812         }
1813         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
1814         if (textureflags & TEXF_ALPHA)
1815         {
1816                 for (i = 3;i < width * height * 4;i += 4)
1817                         if (skindata[i] < 255)
1818                                 break;
1819                 if (i < width * height * 4)
1820                 {
1821                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
1822                         memcpy(fogpixels, skindata, width * height * 4);
1823                         for (i = 0;i < width * height * 4;i += 4)
1824                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
1825                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
1826                         Mem_Free(fogpixels);
1827                 }
1828         }
1829
1830         return skinframe;
1831 }
1832
1833 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
1834 {
1835         int i;
1836         unsigned char *temp1, *temp2;
1837         skinframe_t *skinframe;
1838
1839         if (cls.state == ca_dedicated)
1840                 return NULL;
1841
1842         // if already loaded just return it, otherwise make a new skinframe
1843         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
1844         if (skinframe && skinframe->base)
1845                 return skinframe;
1846
1847         skinframe->stain = NULL;
1848         skinframe->merged = NULL;
1849         skinframe->base = r_texture_notexture;
1850         skinframe->pants = NULL;
1851         skinframe->shirt = NULL;
1852         skinframe->nmap = r_texture_blanknormalmap;
1853         skinframe->gloss = NULL;
1854         skinframe->glow = NULL;
1855         skinframe->fog = NULL;
1856
1857         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1858         if (!skindata)
1859                 return NULL;
1860
1861         if (r_shadow_bumpscale_basetexture.value > 0)
1862         {
1863                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1864                 temp2 = temp1 + width * height * 4;
1865                 // use either a custom palette or the quake palette
1866                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
1867                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1868                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
1869                 Mem_Free(temp1);
1870         }
1871         // use either a custom palette, or the quake palette
1872         skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), (loadglowtexture ? palette_bgra_nofullbrights : ((skinframe->textureflags & TEXF_ALPHA) ? palette_bgra_transparent : palette_bgra_complete)), skinframe->textureflags, true); // all
1873         if (loadglowtexture)
1874                 skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_bgra_onlyfullbrights, skinframe->textureflags, false); // glow
1875         if (loadpantsandshirt)
1876         {
1877                 skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_bgra_pantsaswhite, skinframe->textureflags, false); // pants
1878                 skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_bgra_shirtaswhite, skinframe->textureflags, false); // shirt
1879         }
1880         if (skinframe->pants || skinframe->shirt)
1881                 skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename), loadglowtexture ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap, skinframe->textureflags, false); // no special colors
1882         if (textureflags & TEXF_ALPHA)
1883         {
1884                 for (i = 0;i < width * height;i++)
1885                         if (((unsigned char *)palette_bgra_alpha)[skindata[i]*4+3] < 255)
1886                                 break;
1887                 if (i < width * height)
1888                         skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), palette_bgra_alpha, skinframe->textureflags, true); // fog mask
1889         }
1890
1891         return skinframe;
1892 }
1893
1894 skinframe_t *R_SkinFrame_LoadMissing(void)
1895 {
1896         skinframe_t *skinframe;
1897
1898         if (cls.state == ca_dedicated)
1899                 return NULL;
1900
1901         skinframe = R_SkinFrame_Find("missing", TEXF_PRECACHE, 0, 0, 0, true);
1902         skinframe->stain = NULL;
1903         skinframe->merged = NULL;
1904         skinframe->base = r_texture_notexture;
1905         skinframe->pants = NULL;
1906         skinframe->shirt = NULL;
1907         skinframe->nmap = r_texture_blanknormalmap;
1908         skinframe->gloss = NULL;
1909         skinframe->glow = NULL;
1910         skinframe->fog = NULL;
1911
1912         return skinframe;
1913 }
1914
1915 void gl_main_start(void)
1916 {
1917         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1918         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1919
1920         // set up r_skinframe loading system for textures
1921         memset(&r_skinframe, 0, sizeof(r_skinframe));
1922         r_skinframe.loadsequence = 1;
1923         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
1924
1925         r_main_texturepool = R_AllocTexturePool();
1926         R_BuildBlankTextures();
1927         R_BuildNoTexture();
1928         if (gl_texturecubemap)
1929         {
1930                 R_BuildWhiteCube();
1931                 R_BuildNormalizationCube();
1932         }
1933         r_texture_fogattenuation = NULL;
1934         //r_texture_fogintensity = NULL;
1935         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1936         memset(&r_waterstate, 0, sizeof(r_waterstate));
1937         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1938         memset(&r_svbsp, 0, sizeof (r_svbsp));
1939
1940         r_refdef.fogmasktable_density = 0;
1941 }
1942
1943 void gl_main_shutdown(void)
1944 {
1945         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1946         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1947
1948         // clear out the r_skinframe state
1949         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
1950         memset(&r_skinframe, 0, sizeof(r_skinframe));
1951
1952         if (r_svbsp.nodes)
1953                 Mem_Free(r_svbsp.nodes);
1954         memset(&r_svbsp, 0, sizeof (r_svbsp));
1955         R_FreeTexturePool(&r_main_texturepool);
1956         r_texture_blanknormalmap = NULL;
1957         r_texture_white = NULL;
1958         r_texture_grey128 = NULL;
1959         r_texture_black = NULL;
1960         r_texture_whitecube = NULL;
1961         r_texture_normalizationcube = NULL;
1962         r_texture_fogattenuation = NULL;
1963         //r_texture_fogintensity = NULL;
1964         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1965         memset(&r_waterstate, 0, sizeof(r_waterstate));
1966         R_GLSL_Restart_f();
1967 }
1968
1969 extern void CL_ParseEntityLump(char *entitystring);
1970 void gl_main_newmap(void)
1971 {
1972         // FIXME: move this code to client
1973         int l;
1974         char *entities, entname[MAX_QPATH];
1975         if (cl.worldmodel)
1976         {
1977                 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
1978                 l = (int)strlen(entname) - 4;
1979                 if (l >= 0 && !strcmp(entname + l, ".bsp"))
1980                 {
1981                         memcpy(entname + l, ".ent", 5);
1982                         if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
1983                         {
1984                                 CL_ParseEntityLump(entities);
1985                                 Mem_Free(entities);
1986                                 return;
1987                         }
1988                 }
1989                 if (cl.worldmodel->brush.entities)
1990                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
1991         }
1992 }
1993
1994 void GL_Main_Init(void)
1995 {
1996         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
1997
1998         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
1999         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
2000         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
2001         if (gamemode == GAME_NEHAHRA)
2002         {
2003                 Cvar_RegisterVariable (&gl_fogenable);
2004                 Cvar_RegisterVariable (&gl_fogdensity);
2005                 Cvar_RegisterVariable (&gl_fogred);
2006                 Cvar_RegisterVariable (&gl_foggreen);
2007                 Cvar_RegisterVariable (&gl_fogblue);
2008                 Cvar_RegisterVariable (&gl_fogstart);
2009                 Cvar_RegisterVariable (&gl_fogend);
2010                 Cvar_RegisterVariable (&gl_skyclip);
2011         }
2012         Cvar_RegisterVariable(&r_depthfirst);
2013         Cvar_RegisterVariable(&r_nearclip);
2014         Cvar_RegisterVariable(&r_showbboxes);
2015         Cvar_RegisterVariable(&r_showsurfaces);
2016         Cvar_RegisterVariable(&r_showtris);
2017         Cvar_RegisterVariable(&r_shownormals);
2018         Cvar_RegisterVariable(&r_showlighting);
2019         Cvar_RegisterVariable(&r_showshadowvolumes);
2020         Cvar_RegisterVariable(&r_showcollisionbrushes);
2021         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
2022         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
2023         Cvar_RegisterVariable(&r_showdisabledepthtest);
2024         Cvar_RegisterVariable(&r_drawportals);
2025         Cvar_RegisterVariable(&r_drawentities);
2026         Cvar_RegisterVariable(&r_cullentities_trace);
2027         Cvar_RegisterVariable(&r_cullentities_trace_samples);
2028         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
2029         Cvar_RegisterVariable(&r_cullentities_trace_delay);
2030         Cvar_RegisterVariable(&r_drawviewmodel);
2031         Cvar_RegisterVariable(&r_speeds);
2032         Cvar_RegisterVariable(&r_fullbrights);
2033         Cvar_RegisterVariable(&r_wateralpha);
2034         Cvar_RegisterVariable(&r_dynamic);
2035         Cvar_RegisterVariable(&r_fullbright);
2036         Cvar_RegisterVariable(&r_shadows);
2037         Cvar_RegisterVariable(&r_shadows_throwdistance);
2038         Cvar_RegisterVariable(&r_q1bsp_skymasking);
2039         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
2040         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
2041         Cvar_RegisterVariable(&r_fog_exp2);
2042         Cvar_RegisterVariable(&r_textureunits);
2043         Cvar_RegisterVariable(&r_glsl);
2044         Cvar_RegisterVariable(&r_glsl_offsetmapping);
2045         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
2046         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
2047         Cvar_RegisterVariable(&r_glsl_deluxemapping);
2048         Cvar_RegisterVariable(&r_water);
2049         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
2050         Cvar_RegisterVariable(&r_water_clippingplanebias);
2051         Cvar_RegisterVariable(&r_water_refractdistort);
2052         Cvar_RegisterVariable(&r_water_reflectdistort);
2053         Cvar_RegisterVariable(&r_lerpsprites);
2054         Cvar_RegisterVariable(&r_lerpmodels);
2055         Cvar_RegisterVariable(&r_lerplightstyles);
2056         Cvar_RegisterVariable(&r_waterscroll);
2057         Cvar_RegisterVariable(&r_bloom);
2058         Cvar_RegisterVariable(&r_bloom_colorscale);
2059         Cvar_RegisterVariable(&r_bloom_brighten);
2060         Cvar_RegisterVariable(&r_bloom_blur);
2061         Cvar_RegisterVariable(&r_bloom_resolution);
2062         Cvar_RegisterVariable(&r_bloom_colorexponent);
2063         Cvar_RegisterVariable(&r_bloom_colorsubtract);
2064         Cvar_RegisterVariable(&r_hdr);
2065         Cvar_RegisterVariable(&r_hdr_scenebrightness);
2066         Cvar_RegisterVariable(&r_glsl_contrastboost);
2067         Cvar_RegisterVariable(&r_hdr_glowintensity);
2068         Cvar_RegisterVariable(&r_hdr_range);
2069         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
2070         Cvar_RegisterVariable(&developer_texturelogging);
2071         Cvar_RegisterVariable(&gl_lightmaps);
2072         Cvar_RegisterVariable(&r_test);
2073         Cvar_RegisterVariable(&r_batchmode);
2074         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
2075                 Cvar_SetValue("r_fullbrights", 0);
2076         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
2077
2078         Cvar_RegisterVariable(&r_track_sprites);
2079         Cvar_RegisterVariable(&r_track_sprites_flags);
2080         Cvar_RegisterVariable(&r_track_sprites_scalew);
2081         Cvar_RegisterVariable(&r_track_sprites_scaleh);
2082 }
2083
2084 extern void R_Textures_Init(void);
2085 extern void GL_Draw_Init(void);
2086 extern void GL_Main_Init(void);
2087 extern void R_Shadow_Init(void);
2088 extern void R_Sky_Init(void);
2089 extern void GL_Surf_Init(void);
2090 extern void R_Particles_Init(void);
2091 extern void R_Explosion_Init(void);
2092 extern void gl_backend_init(void);
2093 extern void Sbar_Init(void);
2094 extern void R_LightningBeams_Init(void);
2095 extern void Mod_RenderInit(void);
2096
2097 void Render_Init(void)
2098 {
2099         gl_backend_init();
2100         R_Textures_Init();
2101         GL_Main_Init();
2102         GL_Draw_Init();
2103         R_Shadow_Init();
2104         R_Sky_Init();
2105         GL_Surf_Init();
2106         Sbar_Init();
2107         R_Particles_Init();
2108         R_Explosion_Init();
2109         R_LightningBeams_Init();
2110         Mod_RenderInit();
2111 }
2112
2113 /*
2114 ===============
2115 GL_Init
2116 ===============
2117 */
2118 extern char *ENGINE_EXTENSIONS;
2119 void GL_Init (void)
2120 {
2121         VID_CheckExtensions();
2122
2123         // LordHavoc: report supported extensions
2124         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
2125
2126         // clear to black (loading plaque will be seen over this)
2127         CHECKGLERROR
2128         qglClearColor(0,0,0,1);CHECKGLERROR
2129         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
2130 }
2131
2132 int R_CullBox(const vec3_t mins, const vec3_t maxs)
2133 {
2134         int i;
2135         mplane_t *p;
2136         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
2137         {
2138                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
2139                 if (i == 4)
2140                         continue;
2141                 p = r_refdef.view.frustum + i;
2142                 switch(p->signbits)
2143                 {
2144                 default:
2145                 case 0:
2146                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2147                                 return true;
2148                         break;
2149                 case 1:
2150                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2151                                 return true;
2152                         break;
2153                 case 2:
2154                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2155                                 return true;
2156                         break;
2157                 case 3:
2158                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2159                                 return true;
2160                         break;
2161                 case 4:
2162                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2163                                 return true;
2164                         break;
2165                 case 5:
2166                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2167                                 return true;
2168                         break;
2169                 case 6:
2170                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2171                                 return true;
2172                         break;
2173                 case 7:
2174                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2175                                 return true;
2176                         break;
2177                 }
2178         }
2179         return false;
2180 }
2181
2182 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
2183 {
2184         int i;
2185         const mplane_t *p;
2186         for (i = 0;i < numplanes;i++)
2187         {
2188                 p = planes + i;
2189                 switch(p->signbits)
2190                 {
2191                 default:
2192                 case 0:
2193                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2194                                 return true;
2195                         break;
2196                 case 1:
2197                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2198                                 return true;
2199                         break;
2200                 case 2:
2201                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2202                                 return true;
2203                         break;
2204                 case 3:
2205                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2206                                 return true;
2207                         break;
2208                 case 4:
2209                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2210                                 return true;
2211                         break;
2212                 case 5:
2213                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2214                                 return true;
2215                         break;
2216                 case 6:
2217                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2218                                 return true;
2219                         break;
2220                 case 7:
2221                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2222                                 return true;
2223                         break;
2224                 }
2225         }
2226         return false;
2227 }
2228
2229 //==================================================================================
2230
2231 static void R_View_UpdateEntityVisible (void)
2232 {
2233         int i, renderimask;
2234         entity_render_t *ent;
2235
2236         if (!r_drawentities.integer)
2237                 return;
2238
2239         renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL) : ((chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL : RENDER_EXTERIORMODEL);
2240         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
2241         {
2242                 // worldmodel can check visibility
2243                 for (i = 0;i < r_refdef.scene.numentities;i++)
2244                 {
2245                         ent = r_refdef.scene.entities[i];
2246                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs)) && ((ent->effects & EF_NODEPTHTEST) || (ent->flags & RENDER_VIEWMODEL) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs));
2247
2248                 }
2249                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight)
2250                 {
2251                         for (i = 0;i < r_refdef.scene.numentities;i++)
2252                         {
2253                                 ent = r_refdef.scene.entities[i];
2254                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->effects & EF_NODEPTHTEST) && !(ent->flags & RENDER_VIEWMODEL) && !(ent->model && (ent->model->name[0] == '*')))
2255                                 {
2256                                         if(Mod_CanSeeBox_Trace(r_cullentities_trace_samples.integer, r_cullentities_trace_enlarge.value, r_refdef.scene.worldmodel, r_refdef.view.origin, ent->mins, ent->maxs))
2257                                                 ent->last_trace_visibility = realtime;
2258                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
2259                                                 r_refdef.viewcache.entityvisible[i] = 0;
2260                                 }
2261                         }
2262                 }
2263         }
2264         else
2265         {
2266                 // no worldmodel or it can't check visibility
2267                 for (i = 0;i < r_refdef.scene.numentities;i++)
2268                 {
2269                         ent = r_refdef.scene.entities[i];
2270                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
2271                 }
2272         }
2273 }
2274
2275 // only used if skyrendermasked, and normally returns false
2276 int R_DrawBrushModelsSky (void)
2277 {
2278         int i, sky;
2279         entity_render_t *ent;
2280
2281         if (!r_drawentities.integer)
2282                 return false;
2283
2284         sky = false;
2285         for (i = 0;i < r_refdef.scene.numentities;i++)
2286         {
2287                 if (!r_refdef.viewcache.entityvisible[i])
2288                         continue;
2289                 ent = r_refdef.scene.entities[i];
2290                 if (!ent->model || !ent->model->DrawSky)
2291                         continue;
2292                 ent->model->DrawSky(ent);
2293                 sky = true;
2294         }
2295         return sky;
2296 }
2297
2298 static void R_DrawNoModel(entity_render_t *ent);
2299 static void R_DrawModels(void)
2300 {
2301         int i;
2302         entity_render_t *ent;
2303
2304         if (!r_drawentities.integer)
2305                 return;
2306
2307         for (i = 0;i < r_refdef.scene.numentities;i++)
2308         {
2309                 if (!r_refdef.viewcache.entityvisible[i])
2310                         continue;
2311                 ent = r_refdef.scene.entities[i];
2312                 r_refdef.stats.entities++;
2313                 if (ent->model && ent->model->Draw != NULL)
2314                         ent->model->Draw(ent);
2315                 else
2316                         R_DrawNoModel(ent);
2317         }
2318 }
2319
2320 static void R_DrawModelsDepth(void)
2321 {
2322         int i;
2323         entity_render_t *ent;
2324
2325         if (!r_drawentities.integer)
2326                 return;
2327
2328         for (i = 0;i < r_refdef.scene.numentities;i++)
2329         {
2330                 if (!r_refdef.viewcache.entityvisible[i])
2331                         continue;
2332                 ent = r_refdef.scene.entities[i];
2333                 if (ent->model && ent->model->DrawDepth != NULL)
2334                         ent->model->DrawDepth(ent);
2335         }
2336 }
2337
2338 static void R_DrawModelsDebug(void)
2339 {
2340         int i;
2341         entity_render_t *ent;
2342
2343         if (!r_drawentities.integer)
2344                 return;
2345
2346         for (i = 0;i < r_refdef.scene.numentities;i++)
2347         {
2348                 if (!r_refdef.viewcache.entityvisible[i])
2349                         continue;
2350                 ent = r_refdef.scene.entities[i];
2351                 if (ent->model && ent->model->DrawDebug != NULL)
2352                         ent->model->DrawDebug(ent);
2353         }
2354 }
2355
2356 static void R_DrawModelsAddWaterPlanes(void)
2357 {
2358         int i;
2359         entity_render_t *ent;
2360
2361         if (!r_drawentities.integer)
2362                 return;
2363
2364         for (i = 0;i < r_refdef.scene.numentities;i++)
2365         {
2366                 if (!r_refdef.viewcache.entityvisible[i])
2367                         continue;
2368                 ent = r_refdef.scene.entities[i];
2369                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
2370                         ent->model->DrawAddWaterPlanes(ent);
2371         }
2372 }
2373
2374 static void R_View_SetFrustum(void)
2375 {
2376         int i;
2377         double slopex, slopey;
2378
2379         // break apart the view matrix into vectors for various purposes
2380         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
2381         VectorNegate(r_refdef.view.left, r_refdef.view.right);
2382
2383 #if 0
2384         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
2385         r_refdef.view.frustum[0].normal[1] = 0 - 0;
2386         r_refdef.view.frustum[0].normal[2] = -1 - 0;
2387         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
2388         r_refdef.view.frustum[1].normal[1] = 0 + 0;
2389         r_refdef.view.frustum[1].normal[2] = -1 + 0;
2390         r_refdef.view.frustum[2].normal[0] = 0 - 0;
2391         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
2392         r_refdef.view.frustum[2].normal[2] = -1 - 0;
2393         r_refdef.view.frustum[3].normal[0] = 0 + 0;
2394         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
2395         r_refdef.view.frustum[3].normal[2] = -1 + 0;
2396 #endif
2397
2398 #if 0
2399         zNear = r_refdef.nearclip;
2400         nudge = 1.0 - 1.0 / (1<<23);
2401         r_refdef.view.frustum[4].normal[0] = 0 - 0;
2402         r_refdef.view.frustum[4].normal[1] = 0 - 0;
2403         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
2404         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
2405         r_refdef.view.frustum[5].normal[0] = 0 + 0;
2406         r_refdef.view.frustum[5].normal[1] = 0 + 0;
2407         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
2408         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
2409 #endif
2410
2411
2412
2413 #if 0
2414         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
2415         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
2416         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
2417         r_refdef.view.frustum[0].dist = m[15] - m[12];
2418
2419         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
2420         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
2421         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
2422         r_refdef.view.frustum[1].dist = m[15] + m[12];
2423
2424         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
2425         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
2426         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
2427         r_refdef.view.frustum[2].dist = m[15] - m[13];
2428
2429         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
2430         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
2431         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
2432         r_refdef.view.frustum[3].dist = m[15] + m[13];
2433
2434         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
2435         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
2436         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
2437         r_refdef.view.frustum[4].dist = m[15] - m[14];
2438
2439         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
2440         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
2441         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
2442         r_refdef.view.frustum[5].dist = m[15] + m[14];
2443 #endif
2444
2445         if (r_refdef.view.useperspective)
2446         {
2447                 slopex = 1.0 / r_refdef.view.frustum_x;
2448                 slopey = 1.0 / r_refdef.view.frustum_y;
2449                 VectorMA(r_refdef.view.forward, -slopex, r_refdef.view.left, r_refdef.view.frustum[0].normal);
2450                 VectorMA(r_refdef.view.forward,  slopex, r_refdef.view.left, r_refdef.view.frustum[1].normal);
2451                 VectorMA(r_refdef.view.forward, -slopey, r_refdef.view.up  , r_refdef.view.frustum[2].normal);
2452                 VectorMA(r_refdef.view.forward,  slopey, r_refdef.view.up  , r_refdef.view.frustum[3].normal);
2453                 VectorCopy(r_refdef.view.forward, r_refdef.view.frustum[4].normal);
2454
2455                 // Leaving those out was a mistake, those were in the old code, and they
2456                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
2457                 // I couldn't reproduce it after adding those normalizations. --blub
2458                 VectorNormalize(r_refdef.view.frustum[0].normal);
2459                 VectorNormalize(r_refdef.view.frustum[1].normal);
2460                 VectorNormalize(r_refdef.view.frustum[2].normal);
2461                 VectorNormalize(r_refdef.view.frustum[3].normal);
2462
2463                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
2464                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, r_refdef.view.forward, -1024 * slopex, r_refdef.view.left, -1024 * slopey, r_refdef.view.up, r_refdef.view.frustumcorner[0]);
2465                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, r_refdef.view.forward,  1024 * slopex, r_refdef.view.left, -1024 * slopey, r_refdef.view.up, r_refdef.view.frustumcorner[1]);
2466                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, r_refdef.view.forward, -1024 * slopex, r_refdef.view.left,  1024 * slopey, r_refdef.view.up, r_refdef.view.frustumcorner[2]);
2467                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, r_refdef.view.forward,  1024 * slopex, r_refdef.view.left,  1024 * slopey, r_refdef.view.up, r_refdef.view.frustumcorner[3]);
2468
2469                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
2470                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
2471                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
2472                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
2473                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
2474         }
2475         else
2476         {
2477                 VectorScale(r_refdef.view.left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
2478                 VectorScale(r_refdef.view.left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
2479                 VectorScale(r_refdef.view.up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
2480                 VectorScale(r_refdef.view.up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
2481                 VectorCopy(r_refdef.view.forward, r_refdef.view.frustum[4].normal);
2482                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
2483                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
2484                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
2485                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
2486                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
2487         }
2488         r_refdef.view.numfrustumplanes = 5;
2489
2490         if (r_refdef.view.useclipplane)
2491         {
2492                 r_refdef.view.numfrustumplanes = 6;
2493                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
2494         }
2495
2496         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
2497                 PlaneClassify(r_refdef.view.frustum + i);
2498
2499         // LordHavoc: note to all quake engine coders, Quake had a special case
2500         // for 90 degrees which assumed a square view (wrong), so I removed it,
2501         // Quake2 has it disabled as well.
2502
2503         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
2504         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, r_refdef.view.up, r_refdef.view.forward, -(90 - r_refdef.fov_x / 2));
2505         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
2506         //PlaneClassify(&frustum[0]);
2507
2508         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
2509         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, r_refdef.view.up, r_refdef.view.forward, (90 - r_refdef.fov_x / 2));
2510         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
2511         //PlaneClassify(&frustum[1]);
2512
2513         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
2514         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, r_refdef.view.left, r_refdef.view.forward, -(90 - r_refdef.fov_y / 2));
2515         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
2516         //PlaneClassify(&frustum[2]);
2517
2518         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
2519         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, r_refdef.view.left, r_refdef.view.forward, (90 - r_refdef.fov_y / 2));
2520         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
2521         //PlaneClassify(&frustum[3]);
2522
2523         // nearclip plane
2524         //VectorCopy(r_refdef.view.forward, r_refdef.view.frustum[4].normal);
2525         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
2526         //PlaneClassify(&frustum[4]);
2527 }
2528
2529 void R_View_Update(void)
2530 {
2531         R_View_SetFrustum();
2532         R_View_WorldVisibility(r_refdef.view.useclipplane);
2533         R_View_UpdateEntityVisible();
2534 }
2535
2536 void R_SetupView(void)
2537 {
2538         if (!r_refdef.view.useperspective)
2539                 GL_SetupView_Mode_Ortho(-r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip);
2540         else if (r_refdef.rtworldshadows || r_refdef.rtdlightshadows)
2541                 GL_SetupView_Mode_PerspectiveInfiniteFarClip(r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip);
2542         else
2543                 GL_SetupView_Mode_Perspective(r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip);
2544
2545         GL_SetupView_Orientation_FromEntity(&r_refdef.view.matrix);
2546
2547         if (r_refdef.view.useclipplane)
2548         {
2549                 // LordHavoc: couldn't figure out how to make this approach the
2550                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
2551                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
2552                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
2553                         dist = r_refdef.view.clipplane.dist;
2554                 GL_SetupView_ApplyCustomNearClipPlane(r_refdef.view.clipplane.normal[0], r_refdef.view.clipplane.normal[1], r_refdef.view.clipplane.normal[2], dist);
2555         }
2556 }
2557
2558 void R_ResetViewRendering2D(void)
2559 {
2560         if (gl_support_fragment_shader)
2561         {
2562                 qglUseProgramObjectARB(0);CHECKGLERROR
2563         }
2564
2565         DrawQ_Finish();
2566
2567         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
2568         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2569         GL_SetupView_Mode_Ortho(0, 0, 1, 1, -10, 100);
2570         GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
2571         GL_Color(1, 1, 1, 1);
2572         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2573         GL_BlendFunc(GL_ONE, GL_ZERO);
2574         GL_AlphaTest(false);
2575         GL_ScissorTest(false);
2576         GL_DepthMask(false);
2577         GL_DepthRange(0, 1);
2578         GL_DepthTest(false);
2579         R_Mesh_Matrix(&identitymatrix);
2580         R_Mesh_ResetTextureState();
2581         GL_PolygonOffset(0, 0);
2582         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
2583         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2584         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2585         qglStencilMask(~0);CHECKGLERROR
2586         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
2587         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2588         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
2589 }
2590
2591 void R_ResetViewRendering3D(void)
2592 {
2593         if (gl_support_fragment_shader)
2594         {
2595                 qglUseProgramObjectARB(0);CHECKGLERROR
2596         }
2597
2598         DrawQ_Finish();
2599
2600         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
2601         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2602         R_SetupView();
2603         GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
2604         GL_Color(1, 1, 1, 1);
2605         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2606         GL_BlendFunc(GL_ONE, GL_ZERO);
2607         GL_AlphaTest(false);
2608         GL_ScissorTest(true);
2609         GL_DepthMask(true);
2610         GL_DepthRange(0, 1);
2611         GL_DepthTest(true);
2612         R_Mesh_Matrix(&identitymatrix);
2613         R_Mesh_ResetTextureState();
2614         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
2615         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
2616         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2617         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2618         qglStencilMask(~0);CHECKGLERROR
2619         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
2620         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2621         GL_CullFace(r_refdef.view.cullface_back);
2622 }
2623
2624 /*
2625         R_Bloom_SetupShader(
2626 "// bloom shader\n"
2627 "// written by Forest 'LordHavoc' Hale\n"
2628 "\n"
2629 "// common definitions between vertex shader and fragment shader:\n"
2630 "\n"
2631 "#ifdef __GLSL_CG_DATA_TYPES\n"
2632 "#define myhalf half\n"
2633 "#define myhalf2 half2\n"
2634 "#define myhalf3 half3\n"
2635 "#define myhalf4 half4\n"
2636 "#else\n"
2637 "#define myhalf float\n"
2638 "#define myhalf2 vec2\n"
2639 "#define myhalf3 vec3\n"
2640 "#define myhalf4 vec4\n"
2641 "#endif\n"
2642 "\n"
2643 "varying vec2 ScreenTexCoord;\n"
2644 "varying vec2 BloomTexCoord;\n"
2645 "\n"
2646 "\n"
2647 "\n"
2648 "\n"
2649 "// vertex shader specific:\n"
2650 "#ifdef VERTEX_SHADER\n"
2651 "\n"
2652 "void main(void)\n"
2653 "{\n"
2654 "       ScreenTexCoord = vec2(gl_MultiTexCoord0);\n"
2655 "       BloomTexCoord = vec2(gl_MultiTexCoord1);\n"
2656 "       // transform vertex to camera space, using ftransform to match non-VS\n"
2657 "       // rendering\n"
2658 "       gl_Position = ftransform();\n"
2659 "}\n"
2660 "\n"
2661 "#endif // VERTEX_SHADER\n"
2662 "\n"
2663 "\n"
2664 "\n"
2665 "\n"
2666 "// fragment shader specific:\n"
2667 "#ifdef FRAGMENT_SHADER\n"
2668 "\n"
2669 "void main(void)\n"
2670 "{\n"
2671 "       int x, y;
2672 "       myhalf3 color = myhalf3(texture2D(Texture_Screen, ScreenTexCoord));\n"
2673 "       for (x = -BLUR_X;x <= BLUR_X;x++)
2674 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2675 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2676 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2677 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2678
2679 "       gl_FragColor = vec4(color);\n"
2680 "}\n"
2681 "\n"
2682 "#endif // FRAGMENT_SHADER\n"
2683 */
2684
2685 void R_RenderScene(qboolean addwaterplanes);
2686
2687 static void R_Water_StartFrame(void)
2688 {
2689         int i;
2690         int waterwidth, waterheight, texturewidth, textureheight;
2691         r_waterstate_waterplane_t *p;
2692
2693         // set waterwidth and waterheight to the water resolution that will be
2694         // used (often less than the screen resolution for faster rendering)
2695         waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
2696         waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
2697
2698         // calculate desired texture sizes
2699         // can't use water if the card does not support the texture size
2700         if (!r_water.integer || !r_glsl.integer || !gl_support_fragment_shader || waterwidth > gl_max_texture_size || waterheight > gl_max_texture_size)
2701                 texturewidth = textureheight = waterwidth = waterheight = 0;
2702         else if (gl_support_arb_texture_non_power_of_two)
2703         {
2704                 texturewidth = waterwidth;
2705                 textureheight = waterheight;
2706         }
2707         else
2708         {
2709                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
2710                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
2711         }
2712
2713         // allocate textures as needed
2714         if (r_waterstate.waterwidth != waterwidth || r_waterstate.waterheight != waterheight || r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight)
2715         {
2716                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
2717                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
2718                 {
2719                         if (p->texture_refraction)
2720                                 R_FreeTexture(p->texture_refraction);
2721                         p->texture_refraction = NULL;
2722                         if (p->texture_reflection)
2723                                 R_FreeTexture(p->texture_reflection);
2724                         p->texture_reflection = NULL;
2725                 }
2726                 memset(&r_waterstate, 0, sizeof(r_waterstate));
2727                 r_waterstate.waterwidth = waterwidth;
2728                 r_waterstate.waterheight = waterheight;
2729                 r_waterstate.texturewidth = texturewidth;
2730                 r_waterstate.textureheight = textureheight;
2731         }
2732
2733         if (r_waterstate.waterwidth)
2734         {
2735                 r_waterstate.enabled = true;
2736
2737                 // set up variables that will be used in shader setup
2738                 r_waterstate.screenscale[0] = 0.5f * (float)waterwidth / (float)texturewidth;
2739                 r_waterstate.screenscale[1] = 0.5f * (float)waterheight / (float)textureheight;
2740                 r_waterstate.screencenter[0] = 0.5f * (float)waterwidth / (float)texturewidth;
2741                 r_waterstate.screencenter[1] = 0.5f * (float)waterheight / (float)textureheight;
2742         }
2743
2744         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
2745         r_waterstate.numwaterplanes = 0;
2746 }
2747
2748 static void R_Water_AddWaterPlane(msurface_t *surface)
2749 {
2750         int triangleindex, planeindex;
2751         const int *e;
2752         vec3_t vert[3];
2753         vec3_t normal;
2754         vec3_t center;
2755         r_waterstate_waterplane_t *p;
2756         // just use the first triangle with a valid normal for any decisions
2757         VectorClear(normal);
2758         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2759         {
2760                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
2761                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
2762                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
2763                 TriangleNormal(vert[0], vert[1], vert[2], normal);
2764                 if (VectorLength2(normal) >= 0.001)
2765                         break;
2766         }
2767
2768         // find a matching plane if there is one
2769         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2770                 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
2771                         break;
2772         if (planeindex >= r_waterstate.maxwaterplanes)
2773                 return; // nothing we can do, out of planes
2774
2775         // if this triangle does not fit any known plane rendered this frame, add one
2776         if (planeindex >= r_waterstate.numwaterplanes)
2777         {
2778                 // store the new plane
2779                 r_waterstate.numwaterplanes++;
2780                 VectorCopy(normal, p->plane.normal);
2781                 VectorNormalize(p->plane.normal);
2782                 p->plane.dist = DotProduct(vert[0], p->plane.normal);
2783                 PlaneClassify(&p->plane);
2784                 // flip the plane if it does not face the viewer
2785                 if (PlaneDiff(r_refdef.view.origin, &p->plane) < 0)
2786                 {
2787                         VectorNegate(p->plane.normal, p->plane.normal);
2788                         p->plane.dist *= -1;
2789                         PlaneClassify(&p->plane);
2790                 }
2791                 // clear materialflags and pvs
2792                 p->materialflags = 0;
2793                 p->pvsvalid = false;
2794         }
2795         // merge this surface's materialflags into the waterplane
2796         p->materialflags |= surface->texture->currentframe->currentmaterialflags;
2797         // merge this surface's PVS into the waterplane
2798         VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
2799         if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
2800          && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
2801         {
2802                 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
2803                 p->pvsvalid = true;
2804         }
2805 }
2806
2807 static void R_Water_ProcessPlanes(void)
2808 {
2809         r_refdef_view_t originalview;
2810         int planeindex;
2811         r_waterstate_waterplane_t *p;
2812
2813         originalview = r_refdef.view;
2814
2815         // make sure enough textures are allocated
2816         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2817         {
2818                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
2819                 {
2820                         if (!p->texture_refraction)
2821                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2822                         if (!p->texture_refraction)
2823                                 goto error;
2824                 }
2825
2826                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
2827                 {
2828                         if (!p->texture_reflection)
2829                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2830                         if (!p->texture_reflection)
2831                                 goto error;
2832                 }
2833         }
2834
2835         // render views
2836         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2837         {
2838                 r_refdef.view.showdebug = false;
2839                 r_refdef.view.width = r_waterstate.waterwidth;
2840                 r_refdef.view.height = r_waterstate.waterheight;
2841                 r_refdef.view.useclipplane = true;
2842                 r_waterstate.renderingscene = true;
2843
2844                 // render the normal view scene and copy into texture
2845                 // (except that a clipping plane should be used to hide everything on one side of the water, and the viewer's weapon model should be omitted)
2846                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
2847                 {
2848                         r_refdef.view.clipplane = p->plane;
2849                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
2850                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
2851                         PlaneClassify(&r_refdef.view.clipplane);
2852
2853                         R_RenderScene(false);
2854
2855                         // copy view into the screen texture
2856                         R_Mesh_TexBind(0, R_GetTexture(p->texture_refraction));
2857                         GL_ActiveTexture(0);
2858                         CHECKGLERROR
2859                         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2860                 }
2861
2862                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
2863                 {
2864                         // render reflected scene and copy into texture
2865                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
2866                         r_refdef.view.clipplane = p->plane;
2867                         // reverse the cullface settings for this render
2868                         r_refdef.view.cullface_front = GL_FRONT;
2869                         r_refdef.view.cullface_back = GL_BACK;
2870                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
2871                         {
2872                                 r_refdef.view.usecustompvs = true;
2873                                 if (p->pvsvalid)
2874                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
2875                                 else
2876                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
2877                         }
2878
2879                         R_ResetViewRendering3D();
2880                         R_ClearScreen(r_refdef.fogenabled);
2881                         if (r_timereport_active)
2882                                 R_TimeReport("viewclear");
2883
2884                         R_RenderScene(false);
2885
2886                         R_Mesh_TexBind(0, R_GetTexture(p->texture_reflection));
2887                         GL_ActiveTexture(0);
2888                         CHECKGLERROR
2889                         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2890
2891                         R_ResetViewRendering3D();
2892                         R_ClearScreen(r_refdef.fogenabled);
2893                         if (r_timereport_active)
2894                                 R_TimeReport("viewclear");
2895                 }
2896
2897                 r_refdef.view = originalview;
2898                 r_refdef.view.clear = true;
2899                 r_waterstate.renderingscene = false;
2900         }
2901         return;
2902 error:
2903         r_refdef.view = originalview;
2904         r_waterstate.renderingscene = false;
2905         Cvar_SetValueQuick(&r_water, 0);
2906         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
2907         return;
2908 }
2909
2910 void R_Bloom_StartFrame(void)
2911 {
2912         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
2913
2914         // set bloomwidth and bloomheight to the bloom resolution that will be
2915         // used (often less than the screen resolution for faster rendering)
2916         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.width);
2917         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
2918         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
2919
2920         // calculate desired texture sizes
2921         if (gl_support_arb_texture_non_power_of_two)
2922         {
2923                 screentexturewidth = r_refdef.view.width;
2924                 screentextureheight = r_refdef.view.height;
2925                 bloomtexturewidth = r_bloomstate.bloomwidth;
2926                 bloomtextureheight = r_bloomstate.bloomheight;
2927         }
2928         else
2929         {
2930                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
2931                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
2932                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
2933                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
2934         }
2935
2936         if (r_hdr.integer)
2937         {
2938                 screentexturewidth = screentextureheight = 0;
2939         }
2940         else if (r_bloom.integer)
2941         {
2942         }
2943         else
2944         {
2945                 screentexturewidth = screentextureheight = 0;
2946                 bloomtexturewidth = bloomtextureheight = 0;
2947         }
2948
2949         if ((!bloomtexturewidth && !bloomtextureheight) || r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512 || screentexturewidth > gl_max_texture_size || screentextureheight > gl_max_texture_size || bloomtexturewidth > gl_max_texture_size || bloomtextureheight > gl_max_texture_size)
2950         {
2951                 // can't use bloom if the parameters are too weird
2952                 // can't use bloom if the card does not support the texture size
2953                 if (r_bloomstate.texture_screen)
2954                         R_FreeTexture(r_bloomstate.texture_screen);
2955                 if (r_bloomstate.texture_bloom)
2956                         R_FreeTexture(r_bloomstate.texture_bloom);
2957                 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2958                 return;
2959         }
2960
2961         r_bloomstate.enabled = true;
2962         r_bloomstate.hdr = r_hdr.integer != 0;
2963
2964         // allocate textures as needed
2965         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
2966         {
2967                 if (r_bloomstate.texture_screen)
2968                         R_FreeTexture(r_bloomstate.texture_screen);
2969                 r_bloomstate.texture_screen = NULL;
2970                 r_bloomstate.screentexturewidth = screentexturewidth;
2971                 r_bloomstate.screentextureheight = screentextureheight;
2972                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
2973                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2974         }
2975         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
2976         {
2977                 if (r_bloomstate.texture_bloom)
2978                         R_FreeTexture(r_bloomstate.texture_bloom);
2979                 r_bloomstate.texture_bloom = NULL;
2980                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
2981                 r_bloomstate.bloomtextureheight = bloomtextureheight;
2982                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
2983                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2984         }
2985
2986         // set up a texcoord array for the full resolution screen image
2987         // (we have to keep this around to copy back during final render)
2988         r_bloomstate.screentexcoord2f[0] = 0;
2989         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
2990         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
2991         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
2992         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
2993         r_bloomstate.screentexcoord2f[5] = 0;
2994         r_bloomstate.screentexcoord2f[6] = 0;
2995         r_bloomstate.screentexcoord2f[7] = 0;
2996
2997         // set up a texcoord array for the reduced resolution bloom image
2998         // (which will be additive blended over the screen image)
2999         r_bloomstate.bloomtexcoord2f[0] = 0;
3000         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3001         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3002         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3003         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3004         r_bloomstate.bloomtexcoord2f[5] = 0;
3005         r_bloomstate.bloomtexcoord2f[6] = 0;
3006         r_bloomstate.bloomtexcoord2f[7] = 0;
3007 }
3008
3009 void R_Bloom_CopyScreenTexture(float colorscale)
3010 {
3011         r_refdef.stats.bloom++;
3012
3013         R_ResetViewRendering2D();
3014         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3015         R_Mesh_ColorPointer(NULL, 0, 0);
3016         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
3017         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
3018
3019         // copy view into the screen texture
3020         GL_ActiveTexture(0);
3021         CHECKGLERROR
3022         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
3023         r_refdef.stats.bloom_copypixels += r_refdef.view.width * r_refdef.view.height;
3024
3025         // now scale it down to the bloom texture size
3026         CHECKGLERROR
3027         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3028         GL_BlendFunc(GL_ONE, GL_ZERO);
3029         GL_Color(colorscale, colorscale, colorscale, 1);
3030         // TODO: optimize with multitexture or GLSL
3031         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3032         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3033
3034         // we now have a bloom image in the framebuffer
3035         // copy it into the bloom image texture for later processing
3036         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3037         GL_ActiveTexture(0);
3038         CHECKGLERROR
3039         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3040         r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3041 }
3042
3043 void R_Bloom_CopyHDRTexture(void)
3044 {
3045         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3046         GL_ActiveTexture(0);
3047         CHECKGLERROR
3048         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
3049         r_refdef.stats.bloom_copypixels += r_refdef.view.width * r_refdef.view.height;
3050 }
3051
3052 void R_Bloom_MakeTexture(void)
3053 {
3054         int x, range, dir;
3055         float xoffset, yoffset, r, brighten;
3056
3057         r_refdef.stats.bloom++;
3058
3059         R_ResetViewRendering2D();
3060         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3061         R_Mesh_ColorPointer(NULL, 0, 0);
3062
3063         // we have a bloom image in the framebuffer
3064         CHECKGLERROR
3065         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3066
3067         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
3068         {
3069                 x *= 2;
3070                 r = bound(0, r_bloom_colorexponent.value / x, 1);
3071                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
3072                 GL_Color(r, r, r, 1);
3073                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3074                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3075                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3076                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3077
3078                 // copy the vertically blurred bloom view to a texture
3079                 GL_ActiveTexture(0);
3080                 CHECKGLERROR
3081                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3082                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3083         }
3084
3085         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
3086         brighten = r_bloom_brighten.value;
3087         if (r_hdr.integer)
3088                 brighten *= r_hdr_range.value;
3089         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3090         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
3091
3092         for (dir = 0;dir < 2;dir++)
3093         {
3094                 // blend on at multiple vertical offsets to achieve a vertical blur
3095                 // TODO: do offset blends using GLSL
3096                 GL_BlendFunc(GL_ONE, GL_ZERO);
3097                 for (x = -range;x <= range;x++)
3098                 {
3099                         if (!dir){xoffset = 0;yoffset = x;}
3100                         else {xoffset = x;yoffset = 0;}
3101                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
3102                         yoffset /= (float)r_bloomstate.bloomtextureheight;
3103                         // compute a texcoord array with the specified x and y offset
3104                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
3105                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3106                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3107                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3108                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3109                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
3110                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
3111                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
3112                         // this r value looks like a 'dot' particle, fading sharply to
3113                         // black at the edges
3114                         // (probably not realistic but looks good enough)
3115                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
3116                         //r = (dir ? 1.0f : brighten)/(range*2+1);
3117                         r = (dir ? 1.0f : brighten)/(range*2+1)*(1 - x*x/(float)(range*range));
3118                         GL_Color(r, r, r, 1);
3119                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3120                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3121                         GL_BlendFunc(GL_ONE, GL_ONE);
3122                 }
3123
3124                 // copy the vertically blurred bloom view to a texture
3125                 GL_ActiveTexture(0);
3126                 CHECKGLERROR
3127                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3128                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3129         }
3130
3131         // apply subtract last
3132         // (just like it would be in a GLSL shader)
3133         if (r_bloom_colorsubtract.value > 0 && gl_support_ext_blend_subtract)
3134         {
3135                 GL_BlendFunc(GL_ONE, GL_ZERO);
3136                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3137                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3138                 GL_Color(1, 1, 1, 1);
3139                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3140                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3141
3142                 GL_BlendFunc(GL_ONE, GL_ONE);
3143                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
3144                 R_Mesh_TexBind(0, R_GetTexture(r_texture_white));
3145                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3146                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
3147                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3148                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3149                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
3150
3151                 // copy the darkened bloom view to a texture
3152                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3153                 GL_ActiveTexture(0);
3154                 CHECKGLERROR
3155                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3156                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3157         }
3158 }
3159
3160 void R_HDR_RenderBloomTexture(void)
3161 {
3162         int oldwidth, oldheight;
3163         float oldcolorscale;
3164
3165         oldcolorscale = r_refdef.view.colorscale;
3166         oldwidth = r_refdef.view.width;
3167         oldheight = r_refdef.view.height;
3168         r_refdef.view.width = r_bloomstate.bloomwidth;
3169         r_refdef.view.height = r_bloomstate.bloomheight;
3170
3171         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
3172         // TODO: add exposure compensation features
3173         // TODO: add fp16 framebuffer support
3174
3175         r_refdef.view.showdebug = false;
3176         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
3177
3178         R_ClearScreen(r_refdef.fogenabled);
3179         if (r_timereport_active)
3180                 R_TimeReport("HDRclear");
3181
3182         r_waterstate.numwaterplanes = 0;
3183         R_RenderScene(r_waterstate.enabled);
3184         r_refdef.view.showdebug = true;
3185
3186         R_ResetViewRendering2D();
3187
3188         R_Bloom_CopyHDRTexture();
3189         R_Bloom_MakeTexture();
3190
3191         // restore the view settings
3192         r_refdef.view.width = oldwidth;
3193         r_refdef.view.height = oldheight;
3194         r_refdef.view.colorscale = oldcolorscale;
3195
3196         R_ResetViewRendering3D();
3197
3198         R_ClearScreen(r_refdef.fogenabled);
3199         if (r_timereport_active)
3200                 R_TimeReport("viewclear");
3201 }
3202
3203 static void R_BlendView(void)
3204 {
3205         if (r_bloomstate.enabled && r_bloomstate.hdr)
3206         {
3207                 // render high dynamic range bloom effect
3208                 // the bloom texture was made earlier this render, so we just need to
3209                 // blend it onto the screen...
3210                 R_ResetViewRendering2D();
3211                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3212                 R_Mesh_ColorPointer(NULL, 0, 0);
3213                 GL_Color(1, 1, 1, 1);
3214                 GL_BlendFunc(GL_ONE, GL_ONE);
3215                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3216                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3217                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3218                 r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3219         }
3220         else if (r_bloomstate.enabled)
3221         {
3222                 // render simple bloom effect
3223                 // copy the screen and shrink it and darken it for the bloom process
3224                 R_Bloom_CopyScreenTexture(r_bloom_colorscale.value);
3225                 // make the bloom texture
3226                 R_Bloom_MakeTexture();
3227                 // put the original screen image back in place and blend the bloom
3228                 // texture on it
3229                 R_ResetViewRendering2D();
3230                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3231                 R_Mesh_ColorPointer(NULL, 0, 0);
3232                 GL_Color(1, 1, 1, 1);
3233                 GL_BlendFunc(GL_ONE, GL_ZERO);
3234                 // do both in one pass if possible
3235                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3236                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3237                 if (r_textureunits.integer >= 2 && gl_combine.integer)
3238                 {
3239                         R_Mesh_TexCombine(1, GL_ADD, GL_ADD, 1, 1);
3240                         R_Mesh_TexBind(1, R_GetTexture(r_bloomstate.texture_screen));
3241                         R_Mesh_TexCoordPointer(1, 2, r_bloomstate.screentexcoord2f, 0, 0);
3242                 }
3243                 else
3244                 {
3245                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3246                         r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3247                         // now blend on the bloom texture
3248                         GL_BlendFunc(GL_ONE, GL_ONE);
3249                         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
3250                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
3251                 }
3252                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3253                 r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3254         }
3255         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
3256         {
3257                 // apply a color tint to the whole view
3258                 R_ResetViewRendering2D();
3259                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3260                 R_Mesh_ColorPointer(NULL, 0, 0);
3261                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3262                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
3263                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3264         }
3265 }
3266
3267 void R_RenderScene(qboolean addwaterplanes);
3268
3269 matrix4x4_t r_waterscrollmatrix;
3270
3271 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
3272 {
3273         if (r_refdef.fog_density)
3274         {
3275                 r_refdef.fogcolor[0] = r_refdef.fog_red;
3276                 r_refdef.fogcolor[1] = r_refdef.fog_green;
3277                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
3278
3279                 {
3280                         vec3_t fogvec;
3281                         VectorCopy(r_refdef.fogcolor, fogvec);
3282                         if(r_glsl.integer && (r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)) // need to support contrast boost
3283                         {
3284                                 //   color.rgb /= ((ContrastBoost - 1) * color.rgb + 1);
3285                                 fogvec[0] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[0] + 1);
3286                                 fogvec[1] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[1] + 1);
3287                                 fogvec[2] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[2] + 1);
3288                         }
3289                         //   color.rgb *= ContrastBoost * SceneBrightness;
3290                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
3291                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
3292                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
3293                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
3294                 }
3295         }
3296 }
3297
3298 void R_UpdateVariables(void)
3299 {
3300         R_Textures_Frame();
3301
3302         r_refdef.farclip = 4096;
3303         if (r_refdef.scene.worldmodel)
3304                 r_refdef.farclip += VectorDistance(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3305         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
3306
3307         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
3308                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
3309         r_refdef.polygonfactor = 0;
3310         r_refdef.polygonoffset = 0;
3311         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
3312         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
3313
3314         r_refdef.rtworld = r_shadow_realtime_world.integer;
3315         r_refdef.rtworldshadows = r_shadow_realtime_world_shadows.integer && gl_stencil;
3316         r_refdef.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
3317         r_refdef.rtdlightshadows = r_refdef.rtdlight && r_shadow_realtime_dlight_shadows.integer && gl_stencil;
3318         r_refdef.lightmapintensity = r_refdef.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
3319         if (r_showsurfaces.integer)
3320         {
3321                 r_refdef.rtworld = false;
3322                 r_refdef.rtworldshadows = false;
3323                 r_refdef.rtdlight = false;
3324                 r_refdef.rtdlightshadows = false;
3325                 r_refdef.lightmapintensity = 0;
3326         }
3327
3328         if (gamemode == GAME_NEHAHRA)
3329         {
3330                 if (gl_fogenable.integer)
3331                 {
3332                         r_refdef.oldgl_fogenable = true;
3333                         r_refdef.fog_density = gl_fogdensity.value;
3334                         r_refdef.fog_red = gl_fogred.value;
3335                         r_refdef.fog_green = gl_foggreen.value;
3336                         r_refdef.fog_blue = gl_fogblue.value;
3337                         r_refdef.fog_alpha = 1;
3338                         r_refdef.fog_start = 0;
3339                         r_refdef.fog_end = gl_skyclip.value;
3340                 }
3341                 else if (r_refdef.oldgl_fogenable)
3342                 {
3343                         r_refdef.oldgl_fogenable = false;
3344                         r_refdef.fog_density = 0;
3345                         r_refdef.fog_red = 0;
3346                         r_refdef.fog_green = 0;
3347                         r_refdef.fog_blue = 0;
3348                         r_refdef.fog_alpha = 0;
3349                         r_refdef.fog_start = 0;
3350                         r_refdef.fog_end = 0;
3351                 }
3352         }
3353
3354         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
3355         r_refdef.fog_start = max(0, r_refdef.fog_start);
3356         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
3357
3358         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
3359
3360         if (r_refdef.fog_density)
3361         {
3362                 r_refdef.fogenabled = true;
3363                 // this is the point where the fog reaches 0.9986 alpha, which we
3364                 // consider a good enough cutoff point for the texture
3365                 // (0.9986 * 256 == 255.6)
3366                 if (r_fog_exp2.integer)
3367                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
3368                 else
3369                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
3370                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
3371                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
3372                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
3373                 // fog color was already set
3374                 // update the fog texture
3375                 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
3376                         R_BuildFogTexture();
3377         }
3378         else
3379                 r_refdef.fogenabled = false;
3380 }
3381
3382 /*
3383 ================
3384 R_RenderView
3385 ================
3386 */
3387 void R_RenderView(void)
3388 {
3389         if (!r_refdef.scene.entities/* || !r_refdef.scene.worldmodel*/)
3390                 return; //Host_Error ("R_RenderView: NULL worldmodel");
3391
3392         r_refdef.view.colorscale = r_hdr_scenebrightness.value;
3393
3394         R_Shadow_UpdateWorldLightSelection();
3395
3396         R_Bloom_StartFrame();
3397         R_Water_StartFrame();
3398
3399         CHECKGLERROR
3400         if (r_timereport_active)
3401                 R_TimeReport("viewsetup");
3402
3403         R_ResetViewRendering3D();
3404
3405         if (r_refdef.view.clear || r_refdef.fogenabled)
3406         {
3407                 R_ClearScreen(r_refdef.fogenabled);
3408                 if (r_timereport_active)
3409                         R_TimeReport("viewclear");
3410         }
3411         r_refdef.view.clear = true;
3412
3413         r_refdef.view.showdebug = true;
3414
3415         // this produces a bloom texture to be used in R_BlendView() later
3416         if (r_hdr.integer)
3417                 R_HDR_RenderBloomTexture();
3418
3419         r_waterstate.numwaterplanes = 0;
3420         R_RenderScene(r_waterstate.enabled);
3421
3422         R_BlendView();
3423         if (r_timereport_active)
3424                 R_TimeReport("blendview");
3425
3426         GL_Scissor(0, 0, vid.width, vid.height);
3427         GL_ScissorTest(false);
3428         CHECKGLERROR
3429 }
3430
3431 extern void R_DrawLightningBeams (void);
3432 extern void VM_CL_AddPolygonsToMeshQueue (void);
3433 extern void R_DrawPortals (void);
3434 extern cvar_t cl_locs_show;
3435 static void R_DrawLocs(void);
3436 static void R_DrawEntityBBoxes(void);
3437 void R_RenderScene(qboolean addwaterplanes)
3438 {
3439         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
3440         R_UpdateFogColor();
3441
3442         if (addwaterplanes)
3443         {
3444                 R_ResetViewRendering3D();
3445
3446                 R_View_Update();
3447                 if (r_timereport_active)
3448                         R_TimeReport("watervis");
3449
3450                 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
3451                 {
3452                         r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
3453                         if (r_timereport_active)
3454                                 R_TimeReport("waterworld");
3455                 }
3456
3457                 // don't let sound skip if going slow
3458                 if (r_refdef.scene.extraupdate)
3459                         S_ExtraUpdate ();
3460
3461                 R_DrawModelsAddWaterPlanes();
3462                 if (r_timereport_active)
3463                         R_TimeReport("watermodels");
3464
3465                 R_Water_ProcessPlanes();
3466                 if (r_timereport_active)
3467                         R_TimeReport("waterscenes");
3468         }
3469
3470         R_ResetViewRendering3D();
3471
3472         // don't let sound skip if going slow
3473         if (r_refdef.scene.extraupdate)
3474                 S_ExtraUpdate ();
3475
3476         R_MeshQueue_BeginScene();
3477
3478         R_SkyStartFrame();
3479
3480         R_View_Update();
3481         if (r_timereport_active)
3482                 R_TimeReport("visibility");
3483
3484         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
3485
3486         if (cl.csqc_vidvars.drawworld)
3487         {
3488                 // don't let sound skip if going slow
3489                 if (r_refdef.scene.extraupdate)
3490                         S_ExtraUpdate ();
3491
3492                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
3493                 {
3494                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
3495                         if (r_timereport_active)
3496                                 R_TimeReport("worldsky");
3497                 }
3498
3499                 if (R_DrawBrushModelsSky() && r_timereport_active)
3500                         R_TimeReport("bmodelsky");
3501         }
3502
3503         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
3504         {
3505                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
3506                 if (r_timereport_active)
3507                         R_TimeReport("worlddepth");
3508         }
3509         if (r_depthfirst.integer >= 2)
3510         {
3511                 R_DrawModelsDepth();
3512                 if (r_timereport_active)
3513                         R_TimeReport("modeldepth");
3514         }
3515
3516         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
3517         {
3518                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
3519                 if (r_timereport_active)
3520                         R_TimeReport("world");
3521         }
3522
3523         // don't let sound skip if going slow
3524         if (r_refdef.scene.extraupdate)
3525                 S_ExtraUpdate ();
3526
3527         R_DrawModels();
3528         if (r_timereport_active)
3529                 R_TimeReport("models");
3530
3531         // don't let sound skip if going slow
3532         if (r_refdef.scene.extraupdate)
3533                 S_ExtraUpdate ();
3534
3535         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
3536         {
3537                 R_DrawModelShadows();
3538
3539                 R_ResetViewRendering3D();
3540
3541                 // don't let sound skip if going slow
3542                 if (r_refdef.scene.extraupdate)
3543                         S_ExtraUpdate ();
3544         }
3545
3546         R_ShadowVolumeLighting(false);
3547         if (r_timereport_active)
3548                 R_TimeReport("rtlights");
3549
3550         // don't let sound skip if going slow
3551         if (r_refdef.scene.extraupdate)
3552                 S_ExtraUpdate ();
3553
3554         if (cl.csqc_vidvars.drawworld)
3555         {
3556                 R_DrawLightningBeams();
3557                 if (r_timereport_active)
3558                         R_TimeReport("lightning");
3559
3560                 R_DrawDecals();
3561                 if (r_timereport_active)
3562                         R_TimeReport("decals");
3563
3564                 R_DrawParticles();
3565                 if (r_timereport_active)
3566                         R_TimeReport("particles");
3567
3568                 R_DrawExplosions();
3569                 if (r_timereport_active)
3570                         R_TimeReport("explosions");
3571         }
3572
3573         if (gl_support_fragment_shader)
3574         {
3575                 qglUseProgramObjectARB(0);CHECKGLERROR
3576         }
3577         VM_CL_AddPolygonsToMeshQueue();
3578
3579         if (r_refdef.view.showdebug)
3580         {
3581                 if (cl_locs_show.integer)
3582                 {
3583                         R_DrawLocs();
3584                         if (r_timereport_active)
3585                                 R_TimeReport("showlocs");
3586                 }
3587
3588                 if (r_drawportals.integer)
3589                 {
3590                         R_DrawPortals();
3591                         if (r_timereport_active)
3592                                 R_TimeReport("portals");
3593                 }
3594
3595                 if (r_showbboxes.value > 0)
3596                 {
3597                         R_DrawEntityBBoxes();
3598                         if (r_timereport_active)
3599                                 R_TimeReport("bboxes");
3600                 }
3601         }
3602
3603         if (gl_support_fragment_shader)
3604         {
3605                 qglUseProgramObjectARB(0);CHECKGLERROR
3606         }
3607         R_MeshQueue_RenderTransparent();
3608         if (r_timereport_active)
3609                 R_TimeReport("drawtrans");
3610
3611         if (gl_support_fragment_shader)
3612         {
3613                 qglUseProgramObjectARB(0);CHECKGLERROR
3614         }
3615
3616         if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value > 0 || r_showcollisionbrushes.value > 0))
3617         {
3618                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
3619                 if (r_timereport_active)
3620                         R_TimeReport("worlddebug");
3621                 R_DrawModelsDebug();
3622                 if (r_timereport_active)
3623                         R_TimeReport("modeldebug");
3624         }
3625
3626         if (gl_support_fragment_shader)
3627         {
3628                 qglUseProgramObjectARB(0);CHECKGLERROR
3629         }
3630
3631         if (cl.csqc_vidvars.drawworld)
3632         {
3633                 R_DrawCoronas();
3634                 if (r_timereport_active)
3635                         R_TimeReport("coronas");
3636         }
3637
3638         // don't let sound skip if going slow
3639         if (r_refdef.scene.extraupdate)
3640                 S_ExtraUpdate ();
3641
3642         R_ResetViewRendering2D();
3643 }
3644
3645 static const int bboxelements[36] =
3646 {
3647         5, 1, 3, 5, 3, 7,
3648         6, 2, 0, 6, 0, 4,
3649         7, 3, 2, 7, 2, 6,
3650         4, 0, 1, 4, 1, 5,
3651         4, 5, 7, 4, 7, 6,
3652         1, 0, 2, 1, 2, 3,
3653 };
3654
3655 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
3656 {
3657         int i;
3658         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
3659         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3660         GL_DepthMask(false);
3661         GL_DepthRange(0, 1);
3662         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3663         R_Mesh_Matrix(&identitymatrix);
3664         R_Mesh_ResetTextureState();
3665
3666         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
3667         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
3668         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
3669         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
3670         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
3671         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
3672         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
3673         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
3674         R_FillColors(color4f, 8, cr, cg, cb, ca);
3675         if (r_refdef.fogenabled)
3676         {
3677                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
3678                 {
3679                         f1 = FogPoint_World(v);
3680                         f2 = 1 - f1;
3681                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
3682                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
3683                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
3684                 }
3685         }
3686         R_Mesh_VertexPointer(vertex3f, 0, 0);
3687         R_Mesh_ColorPointer(color4f, 0, 0);
3688         R_Mesh_ResetTextureState();
3689         R_Mesh_Draw(0, 8, 12, bboxelements, 0, 0);
3690 }
3691
3692 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
3693 {
3694         int i;
3695         float color[4];
3696         prvm_edict_t *edict;
3697         // this function draws bounding boxes of server entities
3698         if (!sv.active)
3699                 return;
3700         SV_VM_Begin();
3701         for (i = 0;i < numsurfaces;i++)
3702         {
3703                 edict = PRVM_EDICT_NUM(surfacelist[i]);
3704                 switch ((int)edict->fields.server->solid)
3705                 {
3706                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
3707                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
3708                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
3709                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
3710                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
3711                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
3712                 }
3713                 color[3] *= r_showbboxes.value;
3714                 color[3] = bound(0, color[3], 1);
3715                 GL_DepthTest(!r_showdisabledepthtest.integer);
3716                 GL_CullFace(r_refdef.view.cullface_front);
3717                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
3718         }
3719         SV_VM_End();
3720 }
3721
3722 static void R_DrawEntityBBoxes(void)
3723 {
3724         int i;
3725         prvm_edict_t *edict;
3726         vec3_t center;
3727         // this function draws bounding boxes of server entities
3728         if (!sv.active)
3729                 return;
3730         SV_VM_Begin();
3731         for (i = 0;i < prog->num_edicts;i++)
3732         {
3733                 edict = PRVM_EDICT_NUM(i);
3734                 if (edict->priv.server->free)
3735                         continue;
3736                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
3737                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
3738         }
3739         SV_VM_End();
3740 }
3741
3742 int nomodelelements[24] =
3743 {
3744         5, 2, 0,
3745         5, 1, 2,
3746         5, 0, 3,
3747         5, 3, 1,
3748         0, 2, 4,
3749         2, 1, 4,
3750         3, 0, 4,
3751         1, 3, 4
3752 };
3753
3754 float nomodelvertex3f[6*3] =
3755 {
3756         -16,   0,   0,
3757          16,   0,   0,
3758           0, -16,   0,
3759           0,  16,   0,
3760           0,   0, -16,
3761           0,   0,  16
3762 };
3763
3764 float nomodelcolor4f[6*4] =
3765 {
3766         0.0f, 0.0f, 0.5f, 1.0f,
3767         0.0f, 0.0f, 0.5f, 1.0f,
3768         0.0f, 0.5f, 0.0f, 1.0f,
3769         0.0f, 0.5f, 0.0f, 1.0f,
3770         0.5f, 0.0f, 0.0f, 1.0f,
3771         0.5f, 0.0f, 0.0f, 1.0f
3772 };
3773
3774 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
3775 {
3776         int i;
3777         float f1, f2, *c;
3778         float color4f[6*4];
3779         // this is only called once per entity so numsurfaces is always 1, and
3780         // surfacelist is always {0}, so this code does not handle batches
3781         R_Mesh_Matrix(&ent->matrix);
3782
3783         if (ent->flags & EF_ADDITIVE)
3784         {
3785                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
3786                 GL_DepthMask(false);
3787         }
3788         else if (ent->alpha < 1)
3789         {
3790                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3791                 GL_DepthMask(false);
3792         }
3793         else
3794         {
3795                 GL_BlendFunc(GL_ONE, GL_ZERO);
3796                 GL_DepthMask(true);
3797         }
3798         GL_DepthRange(0, (ent->flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
3799         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3800         GL_DepthTest(!(ent->effects & EF_NODEPTHTEST));
3801         GL_CullFace((ent->effects & EF_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
3802         R_Mesh_VertexPointer(nomodelvertex3f, 0, 0);
3803         if (r_refdef.fogenabled)
3804         {
3805                 vec3_t org;
3806                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
3807                 R_Mesh_ColorPointer(color4f, 0, 0);
3808                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3809                 f1 = FogPoint_World(org);
3810                 f2 = 1 - f1;
3811                 for (i = 0, c = color4f;i < 6;i++, c += 4)
3812                 {
3813                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
3814                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
3815                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
3816                         c[3] *= ent->alpha;
3817                 }
3818         }
3819         else if (ent->alpha != 1)
3820         {
3821                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
3822                 R_Mesh_ColorPointer(color4f, 0, 0);
3823                 for (i = 0, c = color4f;i < 6;i++, c += 4)
3824                         c[3] *= ent->alpha;
3825         }
3826         else
3827                 R_Mesh_ColorPointer(nomodelcolor4f, 0, 0);
3828         R_Mesh_ResetTextureState();
3829         R_Mesh_Draw(0, 6, 8, nomodelelements, 0, 0);
3830 }
3831
3832 void R_DrawNoModel(entity_render_t *ent)
3833 {
3834         vec3_t org;
3835         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3836         //if ((ent->effects & EF_ADDITIVE) || (ent->alpha < 1))
3837                 R_MeshQueue_AddTransparent(ent->effects & EF_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
3838         //else
3839         //      R_DrawNoModelCallback(ent, 0);
3840 }
3841
3842 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
3843 {
3844         vec3_t right1, right2, diff, normal;
3845
3846         VectorSubtract (org2, org1, normal);
3847
3848         // calculate 'right' vector for start
3849         VectorSubtract (r_refdef.view.origin, org1, diff);
3850         CrossProduct (normal, diff, right1);
3851         VectorNormalize (right1);
3852
3853         // calculate 'right' vector for end
3854         VectorSubtract (r_refdef.view.origin, org2, diff);
3855         CrossProduct (normal, diff, right2);
3856         VectorNormalize (right2);
3857
3858         vert[ 0] = org1[0] + width * right1[0];
3859         vert[ 1] = org1[1] + width * right1[1];
3860         vert[ 2] = org1[2] + width * right1[2];
3861         vert[ 3] = org1[0] - width * right1[0];
3862         vert[ 4] = org1[1] - width * right1[1];
3863         vert[ 5] = org1[2] - width * right1[2];
3864         vert[ 6] = org2[0] - width * right2[0];
3865         vert[ 7] = org2[1] - width * right2[1];
3866         vert[ 8] = org2[2] - width * right2[2];
3867         vert[ 9] = org2[0] + width * right2[0];
3868         vert[10] = org2[1] + width * right2[1];
3869         vert[11] = org2[2] + width * right2[2];
3870 }
3871
3872 float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
3873
3874 void R_DrawSprite(int blendfunc1, int blendfunc2, rtexture_t *texture, rtexture_t *fogtexture, qboolean depthdisable, qboolean depthshort, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2, float cr, float cg, float cb, float ca)
3875 {
3876         float fog = 1.0f;
3877         float vertex3f[12];
3878
3879         if (r_refdef.fogenabled && !depthdisable) // TODO maybe make the unfog effect a separate flag?
3880                 fog = FogPoint_World(origin);
3881
3882         R_Mesh_Matrix(&identitymatrix);
3883         GL_BlendFunc(blendfunc1, blendfunc2);
3884
3885         if(v_flipped_state)
3886         {
3887                 scalex1 = -scalex1;
3888                 scalex2 = -scalex2;
3889                 GL_CullFace(r_refdef.view.cullface_front);
3890         }
3891         else
3892                 GL_CullFace(r_refdef.view.cullface_back);
3893
3894         GL_DepthMask(false);
3895         GL_DepthRange(0, depthshort ? 0.0625 : 1);
3896         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3897         GL_DepthTest(!depthdisable);
3898
3899         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
3900         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
3901         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
3902         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
3903         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
3904         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
3905         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
3906         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
3907         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
3908         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
3909         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
3910         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
3911
3912         R_Mesh_VertexPointer(vertex3f, 0, 0);
3913         R_Mesh_ColorPointer(NULL, 0, 0);
3914         R_Mesh_ResetTextureState();
3915         R_Mesh_TexBind(0, R_GetTexture(texture));
3916         R_Mesh_TexCoordPointer(0, 2, spritetexcoord2f, 0, 0);
3917         // FIXME: fixed function path can't properly handle r_refdef.view.colorscale > 1
3918         GL_Color(cr * fog * r_refdef.view.colorscale, cg * fog * r_refdef.view.colorscale, cb * fog * r_refdef.view.colorscale, ca);
3919         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3920
3921         if (blendfunc2 == GL_ONE_MINUS_SRC_ALPHA)
3922         {
3923                 R_Mesh_TexBind(0, R_GetTexture(fogtexture));
3924                 GL_BlendFunc(blendfunc1, GL_ONE);
3925                 fog = 1 - fog;
3926                 GL_Color(r_refdef.fogcolor[0] * fog, r_refdef.fogcolor[1] * fog, r_refdef.fogcolor[2] * fog, ca);
3927                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3928         }
3929 }
3930
3931 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
3932 {
3933         int i;
3934         float *vertex3f;
3935         float v[3];
3936         VectorSet(v, x, y, z);
3937         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
3938                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
3939                         break;
3940         if (i == mesh->numvertices)
3941         {
3942                 if (mesh->numvertices < mesh->maxvertices)
3943                 {
3944                         VectorCopy(v, vertex3f);
3945                         mesh->numvertices++;
3946                 }
3947                 return mesh->numvertices;
3948         }
3949         else
3950                 return i;
3951 }
3952
3953 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
3954 {
3955         int i;
3956         int *e, element[3];
3957         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
3958         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
3959         e = mesh->element3i + mesh->numtriangles * 3;
3960         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
3961         {
3962                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
3963                 if (mesh->numtriangles < mesh->maxtriangles)
3964                 {
3965                         *e++ = element[0];
3966                         *e++ = element[1];
3967                         *e++ = element[2];
3968                         mesh->numtriangles++;
3969                 }
3970                 element[1] = element[2];
3971         }
3972 }
3973
3974 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
3975 {
3976         int i;
3977         int *e, element[3];
3978         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
3979         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
3980         e = mesh->element3i + mesh->numtriangles * 3;
3981         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
3982         {
3983                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
3984                 if (mesh->numtriangles < mesh->maxtriangles)
3985                 {
3986                         *e++ = element[0];
3987                         *e++ = element[1];
3988                         *e++ = element[2];
3989                         mesh->numtriangles++;
3990                 }
3991                 element[1] = element[2];
3992         }
3993 }
3994
3995 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
3996 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
3997 {
3998         int planenum, planenum2;
3999         int w;
4000         int tempnumpoints;
4001         mplane_t *plane, *plane2;
4002         double maxdist;
4003         double temppoints[2][256*3];
4004         // figure out how large a bounding box we need to properly compute this brush
4005         maxdist = 0;
4006         for (w = 0;w < numplanes;w++)
4007                 maxdist = max(maxdist, planes[w].dist);
4008         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
4009         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
4010         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
4011         {
4012                 w = 0;
4013                 tempnumpoints = 4;
4014                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
4015                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
4016                 {
4017                         if (planenum2 == planenum)
4018                                 continue;
4019                         PolygonD_Divide(tempnumpoints, temppoints[w], plane2->normal[0], plane2->normal[1], plane2->normal[2], plane2->dist, R_MESH_PLANE_DIST_EPSILON, 0, NULL, NULL, 256, temppoints[!w], &tempnumpoints, NULL);
4020                         w = !w;
4021                 }
4022                 if (tempnumpoints < 3)
4023                         continue;
4024                 // generate elements forming a triangle fan for this polygon
4025                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
4026         }
4027 }
4028
4029 static void R_Texture_AddLayer(texture_t *t, qboolean depthmask, int blendfunc1, int blendfunc2, texturelayertype_t type, rtexture_t *texture, const matrix4x4_t *matrix, float r, float g, float b, float a)
4030 {
4031         texturelayer_t *layer;
4032         layer = t->currentlayers + t->currentnumlayers++;
4033         layer->type = type;
4034         layer->depthmask = depthmask;
4035         layer->blendfunc1 = blendfunc1;
4036         layer->blendfunc2 = blendfunc2;
4037         layer->texture = texture;
4038         layer->texmatrix = *matrix;
4039         layer->color[0] = r * r_refdef.view.colorscale;
4040         layer->color[1] = g * r_refdef.view.colorscale;
4041         layer->color[2] = b * r_refdef.view.colorscale;
4042         layer->color[3] = a;
4043 }
4044
4045 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
4046 {
4047         double index, f;
4048         index = parms[2] + r_refdef.scene.time * parms[3];
4049         index -= floor(index);
4050         switch (func)
4051         {
4052         default:
4053         case Q3WAVEFUNC_NONE:
4054         case Q3WAVEFUNC_NOISE:
4055         case Q3WAVEFUNC_COUNT:
4056                 f = 0;
4057                 break;
4058         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
4059         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
4060         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
4061         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
4062         case Q3WAVEFUNC_TRIANGLE:
4063                 index *= 4;
4064                 f = index - floor(index);
4065                 if (index < 1)
4066                         f = f;
4067                 else if (index < 2)
4068                         f = 1 - f;
4069                 else if (index < 3)
4070                         f = -f;
4071                 else
4072                         f = -(1 - f);
4073                 break;
4074         }
4075         return (float)(parms[0] + parms[1] * f);
4076 }
4077
4078 void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
4079 {
4080         int i;
4081         model_t *model = ent->model;
4082         float f;
4083         float tcmat[12];
4084         q3shaderinfo_layer_tcmod_t *tcmod;
4085
4086         // switch to an alternate material if this is a q1bsp animated material
4087         {
4088                 texture_t *texture = t;
4089                 int s = ent->skinnum;
4090                 if ((unsigned int)s >= (unsigned int)model->numskins)
4091                         s = 0;
4092                 if (model->skinscenes)
4093                 {
4094                         if (model->skinscenes[s].framecount > 1)
4095                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
4096                         else
4097                                 s = model->skinscenes[s].firstframe;
4098                 }
4099                 if (s > 0)
4100                         t = t + s * model->num_surfaces;
4101                 if (t->animated)
4102                 {
4103                         // use an alternate animation if the entity's frame is not 0,
4104                         // and only if the texture has an alternate animation
4105                         if (ent->frame2 != 0 && t->anim_total[1])
4106                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
4107                         else
4108                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
4109                 }
4110                 texture->currentframe = t;
4111         }
4112
4113         // update currentskinframe to be a qw skin or animation frame
4114         if ((i = ent->entitynumber - 1) >= 0 && i < cl.maxclients)
4115         {
4116                 if (strcmp(r_qwskincache[i], cl.scores[i].qw_skin))
4117                 {
4118                         strlcpy(r_qwskincache[i], cl.scores[i].qw_skin, sizeof(r_qwskincache[i]));
4119                         Con_DPrintf("loading skins/%s\n", r_qwskincache[i]);
4120                         r_qwskincache_skinframe[i] = R_SkinFrame_LoadExternal(va("skins/%s", r_qwskincache[i]), TEXF_PRECACHE | (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS, developer.integer > 0);
4121                 }
4122                 t->currentskinframe = r_qwskincache_skinframe[i];
4123                 if (t->currentskinframe == NULL)
4124                         t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
4125         }
4126         else if (t->numskinframes >= 2)
4127                 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
4128         if (t->backgroundnumskinframes >= 2)
4129                 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - ent->frame2time)) % t->backgroundnumskinframes];
4130
4131         t->currentmaterialflags = t->basematerialflags;
4132         t->currentalpha = ent->alpha;
4133         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
4134         {
4135                 t->currentalpha *= r_wateralpha.value;
4136                 /*
4137                  * FIXME what is this supposed to do?
4138                 // if rendering refraction/reflection, disable transparency
4139                 if (r_waterstate.enabled && (t->currentalpha < 1 || (t->currentmaterialflags & MATERIALFLAG_ALPHA)))
4140                         t->currentmaterialflags |= MATERIALFLAG_WATERSHADER;
4141                 */
4142         }
4143         if(!r_waterstate.enabled)
4144                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION);
4145         if (!(ent->flags & RENDER_LIGHT))
4146                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
4147         else if (rsurface.modeltexcoordlightmap2f == NULL)
4148         {
4149                 // pick a model lighting mode
4150                 if (VectorLength2(ent->modellight_diffuse) >= (1.0f / 256.0f))
4151                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
4152                 else
4153                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
4154         }
4155         if (ent->effects & EF_ADDITIVE)
4156                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
4157         else if (t->currentalpha < 1)
4158                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
4159         if (ent->effects & EF_DOUBLESIDED)
4160                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
4161         if (ent->effects & EF_NODEPTHTEST)
4162                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
4163         if (ent->flags & RENDER_VIEWMODEL)
4164                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
4165         if (t->backgroundnumskinframes && !(t->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
4166                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
4167
4168         // make sure that the waterscroll matrix is used on water surfaces when
4169         // there is no tcmod
4170         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
4171                 t->currenttexmatrix = r_waterscrollmatrix;
4172
4173         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
4174         {
4175                 matrix4x4_t matrix;
4176                 switch(tcmod->tcmod)
4177                 {
4178                 case Q3TCMOD_COUNT:
4179                 case Q3TCMOD_NONE:
4180                         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
4181                                 matrix = r_waterscrollmatrix;
4182                         else
4183                                 matrix = identitymatrix;
4184                         break;
4185                 case Q3TCMOD_ENTITYTRANSLATE:
4186                         // this is used in Q3 to allow the gamecode to control texcoord
4187                         // scrolling on the entity, which is not supported in darkplaces yet.
4188                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
4189                         break;
4190                 case Q3TCMOD_ROTATE:
4191                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
4192                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
4193                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
4194                         break;
4195                 case Q3TCMOD_SCALE:
4196                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
4197                         break;
4198                 case Q3TCMOD_SCROLL:
4199                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
4200                         break;
4201                 case Q3TCMOD_STRETCH:
4202                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
4203                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
4204                         break;
4205                 case Q3TCMOD_TRANSFORM:
4206                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
4207                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
4208                         VectorSet(tcmat +  6, 0                   , 0                , 1);
4209                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
4210                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
4211                         break;
4212                 case Q3TCMOD_TURBULENT:
4213                         // this is handled in the RSurf_PrepareVertices function
4214                         matrix = identitymatrix;
4215                         break;
4216                 }
4217                 // either replace or concatenate the transformation
4218                 if (i < 1)
4219                         t->currenttexmatrix = matrix;
4220                 else
4221                 {
4222                         matrix4x4_t temp = t->currenttexmatrix;
4223                         Matrix4x4_Concat(&t->currenttexmatrix, &matrix, &temp);
4224                 }
4225         }
4226
4227         t->colormapping = VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f);
4228         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
4229         t->glosstexture = r_texture_black;
4230         t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
4231         t->backgroundglosstexture = r_texture_black;
4232         t->specularpower = r_shadow_glossexponent.value;
4233         // TODO: store reference values for these in the texture?
4234         t->specularscale = 0;
4235         if (r_shadow_gloss.integer > 0)
4236         {
4237                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
4238                 {
4239                         if (r_shadow_glossintensity.value > 0)
4240                         {
4241                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
4242                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
4243                                 t->specularscale = r_shadow_glossintensity.value;
4244                         }
4245                 }
4246                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
4247                 {
4248                         t->glosstexture = r_texture_white;
4249                         t->backgroundglosstexture = r_texture_white;
4250                         t->specularscale = r_shadow_gloss2intensity.value;
4251                 }
4252         }
4253
4254         // lightmaps mode looks bad with dlights using actual texturing, so turn
4255         // off the colormap and glossmap, but leave the normalmap on as it still
4256         // accurately represents the shading involved
4257         if (gl_lightmaps.integer && !(t->currentmaterialflags & MATERIALFLAG_BLENDED))
4258         {
4259                 t->basetexture = r_texture_white;
4260                 t->specularscale = 0;
4261         }
4262
4263         Vector4Set(t->lightmapcolor, ent->colormod[0], ent->colormod[1], ent->colormod[2], t->currentalpha);
4264         VectorClear(t->dlightcolor);
4265         t->currentnumlayers = 0;
4266         if (!(t->currentmaterialflags & MATERIALFLAG_NODRAW))
4267         {
4268                 if (!(t->currentmaterialflags & MATERIALFLAG_SKY))
4269                 {
4270                         int blendfunc1, blendfunc2, depthmask;
4271                         if (t->currentmaterialflags & MATERIALFLAG_ADD)
4272                         {
4273                                 blendfunc1 = GL_SRC_ALPHA;
4274                                 blendfunc2 = GL_ONE;
4275                         }
4276                         else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
4277                         {
4278                                 blendfunc1 = GL_SRC_ALPHA;
4279                                 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
4280                         }
4281                         else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
4282                         {
4283                                 blendfunc1 = t->customblendfunc[0];
4284                                 blendfunc2 = t->customblendfunc[1];
4285                         }
4286                         else
4287                         {
4288                                 blendfunc1 = GL_ONE;
4289                                 blendfunc2 = GL_ZERO;
4290                         }
4291                         depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
4292                         if (t->currentmaterialflags & (MATERIALFLAG_WATER | MATERIALFLAG_WALL))
4293                         {
4294                                 rtexture_t *currentbasetexture;
4295                                 int layerflags = 0;
4296                                 if (r_refdef.fogenabled && (t->currentmaterialflags & MATERIALFLAG_BLENDED))
4297                                         layerflags |= TEXTURELAYERFLAG_FOGDARKEN;
4298                                 currentbasetexture = (VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) < (1.0f / 1048576.0f) && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
4299                                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4300                                 {
4301                                         // fullbright is not affected by r_refdef.lightmapintensity
4302                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
4303                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4304                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * t->lightmapcolor[0], ent->colormap_pantscolor[1] * t->lightmapcolor[1], ent->colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4305                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4306                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * t->lightmapcolor[0], ent->colormap_shirtcolor[1] * t->lightmapcolor[1], ent->colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4307                                 }
4308                                 else
4309                                 {
4310                                         vec3_t ambientcolor;
4311                                         float colorscale;
4312                                         // set the color tint used for lights affecting this surface
4313                                         VectorSet(t->dlightcolor, ent->colormod[0] * t->lightmapcolor[3], ent->colormod[1] * t->lightmapcolor[3], ent->colormod[2] * t->lightmapcolor[3]);
4314                                         colorscale = 2;
4315                                         // q3bsp has no lightmap updates, so the lightstylevalue that
4316                                         // would normally be baked into the lightmap must be
4317                                         // applied to the color
4318                                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
4319                                         if (ent->model->type == mod_brushq3)
4320                                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
4321                                         colorscale *= r_refdef.lightmapintensity;
4322                                         VectorScale(t->lightmapcolor, r_ambient.value * (1.0f / 64.0f), ambientcolor);
4323                                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
4324                                         // basic lit geometry
4325                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, currentbasetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
4326                                         // add pants/shirt if needed
4327                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4328                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * t->lightmapcolor[0], ent->colormap_pantscolor[1] * t->lightmapcolor[1], ent->colormap_pantscolor[2]  * t->lightmapcolor[2], t->lightmapcolor[3]);
4329                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4330                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * t->lightmapcolor[0], ent->colormap_shirtcolor[1] * t->lightmapcolor[1], ent->colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4331                                         // now add ambient passes if needed
4332                                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
4333                                         {
4334                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
4335                                                 if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4336                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * ambientcolor[0], ent->colormap_pantscolor[1] * ambientcolor[1], ent->colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
4337                                                 if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4338                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * ambientcolor[0], ent->colormap_shirtcolor[1] * ambientcolor[1], ent->colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
4339                                         }
4340                                 }
4341                                 if (t->currentskinframe->glow != NULL)
4342                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->glow, &t->currenttexmatrix, r_hdr_glowintensity.value, r_hdr_glowintensity.value, r_hdr_glowintensity.value, t->lightmapcolor[3]);
4343                                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
4344                                 {
4345                                         // if this is opaque use alpha blend which will darken the earlier
4346                                         // passes cheaply.
4347                                         //
4348                                         // if this is an alpha blended material, all the earlier passes
4349                                         // were darkened by fog already, so we only need to add the fog
4350                                         // color ontop through the fog mask texture
4351                                         //
4352                                         // if this is an additive blended material, all the earlier passes
4353                                         // were darkened by fog already, and we should not add fog color
4354                                         // (because the background was not darkened, there is no fog color
4355                                         // that was lost behind it).
4356                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->currentskinframe->fog, &identitymatrix, r_refdef.fogcolor[0] / r_refdef.view.colorscale, r_refdef.fogcolor[1] / r_refdef.view.colorscale, r_refdef.fogcolor[2] / r_refdef.view.colorscale, t->lightmapcolor[3]);
4357                                 }
4358                         }
4359                 }
4360         }
4361 }
4362
4363 void R_UpdateAllTextureInfo(entity_render_t *ent)
4364 {
4365         int i;
4366         if (ent->model)
4367                 for (i = 0;i < ent->model->num_texturesperskin;i++)
4368                         R_UpdateTextureInfo(ent, ent->model->data_textures + i);
4369 }
4370
4371 rsurfacestate_t rsurface;
4372
4373 void R_Mesh_ResizeArrays(int newvertices)
4374 {
4375         float *base;
4376         if (rsurface.array_size >= newvertices)
4377                 return;
4378         if (rsurface.array_modelvertex3f)
4379                 Mem_Free(rsurface.array_modelvertex3f);
4380         rsurface.array_size = (newvertices + 1023) & ~1023;
4381         base = (float *)Mem_Alloc(r_main_mempool, rsurface.array_size * sizeof(float[33]));
4382         rsurface.array_modelvertex3f     = base + rsurface.array_size * 0;
4383         rsurface.array_modelsvector3f    = base + rsurface.array_size * 3;
4384         rsurface.array_modeltvector3f    = base + rsurface.array_size * 6;
4385         rsurface.array_modelnormal3f     = base + rsurface.array_size * 9;
4386         rsurface.array_deformedvertex3f  = base + rsurface.array_size * 12;
4387         rsurface.array_deformedsvector3f = base + rsurface.array_size * 15;
4388         rsurface.array_deformedtvector3f = base + rsurface.array_size * 18;
4389         rsurface.array_deformednormal3f  = base + rsurface.array_size * 21;
4390         rsurface.array_texcoord3f        = base + rsurface.array_size * 24;
4391         rsurface.array_color4f           = base + rsurface.array_size * 27;
4392         rsurface.array_generatedtexcoordtexture2f = base + rsurface.array_size * 31;
4393 }
4394
4395 void RSurf_CleanUp(void)
4396 {
4397         CHECKGLERROR
4398         if (rsurface.mode == RSURFMODE_GLSL)
4399         {
4400                 qglUseProgramObjectARB(0);CHECKGLERROR
4401         }
4402         GL_AlphaTest(false);
4403         rsurface.mode = RSURFMODE_NONE;
4404         rsurface.uselightmaptexture = false;
4405         rsurface.texture = NULL;
4406 }
4407
4408 void RSurf_ActiveWorldEntity(void)
4409 {
4410         model_t *model = r_refdef.scene.worldmodel;
4411         RSurf_CleanUp();
4412         if (rsurface.array_size < model->surfmesh.num_vertices)
4413                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
4414         rsurface.matrix = identitymatrix;
4415         rsurface.inversematrix = identitymatrix;
4416         R_Mesh_Matrix(&identitymatrix);
4417         VectorCopy(r_refdef.view.origin, rsurface.modelorg);
4418         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
4419         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
4420         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
4421         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
4422         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
4423         rsurface.frameblend[0].frame = 0;
4424         rsurface.frameblend[0].lerp = 1;
4425         rsurface.frameblend[1].frame = 0;
4426         rsurface.frameblend[1].lerp = 0;
4427         rsurface.frameblend[2].frame = 0;
4428         rsurface.frameblend[2].lerp = 0;
4429         rsurface.frameblend[3].frame = 0;
4430         rsurface.frameblend[3].lerp = 0;
4431         rsurface.basepolygonfactor = r_refdef.polygonfactor;
4432         rsurface.basepolygonoffset = r_refdef.polygonoffset;
4433         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
4434         rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
4435         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
4436         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
4437         rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
4438         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
4439         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
4440         rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
4441         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
4442         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
4443         rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
4444         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
4445         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
4446         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
4447         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
4448         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
4449         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
4450         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
4451         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
4452         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
4453         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
4454         rsurface.modelelement3i = model->surfmesh.data_element3i;
4455         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo;
4456         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
4457         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
4458         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
4459         rsurface.modelsurfaces = model->data_surfaces;
4460         rsurface.generatedvertex = false;
4461         rsurface.vertex3f  = rsurface.modelvertex3f;
4462         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4463         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4464         rsurface.svector3f = rsurface.modelsvector3f;
4465         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4466         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4467         rsurface.tvector3f = rsurface.modeltvector3f;
4468         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4469         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4470         rsurface.normal3f  = rsurface.modelnormal3f;
4471         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4472         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4473         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
4474 }
4475
4476 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
4477 {
4478         model_t *model = ent->model;
4479         RSurf_CleanUp();
4480         if (rsurface.array_size < model->surfmesh.num_vertices)
4481                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
4482         rsurface.matrix = ent->matrix;
4483         rsurface.inversematrix = ent->inversematrix;
4484         R_Mesh_Matrix(&rsurface.matrix);
4485         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.modelorg);
4486         rsurface.modellight_ambient[0] = ent->modellight_ambient[0] * ent->colormod[0];
4487         rsurface.modellight_ambient[1] = ent->modellight_ambient[1] * ent->colormod[1];
4488         rsurface.modellight_ambient[2] = ent->modellight_ambient[2] * ent->colormod[2];
4489         rsurface.modellight_diffuse[0] = ent->modellight_diffuse[0] * ent->colormod[0];
4490         rsurface.modellight_diffuse[1] = ent->modellight_diffuse[1] * ent->colormod[1];
4491         rsurface.modellight_diffuse[2] = ent->modellight_diffuse[2] * ent->colormod[2];
4492         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
4493         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
4494         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
4495         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
4496         rsurface.frameblend[0] = ent->frameblend[0];
4497         rsurface.frameblend[1] = ent->frameblend[1];
4498         rsurface.frameblend[2] = ent->frameblend[2];
4499         rsurface.frameblend[3] = ent->frameblend[3];
4500         rsurface.basepolygonfactor = r_refdef.polygonfactor;
4501         rsurface.basepolygonoffset = r_refdef.polygonoffset;
4502         if (ent->model->brush.submodel)
4503         {
4504                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
4505                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
4506         }
4507         if (model->surfmesh.isanimated && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].frame != 0))
4508         {
4509                 if (wanttangents)
4510                 {
4511                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4512                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
4513                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
4514                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4515                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
4516                 }
4517                 else if (wantnormals)
4518                 {
4519                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4520                         rsurface.modelsvector3f = NULL;
4521                         rsurface.modeltvector3f = NULL;
4522                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4523                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
4524                 }
4525                 else
4526                 {
4527                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4528                         rsurface.modelsvector3f = NULL;
4529                         rsurface.modeltvector3f = NULL;
4530                         rsurface.modelnormal3f = NULL;
4531                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, NULL, NULL, NULL);
4532                 }
4533                 rsurface.modelvertex3f_bufferobject = 0;
4534                 rsurface.modelvertex3f_bufferoffset = 0;
4535                 rsurface.modelsvector3f_bufferobject = 0;
4536                 rsurface.modelsvector3f_bufferoffset = 0;
4537                 rsurface.modeltvector3f_bufferobject = 0;
4538                 rsurface.modeltvector3f_bufferoffset = 0;
4539                 rsurface.modelnormal3f_bufferobject = 0;
4540                 rsurface.modelnormal3f_bufferoffset = 0;
4541                 rsurface.generatedvertex = true;
4542         }
4543         else
4544         {
4545                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
4546                 rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
4547                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
4548                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
4549                 rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
4550                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
4551                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
4552                 rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
4553                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
4554                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
4555                 rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
4556                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
4557                 rsurface.generatedvertex = false;
4558         }
4559         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
4560         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
4561         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
4562         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
4563         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
4564         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
4565         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
4566         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
4567         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
4568         rsurface.modelelement3i = model->surfmesh.data_element3i;
4569         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo;
4570         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
4571         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
4572         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
4573         rsurface.modelsurfaces = model->data_surfaces;
4574         rsurface.vertex3f  = rsurface.modelvertex3f;
4575         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4576         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4577         rsurface.svector3f = rsurface.modelsvector3f;
4578         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4579         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4580         rsurface.tvector3f = rsurface.modeltvector3f;
4581         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4582         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4583         rsurface.normal3f  = rsurface.modelnormal3f;
4584         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4585         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4586         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
4587 }
4588
4589 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
4590 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, msurface_t **texturesurfacelist)
4591 {
4592         int deformindex;
4593         int texturesurfaceindex;
4594         int i, j;
4595         float amplitude;
4596         float animpos;
4597         float scale;
4598         const float *v1, *in_tc;
4599         float *out_tc;
4600         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
4601         float waveparms[4];
4602         q3shaderinfo_deform_t *deform;
4603         // if vertices are dynamic (animated models), generate them into the temporary rsurface.array_model* arrays and point rsurface.model* at them instead of the static data from the model itself
4604         if (rsurface.generatedvertex)
4605         {
4606                 if (rsurface.texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
4607                         generatenormals = true;
4608                 for (i = 0;i < Q3MAXDEFORMS;i++)
4609                 {
4610                         if (rsurface.texture->deforms[i].deform == Q3DEFORM_AUTOSPRITE)
4611                         {
4612                                 generatetangents = true;
4613                                 generatenormals = true;
4614                         }
4615                         if (rsurface.texture->deforms[i].deform != Q3DEFORM_NONE)
4616                                 generatenormals = true;
4617                 }
4618                 if (generatenormals && !rsurface.modelnormal3f)
4619                 {
4620                         rsurface.normal3f = rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4621                         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject = 0;
4622                         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset = 0;
4623                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer);
4624                 }
4625                 if (generatetangents && !rsurface.modelsvector3f)
4626                 {
4627                         rsurface.svector3f = rsurface.modelsvector3f = rsurface.array_modelsvector3f;
4628                         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject = 0;
4629                         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset = 0;
4630                         rsurface.tvector3f = rsurface.modeltvector3f = rsurface.array_modeltvector3f;
4631                         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject = 0;
4632                         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset = 0;
4633                         Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f, r_smoothnormals_areaweighting.integer);
4634                 }
4635         }
4636         rsurface.vertex3f  = rsurface.modelvertex3f;
4637         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4638         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4639         rsurface.svector3f = rsurface.modelsvector3f;
4640         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4641         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4642         rsurface.tvector3f = rsurface.modeltvector3f;
4643         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4644         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4645         rsurface.normal3f  = rsurface.modelnormal3f;
4646         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4647         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4648         // if vertices are deformed (sprite flares and things in maps, possibly
4649         // water waves, bulges and other deformations), generate them into
4650         // rsurface.deform* arrays from whatever the rsurface.* arrays point to
4651         // (may be static model data or generated data for an animated model, or
4652         //  the previous deform pass)
4653         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
4654         {
4655                 switch (deform->deform)
4656                 {
4657                 default:
4658                 case Q3DEFORM_PROJECTIONSHADOW:
4659                 case Q3DEFORM_TEXT0:
4660                 case Q3DEFORM_TEXT1:
4661                 case Q3DEFORM_TEXT2:
4662                 case Q3DEFORM_TEXT3:
4663                 case Q3DEFORM_TEXT4:
4664                 case Q3DEFORM_TEXT5:
4665                 case Q3DEFORM_TEXT6:
4666                 case Q3DEFORM_TEXT7:
4667                 case Q3DEFORM_NONE:
4668                         break;
4669                 case Q3DEFORM_AUTOSPRITE:
4670                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
4671                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
4672                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
4673                         VectorNormalize(newforward);
4674                         VectorNormalize(newright);
4675                         VectorNormalize(newup);
4676                         // make deformed versions of only the model vertices used by the specified surfaces
4677                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4678                         {
4679                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4680                                 // a single autosprite surface can contain multiple sprites...
4681                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
4682                                 {
4683                                         VectorClear(center);
4684                                         for (i = 0;i < 4;i++)
4685                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
4686                                         VectorScale(center, 0.25f, center);
4687                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, forward);
4688                                         VectorCopy((rsurface.svector3f + 3 * surface->num_firstvertex) + j*3, right);
4689                                         VectorCopy((rsurface.tvector3f + 3 * surface->num_firstvertex) + j*3, up);
4690                                         for (i = 0;i < 4;i++)
4691                                         {
4692                                                 VectorSubtract((rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i)*3, center, v);
4693                                                 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
4694                                         }
4695                                 }
4696                                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformednormal3f, r_smoothnormals_areaweighting.integer);
4697                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4698                         }
4699                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4700                         rsurface.vertex3f_bufferobject = 0;
4701                         rsurface.vertex3f_bufferoffset = 0;
4702                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4703                         rsurface.svector3f_bufferobject = 0;
4704                         rsurface.svector3f_bufferoffset = 0;
4705                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4706                         rsurface.tvector3f_bufferobject = 0;
4707                         rsurface.tvector3f_bufferoffset = 0;
4708                         rsurface.normal3f = rsurface.array_deformednormal3f;
4709                         rsurface.normal3f_bufferobject = 0;
4710                         rsurface.normal3f_bufferoffset = 0;
4711                         break;
4712                 case Q3DEFORM_AUTOSPRITE2:
4713                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
4714                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
4715                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
4716                         VectorNormalize(newforward);
4717                         VectorNormalize(newright);
4718                         VectorNormalize(newup);
4719                         // make deformed versions of only the model vertices used by the specified surfaces
4720                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4721                         {
4722                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4723                                 const float *v1, *v2;
4724                                 vec3_t start, end;
4725                                 float f, l;
4726                                 struct
4727                                 {
4728                                         float length2;
4729                                         const float *v1;
4730                                         const float *v2;
4731                                 }
4732                                 shortest[2];
4733                                 memset(shortest, 0, sizeof(shortest));
4734                                 // a single autosprite surface can contain multiple sprites...
4735                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
4736                                 {
4737                                         VectorClear(center);
4738                                         for (i = 0;i < 4;i++)
4739                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
4740                                         VectorScale(center, 0.25f, center);
4741                                         // find the two shortest edges, then use them to define the
4742                                         // axis vectors for rotating around the central axis
4743                                         for (i = 0;i < 6;i++)
4744                                         {
4745                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][0]);
4746                                                 v2 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][1]);
4747 #if 0
4748                                                 Debug_PolygonBegin(NULL, 0, false, 0);
4749                                                 Debug_PolygonVertex(v1[0], v1[1], v1[2], 0, 0, 1, 0, 0, 1);
4750                                                 Debug_PolygonVertex((v1[0] + v2[0]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 4, (v1[1] + v2[1]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1], (v1[2] + v2[2]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2], 0, 0, 1, 1, 0, 1);
4751                                                 Debug_PolygonVertex(v2[0], v2[1], v2[2], 0, 0, 1, 0, 0, 1);
4752                                                 Debug_PolygonEnd();
4753 #endif
4754                                                 l = VectorDistance2(v1, v2);
4755                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
4756                                                 if (v1[2] != v2[2])
4757                                                         l += (1.0f / 1024.0f);
4758                                                 if (shortest[0].length2 > l || i == 0)
4759                                                 {
4760                                                         shortest[1] = shortest[0];
4761                                                         shortest[0].length2 = l;
4762                                                         shortest[0].v1 = v1;
4763                                                         shortest[0].v2 = v2;
4764                                                 }
4765                                                 else if (shortest[1].length2 > l || i == 1)
4766                                                 {
4767                                                         shortest[1].length2 = l;
4768                                                         shortest[1].v1 = v1;
4769                                                         shortest[1].v2 = v2;
4770                                                 }
4771                                         }
4772                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
4773                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
4774 #if 0
4775                                         Debug_PolygonBegin(NULL, 0, false, 0);
4776                                         Debug_PolygonVertex(start[0], start[1], start[2], 0, 0, 1, 1, 0, 1);
4777                                         Debug_PolygonVertex(center[0] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 4, center[1] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1] * 4, center[2] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2] * 4, 0, 0, 0, 1, 0, 1);
4778                                         Debug_PolygonVertex(end[0], end[1], end[2], 0, 0, 0, 1, 1, 1);
4779                                         Debug_PolygonEnd();
4780 #endif
4781                                         // this calculates the right vector from the shortest edge
4782                                         // and the up vector from the edge midpoints
4783                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
4784                                         VectorNormalize(right);
4785                                         VectorSubtract(end, start, up);
4786                                         VectorNormalize(up);
4787                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
4788                                         //VectorSubtract(rsurface.modelorg, center, forward);
4789                                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
4790                                         VectorNegate(forward, forward);
4791                                         VectorReflect(forward, 0, up, forward);
4792                                         VectorNormalize(forward);
4793                                         CrossProduct(up, forward, newright);
4794                                         VectorNormalize(newright);
4795 #if 0
4796                                         Debug_PolygonBegin(NULL, 0, false, 0);
4797                                         Debug_PolygonVertex(center[0] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 8, center[1] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1] * 8, center[2] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2] * 8, 0, 0, 1, 0, 0, 1);
4798                                         Debug_PolygonVertex(center[0] + right[0] * 8, center[1] + right[1] * 8, center[2] + right[2] * 8, 0, 0, 0, 1, 0, 1);
4799                                         Debug_PolygonVertex(center[0] + up   [0] * 8, center[1] + up   [1] * 8, center[2] + up   [2] * 8, 0, 0, 0, 0, 1, 1);
4800                                         Debug_PolygonEnd();
4801 #endif
4802 #if 0
4803                                         Debug_PolygonBegin(NULL, 0, false, 0);
4804                                         Debug_PolygonVertex(center[0] + forward [0] * 8, center[1] + forward [1] * 8, center[2] + forward [2] * 8, 0, 0, 1, 0, 0, 1);
4805                                         Debug_PolygonVertex(center[0] + newright[0] * 8, center[1] + newright[1] * 8, center[2] + newright[2] * 8, 0, 0, 0, 1, 0, 1);
4806                                         Debug_PolygonVertex(center[0] + up      [0] * 8, center[1] + up      [1] * 8, center[2] + up      [2] * 8, 0, 0, 0, 0, 1, 1);
4807                                         Debug_PolygonEnd();
4808 #endif
4809                                         // rotate the quad around the up axis vector, this is made
4810                                         // especially easy by the fact we know the quad is flat,
4811                                         // so we only have to subtract the center position and
4812                                         // measure distance along the right vector, and then
4813                                         // multiply that by the newright vector and add back the
4814                                         // center position
4815                                         // we also need to subtract the old position to undo the
4816                                         // displacement from the center, which we do with a
4817                                         // DotProduct, the subtraction/addition of center is also
4818                                         // optimized into DotProducts here
4819                                         l = DotProduct(right, center);
4820                                         for (i = 0;i < 4;i++)
4821                                         {
4822                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + j + i);
4823                                                 f = DotProduct(right, v1) - l;
4824                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
4825                                         }
4826                                 }
4827                                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformednormal3f, r_smoothnormals_areaweighting.integer);
4828                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4829                         }
4830                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4831                         rsurface.vertex3f_bufferobject = 0;
4832                         rsurface.vertex3f_bufferoffset = 0;
4833                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4834                         rsurface.svector3f_bufferobject = 0;
4835                         rsurface.svector3f_bufferoffset = 0;
4836                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4837                         rsurface.tvector3f_bufferobject = 0;
4838                         rsurface.tvector3f_bufferoffset = 0;
4839                         rsurface.normal3f = rsurface.array_deformednormal3f;
4840                         rsurface.normal3f_bufferobject = 0;
4841                         rsurface.normal3f_bufferoffset = 0;
4842                         break;
4843                 case Q3DEFORM_NORMAL:
4844                         // deform the normals to make reflections wavey
4845                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4846                         {
4847                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4848                                 for (j = 0;j < surface->num_vertices;j++)
4849                                 {
4850                                         float vertex[3];
4851                                         float *normal = (rsurface.array_deformednormal3f  + 3 * surface->num_firstvertex) + j*3;
4852                                         VectorScale((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, 0.98f, vertex);
4853                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, normal);
4854                                         normal[0] += deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4855                                         normal[1] += deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4856                                         normal[2] += deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4857                                         VectorNormalize(normal);
4858                                 }
4859                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4860                         }
4861                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4862                         rsurface.svector3f_bufferobject = 0;
4863                         rsurface.svector3f_bufferoffset = 0;
4864                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4865                         rsurface.tvector3f_bufferobject = 0;
4866                         rsurface.tvector3f_bufferoffset = 0;
4867                         rsurface.normal3f = rsurface.array_deformednormal3f;
4868                         rsurface.normal3f_bufferobject = 0;
4869                         rsurface.normal3f_bufferoffset = 0;
4870                         break;
4871                 case Q3DEFORM_WAVE:
4872                         // deform vertex array to make wavey water and flags and such
4873                         waveparms[0] = deform->waveparms[0];
4874                         waveparms[1] = deform->waveparms[1];
4875                         waveparms[2] = deform->waveparms[2];
4876                         waveparms[3] = deform->waveparms[3];
4877                         // this is how a divisor of vertex influence on deformation
4878                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
4879                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
4880                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4881                         {
4882                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4883                                 for (j = 0;j < surface->num_vertices;j++)
4884                                 {
4885                                         float *vertex = (rsurface.array_deformedvertex3f  + 3 * surface->num_firstvertex) + j*3;
4886                                         VectorCopy((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, vertex);
4887                                         // if the wavefunc depends on time, evaluate it per-vertex
4888                                         if (waveparms[3])
4889                                         {
4890                                                 waveparms[2] = deform->waveparms[2] + (vertex[0] + vertex[1] + vertex[2]) * animpos;
4891                                                 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
4892                                         }
4893                                         VectorMA(vertex, scale, (rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, vertex);
4894                                 }
4895                         }
4896                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4897                         rsurface.vertex3f_bufferobject = 0;
4898                         rsurface.vertex3f_bufferoffset = 0;
4899                         break;
4900                 case Q3DEFORM_BULGE:
4901                         // deform vertex array to make the surface have moving bulges
4902                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4903                         {
4904                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4905                                 for (j = 0;j < surface->num_vertices;j++)
4906                                 {
4907                                         scale = sin((rsurface.modeltexcoordtexture2f[2 * (surface->num_firstvertex + j)] * deform->parms[0] + r_refdef.scene.time * deform->parms[2])) * deform->parms[1];
4908                                         VectorMA(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), scale, rsurface.normal3f + 3 * (surface->num_firstvertex + j), rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
4909                                 }
4910                         }
4911                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4912                         rsurface.vertex3f_bufferobject = 0;
4913                         rsurface.vertex3f_bufferoffset = 0;
4914                         break;
4915                 case Q3DEFORM_MOVE:
4916                         // deform vertex array
4917                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
4918                         VectorScale(deform->parms, scale, waveparms);
4919                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4920                         {
4921                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4922                                 for (j = 0;j < surface->num_vertices;j++)
4923                                         VectorAdd(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), waveparms, rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
4924                         }
4925                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4926                         rsurface.vertex3f_bufferobject = 0;
4927                         rsurface.vertex3f_bufferoffset = 0;
4928                         break;
4929                 }
4930         }
4931         // generate texcoords based on the chosen texcoord source
4932         switch(rsurface.texture->tcgen.tcgen)
4933         {
4934         default:
4935         case Q3TCGEN_TEXTURE:
4936                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordtexture2f;
4937                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordtexture2f_bufferobject;
4938                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
4939                 break;
4940         case Q3TCGEN_LIGHTMAP:
4941                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordlightmap2f;
4942                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordlightmap2f_bufferobject;
4943                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordlightmap2f_bufferoffset;
4944                 break;
4945         case Q3TCGEN_VECTOR:
4946                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4947                 {
4948                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4949                         for (j = 0, v1 = rsurface.modelvertex3f + 3 * surface->num_firstvertex, out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;j < surface->num_vertices;j++, v1 += 3, out_tc += 2)
4950                         {
4951                                 out_tc[0] = DotProduct(v1, rsurface.texture->tcgen.parms);
4952                                 out_tc[1] = DotProduct(v1, rsurface.texture->tcgen.parms + 3);
4953                         }
4954                 }
4955                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
4956                 rsurface.texcoordtexture2f_bufferobject  = 0;
4957                 rsurface.texcoordtexture2f_bufferoffset  = 0;
4958                 break;
4959         case Q3TCGEN_ENVIRONMENT:
4960                 // make environment reflections using a spheremap
4961                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4962                 {
4963                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4964                         const float *vertex = rsurface.modelvertex3f + 3 * surface->num_firstvertex;
4965                         const float *normal = rsurface.modelnormal3f + 3 * surface->num_firstvertex;
4966                         float *out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;
4967                         for (j = 0;j < surface->num_vertices;j++, vertex += 3, normal += 3, out_tc += 2)
4968                         {
4969                                 float l, d, eyedir[3];
4970                                 VectorSubtract(rsurface.modelorg, vertex, eyedir);
4971                                 l = 0.5f / VectorLength(eyedir);
4972                                 d = DotProduct(normal, eyedir)*2;
4973                                 out_tc[0] = 0.5f + (normal[1]*d - eyedir[1])*l;
4974                                 out_tc[1] = 0.5f - (normal[2]*d - eyedir[2])*l;
4975                         }
4976                 }
4977                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
4978                 rsurface.texcoordtexture2f_bufferobject  = 0;
4979                 rsurface.texcoordtexture2f_bufferoffset  = 0;
4980                 break;
4981         }
4982         // the only tcmod that needs software vertex processing is turbulent, so
4983         // check for it here and apply the changes if needed
4984         // and we only support that as the first one
4985         // (handling a mixture of turbulent and other tcmods would be problematic
4986         //  without punting it entirely to a software path)
4987         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
4988         {
4989                 amplitude = rsurface.texture->tcmods[0].parms[1];
4990                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
4991                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4992                 {
4993                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4994                         for (j = 0, v1 = rsurface.modelvertex3f + 3 * surface->num_firstvertex, in_tc = rsurface.texcoordtexture2f + 2 * surface->num_firstvertex, out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;j < surface->num_vertices;j++, v1 += 3, in_tc += 2, out_tc += 2)
4995                         {
4996                                 out_tc[0] = in_tc[0] + amplitude * sin(((v1[0] + v1[2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
4997                                 out_tc[1] = in_tc[1] + amplitude * sin(((v1[1]        ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
4998                         }
4999                 }
5000                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
5001                 rsurface.texcoordtexture2f_bufferobject  = 0;
5002                 rsurface.texcoordtexture2f_bufferoffset  = 0;
5003         }
5004         rsurface.texcoordlightmap2f              = rsurface.modeltexcoordlightmap2f;
5005         rsurface.texcoordlightmap2f_bufferobject = rsurface.modeltexcoordlightmap2f_bufferobject;
5006         rsurface.texcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
5007         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
5008 }
5009
5010 void RSurf_DrawBatch_Simple(int texturenumsurfaces, msurface_t **texturesurfacelist)
5011 {
5012         int i, j;
5013         const msurface_t *surface = texturesurfacelist[0];
5014         const msurface_t *surface2;
5015         int firstvertex;
5016         int endvertex;
5017         int numvertices;
5018         int numtriangles;
5019         // TODO: lock all array ranges before render, rather than on each surface
5020         if (texturenumsurfaces == 1)
5021         {
5022                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5023                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5024         }
5025         else if (r_batchmode.integer == 2)
5026         {
5027                 #define MAXBATCHTRIANGLES 4096
5028                 int batchtriangles = 0;
5029                 int batchelements[MAXBATCHTRIANGLES*3];
5030                 for (i = 0;i < texturenumsurfaces;i = j)
5031                 {
5032                         surface = texturesurfacelist[i];
5033                         j = i + 1;
5034                         if (surface->num_triangles > MAXBATCHTRIANGLES)
5035                         {
5036                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5037                                 continue;
5038                         }
5039                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
5040                         batchtriangles = surface->num_triangles;
5041                         firstvertex = surface->num_firstvertex;
5042                         endvertex = surface->num_firstvertex + surface->num_vertices;
5043                         for (;j < texturenumsurfaces;j++)
5044                         {
5045                                 surface2 = texturesurfacelist[j];
5046                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
5047                                         break;
5048                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
5049                                 batchtriangles += surface2->num_triangles;
5050                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
5051                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
5052                         }
5053                         surface2 = texturesurfacelist[j-1];
5054                         numvertices = endvertex - firstvertex;
5055                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
5056                 }
5057         }
5058         else if (r_batchmode.integer == 1)
5059         {
5060                 for (i = 0;i < texturenumsurfaces;i = j)
5061                 {
5062                         surface = texturesurfacelist[i];
5063                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5064                                 if (texturesurfacelist[j] != surface2)
5065                                         break;
5066                         surface2 = texturesurfacelist[j-1];
5067                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
5068                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
5069                         GL_LockArrays(surface->num_firstvertex, numvertices);
5070                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5071                 }
5072         }
5073         else
5074         {
5075                 for (i = 0;i < texturenumsurfaces;i++)
5076                 {
5077                         surface = texturesurfacelist[i];
5078                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5079                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5080                 }
5081         }
5082 }
5083
5084 static void RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(int texturenumsurfaces, msurface_t **texturesurfacelist, int lightmaptexunit, int deluxemaptexunit, int refractiontexunit, int reflectiontexunit)
5085 {
5086         int i, planeindex, vertexindex;
5087         float d, bestd;
5088         vec3_t vert;
5089         const float *v;
5090         r_waterstate_waterplane_t *p, *bestp;
5091         msurface_t *surface;
5092         if (r_waterstate.renderingscene)
5093                 return;
5094         for (i = 0;i < texturenumsurfaces;i++)
5095         {
5096                 surface = texturesurfacelist[i];
5097                 if (lightmaptexunit >= 0)
5098                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5099                 if (deluxemaptexunit >= 0)
5100                         R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5101                 // pick the closest matching water plane
5102                 bestd = 0;
5103                 bestp = NULL;
5104                 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
5105                 {
5106                         d = 0;
5107                         for (vertexindex = 0, v = rsurface.modelvertex3f + surface->num_firstvertex * 3;vertexindex < surface->num_vertices;vertexindex++, v += 3)
5108                         {
5109                                 Matrix4x4_Transform(&rsurface.matrix, v, vert);
5110                                 d += fabs(PlaneDiff(vert, &p->plane));
5111                         }
5112                         if (bestd > d || !bestp)
5113                         {
5114                                 bestd = d;
5115                                 bestp = p;
5116                         }
5117                 }
5118                 if (bestp)
5119                 {
5120                         if (refractiontexunit >= 0)
5121                                 R_Mesh_TexBind(refractiontexunit, R_GetTexture(bestp->texture_refraction));
5122                         if (reflectiontexunit >= 0)
5123                                 R_Mesh_TexBind(reflectiontexunit, R_GetTexture(bestp->texture_reflection));
5124                 }
5125                 else
5126                 {
5127                         if (refractiontexunit >= 0)
5128                                 R_Mesh_TexBind(refractiontexunit, R_GetTexture(r_texture_black));
5129                         if (reflectiontexunit >= 0)
5130                                 R_Mesh_TexBind(reflectiontexunit, R_GetTexture(r_texture_black));
5131                 }
5132                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5133                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5134         }
5135 }
5136
5137 static void RSurf_DrawBatch_WithLightmapSwitching(int texturenumsurfaces, msurface_t **texturesurfacelist, int lightmaptexunit, int deluxemaptexunit)
5138 {
5139         int i;
5140         int j;
5141         const msurface_t *surface = texturesurfacelist[0];
5142         const msurface_t *surface2;
5143         int firstvertex;
5144         int endvertex;
5145         int numvertices;
5146         int numtriangles;
5147         // TODO: lock all array ranges before render, rather than on each surface
5148         if (texturenumsurfaces == 1)
5149         {
5150                 R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5151                 if (deluxemaptexunit >= 0)
5152                         R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5153                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5154                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5155         }
5156         else if (r_batchmode.integer == 2)
5157         {
5158                 #define MAXBATCHTRIANGLES 4096
5159                 int batchtriangles = 0;
5160                 int batchelements[MAXBATCHTRIANGLES*3];
5161                 for (i = 0;i < texturenumsurfaces;i = j)
5162                 {
5163                         surface = texturesurfacelist[i];
5164                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5165                         if (deluxemaptexunit >= 0)
5166                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5167                         j = i + 1;
5168                         if (surface->num_triangles > MAXBATCHTRIANGLES)
5169                         {
5170                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5171                                 continue;
5172                         }
5173                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
5174                         batchtriangles = surface->num_triangles;
5175                         firstvertex = surface->num_firstvertex;
5176                         endvertex = surface->num_firstvertex + surface->num_vertices;
5177                         for (;j < texturenumsurfaces;j++)
5178                         {
5179                                 surface2 = texturesurfacelist[j];
5180                                 if (surface2->lightmaptexture != surface->lightmaptexture || batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
5181                                         break;
5182                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
5183                                 batchtriangles += surface2->num_triangles;
5184                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
5185                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
5186                         }
5187                         surface2 = texturesurfacelist[j-1];
5188                         numvertices = endvertex - firstvertex;
5189                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
5190                 }
5191         }
5192         else if (r_batchmode.integer == 1)
5193         {
5194 #if 0
5195                 Con_Printf("%s batch sizes ignoring lightmap:", rsurface.texture->name);
5196                 for (i = 0;i < texturenumsurfaces;i = j)
5197                 {
5198                         surface = texturesurfacelist[i];
5199                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5200                                 if (texturesurfacelist[j] != surface2)
5201                                         break;
5202                         Con_Printf(" %i", j - i);
5203                 }
5204                 Con_Printf("\n");
5205                 Con_Printf("%s batch sizes honoring lightmap:", rsurface.texture->name);
5206 #endif
5207                 for (i = 0;i < texturenumsurfaces;i = j)
5208                 {
5209                         surface = texturesurfacelist[i];
5210                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5211                         if (deluxemaptexunit >= 0)
5212                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5213                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5214                                 if (texturesurfacelist[j] != surface2 || texturesurfacelist[j]->lightmaptexture != surface->lightmaptexture)
5215                                         break;
5216 #if 0
5217                         Con_Printf(" %i", j - i);
5218 #endif
5219                         surface2 = texturesurfacelist[j-1];
5220                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
5221                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
5222                         GL_LockArrays(surface->num_firstvertex, numvertices);
5223                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5224                 }
5225 #if 0
5226                 Con_Printf("\n");
5227 #endif
5228         }
5229         else
5230         {
5231                 for (i = 0;i < texturenumsurfaces;i++)
5232                 {
5233                         surface = texturesurfacelist[i];
5234                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5235                         if (deluxemaptexunit >= 0)
5236                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5237                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5238                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5239                 }
5240         }
5241 }
5242
5243 static void RSurf_DrawBatch_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
5244 {
5245         int j;
5246         int texturesurfaceindex;
5247         if (r_showsurfaces.integer == 2)
5248         {
5249                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5250                 {
5251                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5252                         for (j = 0;j < surface->num_triangles;j++)
5253                         {
5254                                 float f = ((j + surface->num_firsttriangle) & 31) * (1.0f / 31.0f) * r_refdef.view.colorscale;
5255                                 GL_Color(f, f, f, 1);
5256                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, 1, (rsurface.modelelement3i + 3 * (j + surface->num_firsttriangle)), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * (j + surface->num_firsttriangle)));
5257                         }
5258                 }
5259         }
5260         else
5261         {
5262                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5263                 {
5264                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5265                         int k = (int)(((size_t)surface) / sizeof(msurface_t));
5266                         GL_Color((k & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 4) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 8) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, 1);
5267                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5268                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5269                 }
5270         }
5271 }
5272
5273 static void RSurf_DrawBatch_GL11_ApplyFog(int texturenumsurfaces, msurface_t **texturesurfacelist)
5274 {
5275         int texturesurfaceindex;
5276         int i;
5277         float f;
5278         float *v, *c, *c2;
5279         if (rsurface.lightmapcolor4f)
5280         {
5281                 // generate color arrays for the surfaces in this list
5282                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5283                 {
5284                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5285                         for (i = 0, v = (rsurface.vertex3f + 3 * surface->num_firstvertex), c = (rsurface.lightmapcolor4f + 4 * surface->num_firstvertex), c2 = (rsurface.array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4, c2 += 4)
5286                         {
5287                                 f = FogPoint_Model(v);
5288                                 c2[0] = c[0] * f;
5289                                 c2[1] = c[1] * f;
5290                                 c2[2] = c[2] * f;
5291                                 c2[3] = c[3];
5292                         }
5293                 }
5294         }
5295         else
5296         {
5297                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5298                 {
5299                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5300                         for (i = 0, v = (rsurface.vertex3f + 3 * surface->num_firstvertex), c2 = (rsurface.array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c2 += 4)
5301                         {
5302                                 f = FogPoint_Model(v);
5303                                 c2[0] = f;
5304                                 c2[1] = f;
5305                                 c2[2] = f;
5306                                 c2[3] = 1;
5307                         }
5308                 }
5309         }
5310         rsurface.lightmapcolor4f = rsurface.array_color4f;
5311         rsurface.lightmapcolor4f_bufferobject = 0;
5312         rsurface.lightmapcolor4f_bufferoffset = 0;
5313 }
5314
5315 static void RSurf_DrawBatch_GL11_ApplyColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a)
5316 {
5317         int texturesurfaceindex;
5318         int i;
5319         float *c, *c2;
5320         if (!rsurface.lightmapcolor4f)
5321                 return;
5322         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5323         {
5324                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5325                 for (i = 0, c = (rsurface.lightmapcolor4f + 4 * surface->num_firstvertex), c2 = (rsurface.array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, c += 4, c2 += 4)
5326                 {
5327                         c2[0] = c[0] * r;
5328                         c2[1] = c[1] * g;
5329                         c2[2] = c[2] * b;
5330                         c2[3] = c[3] * a;
5331                 }
5332         }
5333         rsurface.lightmapcolor4f = rsurface.array_color4f;
5334         rsurface.lightmapcolor4f_bufferobject = 0;
5335         rsurface.lightmapcolor4f_bufferoffset = 0;
5336 }
5337
5338 static void RSurf_DrawBatch_GL11_Lightmap(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5339 {
5340         // TODO: optimize
5341         rsurface.lightmapcolor4f = NULL;
5342         rsurface.lightmapcolor4f_bufferobject = 0;
5343         rsurface.lightmapcolor4f_bufferoffset = 0;
5344         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5345         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5346         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5347         GL_Color(r, g, b, a);
5348         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, 0, -1);
5349 }
5350
5351 static void RSurf_DrawBatch_GL11_Unlit(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5352 {
5353         // TODO: optimize applyfog && applycolor case
5354         // just apply fog if necessary, and tint the fog color array if necessary
5355         rsurface.lightmapcolor4f = NULL;
5356         rsurface.lightmapcolor4f_bufferobject = 0;
5357         rsurface.lightmapcolor4f_bufferoffset = 0;
5358         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5359         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5360         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5361         GL_Color(r, g, b, a);
5362         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5363 }
5364
5365 static void RSurf_DrawBatch_GL11_VertexColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5366 {
5367         int texturesurfaceindex;
5368         int i;
5369         float *c;
5370         // TODO: optimize
5371         if (texturesurfacelist[0]->lightmapinfo && texturesurfacelist[0]->lightmapinfo->stainsamples)
5372         {
5373                 // generate color arrays for the surfaces in this list
5374                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5375                 {
5376                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5377                         for (i = 0, c = rsurface.array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
5378                         {
5379                                 if (surface->lightmapinfo->samples)
5380                                 {
5381                                         const unsigned char *lm = surface->lightmapinfo->samples + (rsurface.modellightmapoffsets + surface->num_firstvertex)[i];
5382                                         float scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]] * (1.0f / 32768.0f);
5383                                         VectorScale(lm, scale, c);
5384                                         if (surface->lightmapinfo->styles[1] != 255)
5385                                         {
5386                                                 int size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
5387                                                 lm += size3;
5388                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]] * (1.0f / 32768.0f);
5389                                                 VectorMA(c, scale, lm, c);
5390                                                 if (surface->lightmapinfo->styles[2] != 255)
5391                                                 {
5392                                                         lm += size3;
5393                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]] * (1.0f / 32768.0f);
5394                                                         VectorMA(c, scale, lm, c);
5395                                                         if (surface->lightmapinfo->styles[3] != 255)
5396                                                         {
5397                                                                 lm += size3;
5398                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]] * (1.0f / 32768.0f);
5399                                                                 VectorMA(c, scale, lm, c);
5400                                                         }
5401                                                 }
5402                                         }
5403                                 }
5404                                 else
5405                                         VectorClear(c);
5406                                 c[3] = 1;
5407                         }
5408                 }
5409                 rsurface.lightmapcolor4f = rsurface.array_color4f;
5410                 rsurface.lightmapcolor4f_bufferobject = 0;
5411                 rsurface.lightmapcolor4f_bufferoffset = 0;
5412         }
5413         else
5414         {
5415                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
5416                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
5417                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
5418         }
5419         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5420         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5421         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5422         GL_Color(r, g, b, a);
5423         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5424 }
5425
5426 static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5427 {
5428         int texturesurfaceindex;
5429         int i;
5430         float f;
5431         float *v, *c, *c2;
5432         vec3_t ambientcolor;
5433         vec3_t diffusecolor;
5434         vec3_t lightdir;
5435         // TODO: optimize
5436         // model lighting
5437         VectorCopy(rsurface.modellight_lightdir, lightdir);
5438         f = 0.5f * r_refdef.lightmapintensity;
5439         ambientcolor[0] = rsurface.modellight_ambient[0] * r * f;
5440         ambientcolor[1] = rsurface.modellight_ambient[1] * g * f;
5441         ambientcolor[2] = rsurface.modellight_ambient[2] * b * f;
5442         diffusecolor[0] = rsurface.modellight_diffuse[0] * r * f;
5443         diffusecolor[1] = rsurface.modellight_diffuse[1] * g * f;
5444         diffusecolor[2] = rsurface.modellight_diffuse[2] * b * f;
5445         if (VectorLength2(diffusecolor) > 0)
5446         {
5447                 // generate color arrays for the surfaces in this list
5448                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5449                 {
5450                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5451                         int numverts = surface->num_vertices;
5452                         v = rsurface.vertex3f + 3 * surface->num_firstvertex;
5453                         c2 = rsurface.normal3f + 3 * surface->num_firstvertex;
5454                         c = rsurface.array_color4f + 4 * surface->num_firstvertex;
5455                         // q3-style directional shading
5456                         for (i = 0;i < numverts;i++, v += 3, c2 += 3, c += 4)
5457                         {
5458                                 if ((f = DotProduct(c2, lightdir)) > 0)
5459                                         VectorMA(ambientcolor, f, diffusecolor, c);
5460                                 else
5461                                         VectorCopy(ambientcolor, c);
5462                                 c[3] = a;
5463                         }
5464                 }
5465                 r = 1;
5466                 g = 1;
5467                 b = 1;
5468                 a = 1;
5469                 applycolor = false;
5470                 rsurface.lightmapcolor4f = rsurface.array_color4f;
5471                 rsurface.lightmapcolor4f_bufferobject = 0;
5472                 rsurface.lightmapcolor4f_bufferoffset = 0;
5473         }
5474         else
5475         {
5476                 r = ambientcolor[0];
5477                 g = ambientcolor[1];
5478                 b = ambientcolor[2];
5479                 rsurface.lightmapcolor4f = NULL;
5480                 rsurface.lightmapcolor4f_bufferobject = 0;
5481                 rsurface.lightmapcolor4f_bufferoffset = 0;
5482         }
5483         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5484         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5485         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5486         GL_Color(r, g, b, a);
5487         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5488 }
5489
5490 void RSurf_SetupDepthAndCulling(void)
5491 {
5492         // submodels are biased to avoid z-fighting with world surfaces that they
5493         // may be exactly overlapping (avoids z-fighting artifacts on certain
5494         // doors and things in Quake maps)
5495         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
5496         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
5497         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
5498         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
5499 }
5500
5501 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
5502 {
5503         RSurf_SetupDepthAndCulling();
5504         if (rsurface.mode != RSURFMODE_SHOWSURFACES)
5505         {
5506                 rsurface.mode = RSURFMODE_SHOWSURFACES;
5507                 GL_DepthMask(true);
5508                 GL_BlendFunc(GL_ONE, GL_ZERO);
5509                 R_Mesh_ColorPointer(NULL, 0, 0);
5510                 R_Mesh_ResetTextureState();
5511         }
5512         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
5513         RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
5514 }
5515
5516 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, msurface_t **texturesurfacelist)
5517 {
5518         // transparent sky would be ridiculous
5519         if ((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
5520                 return;
5521         if (rsurface.mode != RSURFMODE_SKY)
5522         {
5523                 if (rsurface.mode == RSURFMODE_GLSL)
5524                 {
5525                         qglUseProgramObjectARB(0);CHECKGLERROR
5526                 }
5527                 rsurface.mode = RSURFMODE_SKY;
5528         }
5529         if (skyrendernow)
5530         {
5531                 skyrendernow = false;
5532                 R_Sky();
5533                 // restore entity matrix
5534                 R_Mesh_Matrix(&rsurface.matrix);
5535         }
5536         RSurf_SetupDepthAndCulling();
5537         GL_DepthMask(true);
5538         // LordHavoc: HalfLife maps have freaky skypolys so don't use
5539         // skymasking on them, and Quake3 never did sky masking (unlike
5540         // software Quake and software Quake2), so disable the sky masking
5541         // in Quake3 maps as it causes problems with q3map2 sky tricks,
5542         // and skymasking also looks very bad when noclipping outside the
5543         // level, so don't use it then either.
5544         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
5545         {
5546                 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
5547                 R_Mesh_ColorPointer(NULL, 0, 0);
5548                 R_Mesh_ResetTextureState();
5549                 if (skyrendermasked)
5550                 {
5551                         // depth-only (masking)
5552                         GL_ColorMask(0,0,0,0);
5553                         // just to make sure that braindead drivers don't draw
5554                         // anything despite that colormask...
5555                         GL_BlendFunc(GL_ZERO, GL_ONE);
5556                 }
5557                 else
5558                 {
5559                         // fog sky
5560                         GL_BlendFunc(GL_ONE, GL_ZERO);
5561                 }
5562                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
5563                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5564                 if (skyrendermasked)
5565                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5566         }
5567 }
5568
5569 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **texturesurfacelist)
5570 {
5571         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION)))
5572                 return;
5573
5574         if (rsurface.mode != RSURFMODE_GLSL)
5575         {
5576                 rsurface.mode = RSURFMODE_GLSL;
5577                 R_Mesh_ResetTextureState();
5578                 GL_Color(1, 1, 1, 1);
5579         }
5580
5581         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
5582         R_Mesh_TexBind(0, R_GetTexture(rsurface.texture->currentskinframe->nmap));
5583         R_Mesh_TexBind(1, R_GetTexture(rsurface.texture->basetexture));
5584         R_Mesh_TexBind(2, R_GetTexture(rsurface.texture->glosstexture));
5585         R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation));
5586         R_Mesh_TexBind(5, R_GetTexture(rsurface.texture->currentskinframe->pants));
5587         R_Mesh_TexBind(6, R_GetTexture(rsurface.texture->currentskinframe->shirt));
5588         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5589         {
5590                 R_Mesh_TexBind(7, R_GetTexture(r_texture_grey128));
5591                 R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
5592                 R_Mesh_ColorPointer(NULL, 0, 0);
5593         }
5594         else if (rsurface.uselightmaptexture)
5595         {
5596                 R_Mesh_TexBind(7, R_GetTexture(texturesurfacelist[0]->lightmaptexture));
5597                 R_Mesh_TexBind(8, R_GetTexture(texturesurfacelist[0]->deluxemaptexture));
5598                 R_Mesh_ColorPointer(NULL, 0, 0);
5599         }
5600         else
5601         {
5602                 R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
5603                 R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
5604                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5605         }
5606         R_Mesh_TexBind(9, R_GetTexture(rsurface.texture->currentskinframe->glow));
5607         R_Mesh_TexBind(11, R_GetTexture(r_texture_white)); // changed per surface
5608         R_Mesh_TexBind(12, R_GetTexture(r_texture_white)); // changed per surface
5609
5610         if (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
5611         {
5612                 // render background
5613                 GL_BlendFunc(GL_ONE, GL_ZERO);
5614                 GL_DepthMask(true);
5615                 GL_AlphaTest(false);
5616
5617                 GL_Color(1, 1, 1, 1);
5618                 R_Mesh_ColorPointer(NULL, 0, 0);
5619
5620                 R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
5621                 if (r_glsl_permutation)
5622                 {
5623                         RSurf_PrepareVerticesForBatch(true, true, texturenumsurfaces, texturesurfacelist);
5624                         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5625                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5626                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5627                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5628                         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5629                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, -1, -1, r_glsl_permutation->loc_Texture_Refraction ? 11 : -1, r_glsl_permutation->loc_Texture_Reflection ? 12 : -1);
5630                 }
5631
5632                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5633                 GL_DepthMask(false);
5634                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5635                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5636                 {
5637                         R_Mesh_TexBind(7, R_GetTexture(r_texture_grey128));
5638                         R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
5639                         R_Mesh_ColorPointer(NULL, 0, 0);
5640                 }
5641                 else if (rsurface.uselightmaptexture)
5642                 {
5643                         R_Mesh_TexBind(7, R_GetTexture(texturesurfacelist[0]->lightmaptexture));
5644                         R_Mesh_TexBind(8, R_GetTexture(texturesurfacelist[0]->deluxemaptexture));
5645                         R_Mesh_ColorPointer(NULL, 0, 0);
5646                 }
5647                 else
5648                 {
5649                         R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
5650                         R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
5651                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5652                 }
5653                 R_Mesh_TexBind(11, R_GetTexture(r_texture_white)); // changed per surface
5654                 R_Mesh_TexBind(12, R_GetTexture(r_texture_white)); // changed per surface
5655         }
5656
5657         R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
5658         if (!r_glsl_permutation)
5659                 return;
5660
5661         RSurf_PrepareVerticesForBatch(r_glsl_permutation->loc_Texture_Normal >= 0 || r_glsl_permutation->loc_LightDir >= 0, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
5662         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5663         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5664         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5665         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5666         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5667
5668         if (r_glsl_permutation->loc_Texture_Refraction >= 0)
5669         {
5670                 GL_BlendFunc(GL_ONE, GL_ZERO);
5671                 GL_DepthMask(true);
5672                 GL_AlphaTest(false);
5673         }
5674
5675         if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
5676         {
5677                 if (r_glsl_permutation->loc_Texture_Refraction >= 0 || r_glsl_permutation->loc_Texture_Reflection >= 0)
5678                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, 7, r_glsl_permutation->loc_Texture_Deluxemap >= 0 ? 8 : -1, r_glsl_permutation->loc_Texture_Refraction >= 0 ? 11 : -1, r_glsl_permutation->loc_Texture_Reflection >= 0 ? 12 : -1);
5679                 else
5680                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, 7, r_glsl_permutation->loc_Texture_Deluxemap >= 0 ? 8 : -1);
5681         }
5682         else
5683         {
5684                 if (r_glsl_permutation->loc_Texture_Refraction >= 0 || r_glsl_permutation->loc_Texture_Reflection >= 0)
5685                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, -1, -1, r_glsl_permutation->loc_Texture_Refraction >= 0 ? 11 : -1, r_glsl_permutation->loc_Texture_Reflection >= 0 ? 12 : -1);
5686                 else
5687                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5688         }
5689         if (rsurface.texture->backgroundnumskinframes && !(rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
5690         {
5691         }
5692 }
5693
5694 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, msurface_t **texturesurfacelist)
5695 {
5696         // OpenGL 1.3 path - anything not completely ancient
5697         int texturesurfaceindex;
5698         qboolean applycolor;
5699         qboolean applyfog;
5700         rmeshstate_t m;
5701         int layerindex;
5702         const texturelayer_t *layer;
5703         if (rsurface.mode != RSURFMODE_MULTIPASS)
5704                 rsurface.mode = RSURFMODE_MULTIPASS;
5705         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
5706
5707         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
5708         {
5709                 vec4_t layercolor;
5710                 int layertexrgbscale;
5711                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5712                 {
5713                         if (layerindex == 0)
5714                                 GL_AlphaTest(true);
5715                         else
5716                         {
5717                                 GL_AlphaTest(false);
5718                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
5719                         }
5720                 }
5721                 GL_DepthMask(layer->depthmask);
5722                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
5723                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
5724                 {
5725                         layertexrgbscale = 4;
5726                         VectorScale(layer->color, 0.25f, layercolor);
5727                 }
5728                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
5729                 {
5730                         layertexrgbscale = 2;
5731                         VectorScale(layer->color, 0.5f, layercolor);
5732                 }
5733                 else
5734                 {
5735                         layertexrgbscale = 1;
5736                         VectorScale(layer->color, 1.0f, layercolor);
5737                 }
5738                 layercolor[3] = layer->color[3];
5739                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
5740                 R_Mesh_ColorPointer(NULL, 0, 0);
5741                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
5742                 switch (layer->type)
5743                 {
5744                 case TEXTURELAYERTYPE_LITTEXTURE:
5745                         memset(&m, 0, sizeof(m));
5746                         m.tex[0] = R_GetTexture(r_texture_white);
5747                         m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
5748                         m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
5749                         m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
5750                         m.tex[1] = R_GetTexture(layer->texture);
5751                         m.texmatrix[1] = layer->texmatrix;
5752                         m.texrgbscale[1] = layertexrgbscale;
5753                         m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
5754                         m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
5755                         m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
5756                         R_Mesh_TextureState(&m);
5757                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5758                                 RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5759                         else if (rsurface.uselightmaptexture)
5760                                 RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5761                         else
5762                                 RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5763                         break;
5764                 case TEXTURELAYERTYPE_TEXTURE:
5765                         memset(&m, 0, sizeof(m));
5766                         m.tex[0] = R_GetTexture(layer->texture);
5767                         m.texmatrix[0] = layer->texmatrix;
5768                         m.texrgbscale[0] = layertexrgbscale;
5769                         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5770                         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5771                         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5772                         R_Mesh_TextureState(&m);
5773                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5774                         break;
5775                 case TEXTURELAYERTYPE_FOG:
5776                         memset(&m, 0, sizeof(m));
5777                         m.texrgbscale[0] = layertexrgbscale;
5778                         if (layer->texture)
5779                         {
5780                                 m.tex[0] = R_GetTexture(layer->texture);
5781                                 m.texmatrix[0] = layer->texmatrix;
5782                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5783                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5784                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5785                         }
5786                         R_Mesh_TextureState(&m);
5787                         // generate a color array for the fog pass
5788                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
5789                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5790                         {
5791                                 int i;
5792                                 float f, *v, *c;
5793                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5794                                 for (i = 0, v = (rsurface.vertex3f + 3 * surface->num_firstvertex), c = (rsurface.array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4)
5795                                 {
5796                                         f = 1 - FogPoint_Model(v);
5797                                         c[0] = layercolor[0];
5798                                         c[1] = layercolor[1];
5799                                         c[2] = layercolor[2];
5800                                         c[3] = f * layercolor[3];
5801                                 }
5802                         }
5803                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5804                         break;
5805                 default:
5806                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
5807                 }
5808                 GL_LockArrays(0, 0);
5809         }
5810         CHECKGLERROR
5811         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5812         {
5813                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
5814                 GL_AlphaTest(false);
5815         }
5816 }
5817
5818 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, msurface_t **texturesurfacelist)
5819 {
5820         // OpenGL 1.1 - crusty old voodoo path
5821         int texturesurfaceindex;
5822         qboolean applyfog;
5823         rmeshstate_t m;
5824         int layerindex;
5825         const texturelayer_t *layer;
5826         if (rsurface.mode != RSURFMODE_MULTIPASS)
5827                 rsurface.mode = RSURFMODE_MULTIPASS;
5828         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
5829
5830         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
5831         {
5832                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5833                 {
5834                         if (layerindex == 0)
5835                                 GL_AlphaTest(true);
5836                         else
5837                         {
5838                                 GL_AlphaTest(false);
5839                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
5840                         }
5841                 }
5842                 GL_DepthMask(layer->depthmask);
5843                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
5844                 R_Mesh_ColorPointer(NULL, 0, 0);
5845                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
5846                 switch (layer->type)
5847                 {
5848                 case TEXTURELAYERTYPE_LITTEXTURE:
5849                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
5850                         {
5851                                 // two-pass lit texture with 2x rgbscale
5852                                 // first the lightmap pass
5853                                 memset(&m, 0, sizeof(m));
5854                                 m.tex[0] = R_GetTexture(r_texture_white);
5855                                 m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
5856                                 m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
5857                                 m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
5858                                 R_Mesh_TextureState(&m);
5859                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5860                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5861                                 else if (rsurface.uselightmaptexture)
5862                                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5863                                 else
5864                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5865                                 GL_LockArrays(0, 0);
5866                                 // then apply the texture to it
5867                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
5868                                 memset(&m, 0, sizeof(m));
5869                                 m.tex[0] = R_GetTexture(layer->texture);
5870                                 m.texmatrix[0] = layer->texmatrix;
5871                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5872                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5873                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5874                                 R_Mesh_TextureState(&m);
5875                                 RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layer->color[0] * 0.5f, layer->color[1] * 0.5f, layer->color[2] * 0.5f, layer->color[3], layer->color[0] != 2 || layer->color[1] != 2 || layer->color[2] != 2 || layer->color[3] != 1, false);
5876                         }
5877                         else
5878                         {
5879                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
5880                                 memset(&m, 0, sizeof(m));
5881                                 m.tex[0] = R_GetTexture(layer->texture);
5882                                 m.texmatrix[0] = layer->texmatrix;
5883                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5884                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5885                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5886                                 R_Mesh_TextureState(&m);
5887                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5888                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
5889                                 else
5890                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
5891                         }
5892                         break;
5893                 case TEXTURELAYERTYPE_TEXTURE:
5894                         // singletexture unlit texture with transparency support
5895                         memset(&m, 0, sizeof(m));
5896                         m.tex[0] = R_GetTexture(layer->texture);
5897                         m.texmatrix[0] = layer->texmatrix;
5898                         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5899                         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5900                         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5901                         R_Mesh_TextureState(&m);
5902                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
5903                         break;
5904                 case TEXTURELAYERTYPE_FOG:
5905                         // singletexture fogging
5906                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
5907                         if (layer->texture)
5908                         {
5909                                 memset(&m, 0, sizeof(m));
5910                                 m.tex[0] = R_GetTexture(layer->texture);
5911                                 m.texmatrix[0] = layer->texmatrix;
5912                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5913                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5914                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5915                                 R_Mesh_TextureState(&m);
5916                         }
5917                         else
5918                                 R_Mesh_ResetTextureState();
5919                         // generate a color array for the fog pass
5920                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5921                         {
5922                                 int i;
5923                                 float f, *v, *c;
5924                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5925                                 for (i = 0, v = (rsurface.vertex3f + 3 * surface->num_firstvertex), c = (rsurface.array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4)
5926                                 {
5927                                         f = 1 - FogPoint_Model(v);
5928                                         c[0] = layer->color[0];
5929                                         c[1] = layer->color[1];
5930                                         c[2] = layer->color[2];
5931                                         c[3] = f * layer->color[3];
5932                                 }
5933                         }
5934                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5935                         break;
5936                 default:
5937                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
5938                 }
5939                 GL_LockArrays(0, 0);
5940         }
5941         CHECKGLERROR
5942         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5943         {
5944                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
5945                 GL_AlphaTest(false);
5946         }
5947 }
5948
5949 static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly)
5950 {
5951         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW)
5952                 return;
5953         rsurface.rtlight = NULL;
5954         CHECKGLERROR
5955         if (depthonly)
5956         {
5957                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
5958                         return;
5959                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
5960                         return;
5961                 if (rsurface.mode != RSURFMODE_MULTIPASS)
5962                         rsurface.mode = RSURFMODE_MULTIPASS;
5963                 if (r_depthfirst.integer == 3)
5964                 {
5965                         int i = (int)(texturesurfacelist[0] - rsurface.modelsurfaces);
5966                         if (!r_refdef.view.showdebug)
5967                                 GL_Color(0, 0, 0, 1);
5968                         else
5969                                 GL_Color(((i >> 6) & 7) / 7.0f, ((i >> 3) & 7) / 7.0f, (i & 7) / 7.0f,1);
5970                 }
5971                 else
5972                 {
5973                         GL_ColorMask(0,0,0,0);
5974                         GL_Color(1,1,1,1);
5975                 }
5976                 RSurf_SetupDepthAndCulling();
5977                 GL_DepthTest(true);
5978                 GL_BlendFunc(GL_ONE, GL_ZERO);
5979                 GL_DepthMask(true);
5980                 GL_AlphaTest(false);
5981                 R_Mesh_ColorPointer(NULL, 0, 0);
5982                 R_Mesh_ResetTextureState();
5983                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
5984                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5985                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5986         }
5987         else if (r_depthfirst.integer == 3)
5988                 return;
5989         else if (!r_refdef.view.showdebug && (r_showsurfaces.integer || gl_lightmaps.integer))
5990         {
5991                 GL_Color(0, 0, 0, 1);
5992                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5993         }
5994         else if (r_showsurfaces.integer)
5995         {
5996                 if (rsurface.mode != RSURFMODE_MULTIPASS)
5997                         rsurface.mode = RSURFMODE_MULTIPASS;
5998                 RSurf_SetupDepthAndCulling();
5999                 GL_DepthTest(true);
6000                 GL_BlendFunc(GL_ONE, GL_ZERO);
6001                 GL_DepthMask(writedepth);
6002                 GL_Color(1,1,1,1);
6003                 GL_AlphaTest(false);
6004                 R_Mesh_ColorPointer(NULL, 0, 0);
6005                 R_Mesh_ResetTextureState();
6006                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
6007                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
6008         }
6009         else if (gl_lightmaps.integer)
6010         {
6011                 rmeshstate_t m;
6012                 if (rsurface.mode != RSURFMODE_MULTIPASS)
6013                         rsurface.mode = RSURFMODE_MULTIPASS;
6014                 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
6015                 GL_DepthTest(true);
6016                 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
6017                 GL_BlendFunc(GL_ONE, GL_ZERO);
6018                 GL_DepthMask(writedepth);
6019                 GL_Color(1,1,1,1);
6020                 GL_AlphaTest(false);
6021                 R_Mesh_ColorPointer(NULL, 0, 0);
6022                 memset(&m, 0, sizeof(m));
6023                 m.tex[0] = R_GetTexture(r_texture_white);
6024                 m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
6025                 m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
6026                 m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
6027                 R_Mesh_TextureState(&m);
6028                 RSurf_PrepareVerticesForBatch(rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, false, texturenumsurfaces, texturesurfacelist);
6029                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
6030                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6031                 else if (rsurface.uselightmaptexture)
6032                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6033                 else
6034                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6035         }
6036         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
6037                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
6038         else if (rsurface.texture->currentnumlayers)
6039         {
6040                 // write depth for anything we skipped on the depth-only pass earlier
6041                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
6042                         writedepth = true;
6043                 RSurf_SetupDepthAndCulling();
6044                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
6045                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
6046                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
6047                 if (r_glsl.integer && gl_support_fragment_shader)
6048                         R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist);
6049                 else if (gl_combine.integer && r_textureunits.integer >= 2)
6050                         R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist);
6051                 else
6052                         R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist);
6053         }
6054         CHECKGLERROR
6055         GL_LockArrays(0, 0);
6056 }
6057
6058 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
6059 {
6060         int i, j;
6061         int texturenumsurfaces, endsurface;
6062         texture_t *texture;
6063         msurface_t *surface;
6064         msurface_t *texturesurfacelist[1024];
6065
6066         // if the model is static it doesn't matter what value we give for
6067         // wantnormals and wanttangents, so this logic uses only rules applicable
6068         // to a model, knowing that they are meaningless otherwise
6069         if (ent == r_refdef.scene.worldentity)
6070                 RSurf_ActiveWorldEntity();
6071         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
6072                 RSurf_ActiveModelEntity(ent, false, false);
6073         else
6074                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader);
6075
6076         for (i = 0;i < numsurfaces;i = j)
6077         {
6078                 j = i + 1;
6079                 surface = rsurface.modelsurfaces + surfacelist[i];
6080                 texture = surface->texture;
6081                 R_UpdateTextureInfo(ent, texture);
6082                 rsurface.texture = texture->currentframe;
6083                 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
6084                 // scan ahead until we find a different texture
6085                 endsurface = min(i + 1024, numsurfaces);
6086                 texturenumsurfaces = 0;
6087                 texturesurfacelist[texturenumsurfaces++] = surface;
6088                 for (;j < endsurface;j++)
6089                 {
6090                         surface = rsurface.modelsurfaces + surfacelist[j];
6091                         if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
6092                                 break;
6093                         texturesurfacelist[texturenumsurfaces++] = surface;
6094                 }
6095                 // render the range of surfaces
6096                 R_DrawTextureSurfaceList(texturenumsurfaces, texturesurfacelist, true, false);
6097         }
6098
6099         RSurf_CleanUp();
6100 }
6101
6102 void R_QueueSurfaceList(entity_render_t *ent, int numsurfaces, msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes)
6103 {
6104         int i, j;
6105         vec3_t tempcenter, center;
6106         texture_t *texture;
6107         // if we're rendering water textures (extra scene renders), use a separate loop to avoid burdening the main one
6108         if (addwaterplanes)
6109         {
6110                 for (i = 0;i < numsurfaces;i++)
6111                         if (surfacelist[i]->texture->currentframe->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
6112                                 R_Water_AddWaterPlane(surfacelist[i]);
6113                 return;
6114         }
6115         // break the surface list down into batches by texture and use of lightmapping
6116         for (i = 0;i < numsurfaces;i = j)
6117         {
6118                 j = i + 1;
6119                 // texture is the base texture pointer, rsurface.texture is the
6120                 // current frame/skin the texture is directing us to use (for example
6121                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
6122                 // use skin 1 instead)
6123                 texture = surfacelist[i]->texture;
6124                 rsurface.texture = texture->currentframe;
6125                 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
6126                 if (!(rsurface.texture->currentmaterialflags & flagsmask))
6127                 {
6128                         // if this texture is not the kind we want, skip ahead to the next one
6129                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
6130                                 ;
6131                         continue;
6132                 }
6133                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
6134                 {
6135                         // transparent surfaces get pushed off into the transparent queue
6136                         const msurface_t *surface = surfacelist[i];
6137                         if (depthonly)
6138                                 continue;
6139                         tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
6140                         tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
6141                         tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
6142                         Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
6143                         R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, ent, surface - rsurface.modelsurfaces, rsurface.rtlight);
6144                 }
6145                 else
6146                 {
6147                         // simply scan ahead until we find a different texture or lightmap state
6148                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
6149                                 ;
6150                         // render the range of surfaces
6151                         R_DrawTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly);
6152                 }
6153         }
6154 }
6155
6156 float locboxvertex3f[6*4*3] =
6157 {
6158         1,0,1, 1,0,0, 1,1,0, 1,1,1,
6159         0,1,1, 0,1,0, 0,0,0, 0,0,1,
6160         1,1,1, 1,1,0, 0,1,0, 0,1,1,
6161         0,0,1, 0,0,0, 1,0,0, 1,0,1,
6162         0,0,1, 1,0,1, 1,1,1, 0,1,1,
6163         1,0,0, 0,0,0, 0,1,0, 1,1,0
6164 };
6165
6166 int locboxelement3i[6*2*3] =
6167 {
6168          0, 1, 2, 0, 2, 3,
6169          4, 5, 6, 4, 6, 7,
6170          8, 9,10, 8,10,11,
6171         12,13,14, 12,14,15,
6172         16,17,18, 16,18,19,
6173         20,21,22, 20,22,23
6174 };
6175
6176 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
6177 {
6178         int i, j;
6179         cl_locnode_t *loc = (cl_locnode_t *)ent;
6180         vec3_t mins, size;
6181         float vertex3f[6*4*3];
6182         CHECKGLERROR
6183         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6184         GL_DepthMask(false);
6185         GL_DepthRange(0, 1);
6186         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
6187         GL_DepthTest(true);
6188         GL_CullFace(GL_NONE);
6189         R_Mesh_Matrix(&identitymatrix);
6190
6191         R_Mesh_VertexPointer(vertex3f, 0, 0);
6192         R_Mesh_ColorPointer(NULL, 0, 0);
6193         R_Mesh_ResetTextureState();
6194
6195         i = surfacelist[0];
6196         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6197                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6198                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6199                         surfacelist[0] < 0 ? 0.5f : 0.125f);
6200
6201         if (VectorCompare(loc->mins, loc->maxs))
6202         {
6203                 VectorSet(size, 2, 2, 2);
6204                 VectorMA(loc->mins, -0.5f, size, mins);
6205         }
6206         else
6207         {
6208                 VectorCopy(loc->mins, mins);
6209                 VectorSubtract(loc->maxs, loc->mins, size);
6210         }
6211
6212         for (i = 0;i < 6*4*3;)
6213                 for (j = 0;j < 3;j++, i++)
6214                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
6215
6216         R_Mesh_Draw(0, 6*4, 6*2, locboxelement3i, 0, 0);
6217 }
6218
6219 void R_DrawLocs(void)
6220 {
6221         int index;
6222         cl_locnode_t *loc, *nearestloc;
6223         vec3_t center;
6224         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
6225         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
6226         {
6227                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
6228                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
6229         }
6230 }
6231
6232 void R_DrawDebugModel(entity_render_t *ent)
6233 {
6234         int i, j, k, l, flagsmask;
6235         const int *elements;
6236         q3mbrush_t *brush;
6237         msurface_t *surface;
6238         model_t *model = ent->model;
6239         vec3_t v;
6240
6241         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WATER | MATERIALFLAG_WALL;
6242
6243         R_Mesh_ColorPointer(NULL, 0, 0);
6244         R_Mesh_ResetTextureState();
6245         GL_DepthRange(0, 1);
6246         GL_DepthTest(!r_showdisabledepthtest.integer);
6247         GL_DepthMask(false);
6248         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6249
6250         if (r_showcollisionbrushes.value > 0 && model->brush.num_brushes)
6251         {
6252                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
6253                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6254                 {
6255                         if (brush->colbrushf && brush->colbrushf->numtriangles)
6256                         {
6257                                 R_Mesh_VertexPointer(brush->colbrushf->points->v, 0, 0);
6258                                 GL_Color((i & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
6259                                 R_Mesh_Draw(0, brush->colbrushf->numpoints, brush->colbrushf->numtriangles, brush->colbrushf->elements, 0, 0);
6260                         }
6261                 }
6262                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6263                 {
6264                         if (surface->num_collisiontriangles)
6265                         {
6266                                 R_Mesh_VertexPointer(surface->data_collisionvertex3f, 0, 0);
6267                                 GL_Color((i & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
6268                                 R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i, 0, 0);
6269                         }
6270                 }
6271         }
6272
6273         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
6274
6275         if (r_showtris.integer || r_shownormals.integer)
6276         {
6277                 if (r_showdisabledepthtest.integer)
6278                 {
6279                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6280                         GL_DepthMask(false);
6281                 }
6282                 else
6283                 {
6284                         GL_BlendFunc(GL_ONE, GL_ZERO);
6285                         GL_DepthMask(true);
6286                 }
6287                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
6288                 {
6289                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
6290                                 continue;
6291                         rsurface.texture = surface->texture->currentframe;
6292                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
6293                         {
6294                                 RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
6295                                 if (r_showtris.value > 0)
6296                                 {
6297                                         if (!rsurface.texture->currentlayers->depthmask)
6298                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
6299                                         else if (ent == r_refdef.scene.worldentity)
6300                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
6301                                         else
6302                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
6303                                         elements = (ent->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);
6304                                         CHECKGLERROR
6305                                         qglBegin(GL_LINES);
6306                                         for (k = 0;k < surface->num_triangles;k++, elements += 3)
6307                                         {
6308 #define GLVERTEXELEMENT(n) qglVertex3f(rsurface.vertex3f[elements[n]*3+0], rsurface.vertex3f[elements[n]*3+1], rsurface.vertex3f[elements[n]*3+2])
6309                                                 GLVERTEXELEMENT(0);GLVERTEXELEMENT(1);
6310                                                 GLVERTEXELEMENT(1);GLVERTEXELEMENT(2);
6311                                                 GLVERTEXELEMENT(2);GLVERTEXELEMENT(0);
6312                                         }
6313                                         qglEnd();
6314                                         CHECKGLERROR
6315                                 }
6316                                 if (r_shownormals.value > 0)
6317                                 {
6318                                         qglBegin(GL_LINES);
6319                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6320                                         {
6321                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6322                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
6323                                                 qglVertex3f(v[0], v[1], v[2]);
6324                                                 VectorMA(v, r_shownormals.value, rsurface.svector3f + l * 3, v);
6325                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6326                                                 qglVertex3f(v[0], v[1], v[2]);
6327                                         }
6328                                         qglEnd();
6329                                         CHECKGLERROR
6330                                         qglBegin(GL_LINES);
6331                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6332                                         {
6333                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6334                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
6335                                                 qglVertex3f(v[0], v[1], v[2]);
6336                                                 VectorMA(v, r_shownormals.value, rsurface.tvector3f + l * 3, v);
6337                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6338                                                 qglVertex3f(v[0], v[1], v[2]);
6339                                         }
6340                                         qglEnd();
6341                                         CHECKGLERROR
6342                                         qglBegin(GL_LINES);
6343                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6344                                         {
6345                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6346                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
6347                                                 qglVertex3f(v[0], v[1], v[2]);
6348                                                 VectorMA(v, r_shownormals.value, rsurface.normal3f + l * 3, v);
6349                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6350                                                 qglVertex3f(v[0], v[1], v[2]);
6351                                         }
6352                                         qglEnd();
6353                                         CHECKGLERROR
6354                                 }
6355                         }
6356                 }
6357                 rsurface.texture = NULL;
6358         }
6359 }
6360
6361 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
6362 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
6363 {
6364         int i, j, endj, f, flagsmask;
6365         msurface_t *surface;
6366         texture_t *t;
6367         model_t *model = r_refdef.scene.worldmodel;
6368         const int maxsurfacelist = 1024;
6369         int numsurfacelist = 0;
6370         msurface_t *surfacelist[1024];
6371         if (model == NULL)
6372                 return;
6373
6374         RSurf_ActiveWorldEntity();
6375
6376         // update light styles on this submodel
6377         if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
6378         {
6379                 model_brush_lightstyleinfo_t *style;
6380                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
6381                 {
6382                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
6383                         {
6384                                 msurface_t *surfaces = model->data_surfaces;
6385                                 int *list = style->surfacelist;
6386                                 style->value = r_refdef.scene.lightstylevalue[style->style];
6387                                 for (j = 0;j < style->numsurfaces;j++)
6388                                         surfaces[list[j]].cached_dlight = true;
6389                         }
6390                 }
6391         }
6392
6393         R_UpdateAllTextureInfo(r_refdef.scene.worldentity);
6394         flagsmask = addwaterplanes ? (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) : (skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL));
6395
6396         if (debug)
6397         {
6398                 R_DrawDebugModel(r_refdef.scene.worldentity);
6399                 return;
6400         }
6401
6402         f = 0;
6403         t = NULL;
6404         rsurface.uselightmaptexture = false;
6405         rsurface.texture = NULL;
6406         numsurfacelist = 0;
6407         j = model->firstmodelsurface;
6408         endj = j + model->nummodelsurfaces;
6409         while (j < endj)
6410         {
6411                 // quickly skip over non-visible surfaces
6412                 for (;j < endj && !r_refdef.viewcache.world_surfacevisible[j];j++)
6413                         ;
6414                 // quickly iterate over visible surfaces
6415                 for (;j < endj && r_refdef.viewcache.world_surfacevisible[j];j++)
6416                 {
6417                         // process this surface
6418                         surface = model->data_surfaces + j;
6419                         // if this surface fits the criteria, add it to the list
6420                         if (surface->num_triangles)
6421                         {
6422                                 // if lightmap parameters changed, rebuild lightmap texture
6423                                 if (surface->cached_dlight)
6424                                         R_BuildLightMap(r_refdef.scene.worldentity, surface);
6425                                 // add face to draw list
6426                                 surfacelist[numsurfacelist++] = surface;
6427                                 r_refdef.stats.world_triangles += surface->num_triangles;
6428                                 if (numsurfacelist >= maxsurfacelist)
6429                                 {
6430                                         r_refdef.stats.world_surfaces += numsurfacelist;
6431                                         R_QueueSurfaceList(r_refdef.scene.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6432                                         numsurfacelist = 0;
6433                                 }
6434                         }
6435                 }
6436         }
6437         r_refdef.stats.world_surfaces += numsurfacelist;
6438         if (numsurfacelist)
6439                 R_QueueSurfaceList(r_refdef.scene.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6440         RSurf_CleanUp();
6441 }
6442
6443 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
6444 {
6445         int i, j, f, flagsmask;
6446         msurface_t *surface, *endsurface;
6447         texture_t *t;
6448         model_t *model = ent->model;
6449         const int maxsurfacelist = 1024;
6450         int numsurfacelist = 0;
6451         msurface_t *surfacelist[1024];
6452         if (model == NULL)
6453                 return;
6454
6455         // if the model is static it doesn't matter what value we give for
6456         // wantnormals and wanttangents, so this logic uses only rules applicable
6457         // to a model, knowing that they are meaningless otherwise
6458         if (ent == r_refdef.scene.worldentity)
6459                 RSurf_ActiveWorldEntity();
6460         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
6461                 RSurf_ActiveModelEntity(ent, false, false);
6462         else
6463                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader && !depthonly);
6464
6465         // update light styles
6466         if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
6467         {
6468                 model_brush_lightstyleinfo_t *style;
6469                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
6470                 {
6471                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
6472                         {
6473                                 msurface_t *surfaces = model->data_surfaces;
6474                                 int *list = style->surfacelist;
6475                                 style->value = r_refdef.scene.lightstylevalue[style->style];
6476                                 for (j = 0;j < style->numsurfaces;j++)
6477                                         surfaces[list[j]].cached_dlight = true;
6478                         }
6479                 }
6480         }
6481
6482         R_UpdateAllTextureInfo(ent);
6483         flagsmask = addwaterplanes ? (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) : (skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL));
6484
6485         if (debug)
6486         {
6487                 R_DrawDebugModel(ent);
6488                 return;
6489         }
6490
6491         f = 0;
6492         t = NULL;
6493         rsurface.uselightmaptexture = false;
6494         rsurface.texture = NULL;
6495         numsurfacelist = 0;
6496         surface = model->data_surfaces + model->firstmodelsurface;
6497         endsurface = surface + model->nummodelsurfaces;
6498         for (;surface < endsurface;surface++)
6499         {
6500                 // if this surface fits the criteria, add it to the list
6501                 if (surface->num_triangles)
6502                 {
6503                         // if lightmap parameters changed, rebuild lightmap texture
6504                         if (surface->cached_dlight)
6505                                 R_BuildLightMap(ent, surface);
6506                         // add face to draw list
6507                         surfacelist[numsurfacelist++] = surface;
6508                         r_refdef.stats.entities_triangles += surface->num_triangles;
6509                         if (numsurfacelist >= maxsurfacelist)
6510                         {
6511                                 r_refdef.stats.entities_surfaces += numsurfacelist;
6512                                 R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6513                                 numsurfacelist = 0;
6514                         }
6515                 }
6516         }
6517         r_refdef.stats.entities_surfaces += numsurfacelist;
6518         if (numsurfacelist)
6519                 R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6520         RSurf_CleanUp();
6521 }