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