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