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