]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rmain.c
r_water_scissormode: 0 = none, 1 = glScissor, 2 = glScissor and frustum culling
[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 #include "ft2.h"
28 #include "csprogs.h"
29 #include "cl_video.h"
30
31 #ifdef SUPPORTD3D
32 #include <d3d9.h>
33 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
34 #endif
35
36 mempool_t *r_main_mempool;
37 rtexturepool_t *r_main_texturepool;
38
39 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
40
41 static qboolean r_loadnormalmap;
42 static qboolean r_loadgloss;
43 qboolean r_loadfog;
44 static qboolean r_loaddds;
45 static qboolean r_savedds;
46
47 //
48 // screen size info
49 //
50 r_refdef_t r_refdef;
51
52 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
53 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
54 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
55 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
56 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
57 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
58 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
59 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
60
61 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
62 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
63 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
64 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
65 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
66
67 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
68 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
69 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
70 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
71 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
72 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
73 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)"};
74 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
75 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
76 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"};
77 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"};
78 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
79 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"};
80 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"};
81 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"};
82 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
83 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
84 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
85 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
86 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
87 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
88 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
89 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
90 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
91 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
92 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
93 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
94 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
95
96 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
97 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
98 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
99
100 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
101 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
102 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
103 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
104 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
105 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
106 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
107 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
108 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
109 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
110 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
111 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
112 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"};
113 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
114 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
115 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
116 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
117 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
118 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
119
120 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
121 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
122 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
123 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
124 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
125 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
126 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
127 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
128
129 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
130 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
131
132 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
133 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
134 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
135 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
136 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
137
138 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
139 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
140 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
141
142 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)"};
143 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
144 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
145 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
146 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
147 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
148 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
149 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
150 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
151
152 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)"};
153 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
154 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"};
155 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
156 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
157 cvar_t r_water_scissormode = {CVAR_SAVE, "r_water_scissormode", "2", "scissor (1) and cull (2) water renders"};
158
159 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
160 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
161 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
162 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
163
164 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
165 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
166 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
167 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
168 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
169 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
170 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
171
172 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
173 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
174 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
175 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)"};
176
177 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"};
178
179 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"};
180
181 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
182
183 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
184 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"};
185 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
186 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
187 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
188 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
189 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "16", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
190
191 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
192
193 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "1", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
194
195 extern cvar_t v_glslgamma;
196
197 extern qboolean v_flipped_state;
198
199 static struct r_bloomstate_s
200 {
201         qboolean enabled;
202         qboolean hdr;
203
204         int bloomwidth, bloomheight;
205
206         int screentexturewidth, screentextureheight;
207         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
208
209         int bloomtexturewidth, bloomtextureheight;
210         rtexture_t *texture_bloom;
211
212         // arrays for rendering the screen passes
213         float screentexcoord2f[8];
214         float bloomtexcoord2f[8];
215         float offsettexcoord2f[8];
216
217         r_viewport_t viewport;
218 }
219 r_bloomstate;
220
221 r_waterstate_t r_waterstate;
222
223 /// shadow volume bsp struct with automatically growing nodes buffer
224 svbsp_t r_svbsp;
225
226 rtexture_t *r_texture_blanknormalmap;
227 rtexture_t *r_texture_white;
228 rtexture_t *r_texture_grey128;
229 rtexture_t *r_texture_black;
230 rtexture_t *r_texture_notexture;
231 rtexture_t *r_texture_whitecube;
232 rtexture_t *r_texture_normalizationcube;
233 rtexture_t *r_texture_fogattenuation;
234 rtexture_t *r_texture_fogheighttexture;
235 rtexture_t *r_texture_gammaramps;
236 unsigned int r_texture_gammaramps_serial;
237 //rtexture_t *r_texture_fogintensity;
238 rtexture_t *r_texture_reflectcube;
239
240 // TODO: hash lookups?
241 typedef struct cubemapinfo_s
242 {
243         char basename[64];
244         rtexture_t *texture;
245 }
246 cubemapinfo_t;
247
248 int r_texture_numcubemaps;
249 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
250
251 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
252 unsigned int r_numqueries;
253 unsigned int r_maxqueries;
254
255 typedef struct r_qwskincache_s
256 {
257         char name[MAX_QPATH];
258         skinframe_t *skinframe;
259 }
260 r_qwskincache_t;
261
262 static r_qwskincache_t *r_qwskincache;
263 static int r_qwskincache_size;
264
265 /// vertex coordinates for a quad that covers the screen exactly
266 extern const float r_screenvertex3f[12];
267 extern const float r_d3dscreenvertex3f[12];
268 const float r_screenvertex3f[12] =
269 {
270         0, 0, 0,
271         1, 0, 0,
272         1, 1, 0,
273         0, 1, 0
274 };
275 const float r_d3dscreenvertex3f[12] =
276 {
277         0, 1, 0,
278         1, 1, 0,
279         1, 0, 0,
280         0, 0, 0
281 };
282
283 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
284 {
285         int i;
286         for (i = 0;i < verts;i++)
287         {
288                 out[0] = in[0] * r;
289                 out[1] = in[1] * g;
290                 out[2] = in[2] * b;
291                 out[3] = in[3];
292                 in += 4;
293                 out += 4;
294         }
295 }
296
297 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
298 {
299         int i;
300         for (i = 0;i < verts;i++)
301         {
302                 out[0] = r;
303                 out[1] = g;
304                 out[2] = b;
305                 out[3] = a;
306                 out += 4;
307         }
308 }
309
310 // FIXME: move this to client?
311 void FOG_clear(void)
312 {
313         if (gamemode == GAME_NEHAHRA)
314         {
315                 Cvar_Set("gl_fogenable", "0");
316                 Cvar_Set("gl_fogdensity", "0.2");
317                 Cvar_Set("gl_fogred", "0.3");
318                 Cvar_Set("gl_foggreen", "0.3");
319                 Cvar_Set("gl_fogblue", "0.3");
320         }
321         r_refdef.fog_density = 0;
322         r_refdef.fog_red = 0;
323         r_refdef.fog_green = 0;
324         r_refdef.fog_blue = 0;
325         r_refdef.fog_alpha = 1;
326         r_refdef.fog_start = 0;
327         r_refdef.fog_end = 16384;
328         r_refdef.fog_height = 1<<30;
329         r_refdef.fog_fadedepth = 128;
330         memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
331 }
332
333 static void R_BuildBlankTextures(void)
334 {
335         unsigned char data[4];
336         data[2] = 128; // normal X
337         data[1] = 128; // normal Y
338         data[0] = 255; // normal Z
339         data[3] = 128; // height
340         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
341         data[0] = 255;
342         data[1] = 255;
343         data[2] = 255;
344         data[3] = 255;
345         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
346         data[0] = 128;
347         data[1] = 128;
348         data[2] = 128;
349         data[3] = 255;
350         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
351         data[0] = 0;
352         data[1] = 0;
353         data[2] = 0;
354         data[3] = 255;
355         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
356 }
357
358 static void R_BuildNoTexture(void)
359 {
360         int x, y;
361         unsigned char pix[16][16][4];
362         // this makes a light grey/dark grey checkerboard texture
363         for (y = 0;y < 16;y++)
364         {
365                 for (x = 0;x < 16;x++)
366                 {
367                         if ((y < 8) ^ (x < 8))
368                         {
369                                 pix[y][x][0] = 128;
370                                 pix[y][x][1] = 128;
371                                 pix[y][x][2] = 128;
372                                 pix[y][x][3] = 255;
373                         }
374                         else
375                         {
376                                 pix[y][x][0] = 64;
377                                 pix[y][x][1] = 64;
378                                 pix[y][x][2] = 64;
379                                 pix[y][x][3] = 255;
380                         }
381                 }
382         }
383         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
384 }
385
386 static void R_BuildWhiteCube(void)
387 {
388         unsigned char data[6*1*1*4];
389         memset(data, 255, sizeof(data));
390         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
391 }
392
393 static void R_BuildNormalizationCube(void)
394 {
395         int x, y, side;
396         vec3_t v;
397         vec_t s, t, intensity;
398 #define NORMSIZE 64
399         unsigned char *data;
400         data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
401         for (side = 0;side < 6;side++)
402         {
403                 for (y = 0;y < NORMSIZE;y++)
404                 {
405                         for (x = 0;x < NORMSIZE;x++)
406                         {
407                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
408                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
409                                 switch(side)
410                                 {
411                                 default:
412                                 case 0:
413                                         v[0] = 1;
414                                         v[1] = -t;
415                                         v[2] = -s;
416                                         break;
417                                 case 1:
418                                         v[0] = -1;
419                                         v[1] = -t;
420                                         v[2] = s;
421                                         break;
422                                 case 2:
423                                         v[0] = s;
424                                         v[1] = 1;
425                                         v[2] = t;
426                                         break;
427                                 case 3:
428                                         v[0] = s;
429                                         v[1] = -1;
430                                         v[2] = -t;
431                                         break;
432                                 case 4:
433                                         v[0] = s;
434                                         v[1] = -t;
435                                         v[2] = 1;
436                                         break;
437                                 case 5:
438                                         v[0] = -s;
439                                         v[1] = -t;
440                                         v[2] = -1;
441                                         break;
442                                 }
443                                 intensity = 127.0f / sqrt(DotProduct(v, v));
444                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
445                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
446                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
447                                 data[((side*64+y)*64+x)*4+3] = 255;
448                         }
449                 }
450         }
451         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
452         Mem_Free(data);
453 }
454
455 static void R_BuildFogTexture(void)
456 {
457         int x, b;
458 #define FOGWIDTH 256
459         unsigned char data1[FOGWIDTH][4];
460         //unsigned char data2[FOGWIDTH][4];
461         double d, r, alpha;
462
463         r_refdef.fogmasktable_start = r_refdef.fog_start;
464         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
465         r_refdef.fogmasktable_range = r_refdef.fogrange;
466         r_refdef.fogmasktable_density = r_refdef.fog_density;
467
468         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
469         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
470         {
471                 d = (x * r - r_refdef.fogmasktable_start);
472                 if(developer_extra.integer)
473                         Con_DPrintf("%f ", d);
474                 d = max(0, d);
475                 if (r_fog_exp2.integer)
476                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
477                 else
478                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
479                 if(developer_extra.integer)
480                         Con_DPrintf(" : %f ", alpha);
481                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
482                 if(developer_extra.integer)
483                         Con_DPrintf(" = %f\n", alpha);
484                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
485         }
486
487         for (x = 0;x < FOGWIDTH;x++)
488         {
489                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
490                 data1[x][0] = b;
491                 data1[x][1] = b;
492                 data1[x][2] = b;
493                 data1[x][3] = 255;
494                 //data2[x][0] = 255 - b;
495                 //data2[x][1] = 255 - b;
496                 //data2[x][2] = 255 - b;
497                 //data2[x][3] = 255;
498         }
499         if (r_texture_fogattenuation)
500         {
501                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
502                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
503         }
504         else
505         {
506                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
507                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
508         }
509 }
510
511 static void R_BuildFogHeightTexture(void)
512 {
513         unsigned char *inpixels;
514         int size;
515         int x;
516         int y;
517         int j;
518         float c[4];
519         float f;
520         inpixels = NULL;
521         strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
522         if (r_refdef.fogheighttexturename[0])
523                 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
524         if (!inpixels)
525         {
526                 r_refdef.fog_height_tablesize = 0;
527                 if (r_texture_fogheighttexture)
528                         R_FreeTexture(r_texture_fogheighttexture);
529                 r_texture_fogheighttexture = NULL;
530                 if (r_refdef.fog_height_table2d)
531                         Mem_Free(r_refdef.fog_height_table2d);
532                 r_refdef.fog_height_table2d = NULL;
533                 if (r_refdef.fog_height_table1d)
534                         Mem_Free(r_refdef.fog_height_table1d);
535                 r_refdef.fog_height_table1d = NULL;
536                 return;
537         }
538         size = image_width;
539         r_refdef.fog_height_tablesize = size;
540         r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
541         r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
542         memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
543         Mem_Free(inpixels);
544         // LordHavoc: now the magic - what is that table2d for?  it is a cooked
545         // average fog color table accounting for every fog layer between a point
546         // and the camera.  (Note: attenuation is handled separately!)
547         for (y = 0;y < size;y++)
548         {
549                 for (x = 0;x < size;x++)
550                 {
551                         Vector4Clear(c);
552                         f = 0;
553                         if (x < y)
554                         {
555                                 for (j = x;j <= y;j++)
556                                 {
557                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
558                                         f++;
559                                 }
560                         }
561                         else
562                         {
563                                 for (j = x;j >= y;j--)
564                                 {
565                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
566                                         f++;
567                                 }
568                         }
569                         f = 1.0f / f;
570                         r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
571                         r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
572                         r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
573                         r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
574                 }
575         }
576         r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
577 }
578
579 //=======================================================================================================================================================
580
581 static const char *builtinshaderstring =
582 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
583 "// written by Forest 'LordHavoc' Hale\n"
584 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
585 "\n"
586 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
587 "# define USEFOG\n"
588 "#endif\n"
589 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
590 "#define USELIGHTMAP\n"
591 "#endif\n"
592 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
593 "#define USEEYEVECTOR\n"
594 "#endif\n"
595 "\n"
596 "#ifdef USESHADOWMAP2D\n"
597 "# ifdef GL_EXT_gpu_shader4\n"
598 "#   extension GL_EXT_gpu_shader4 : enable\n"
599 "# endif\n"
600 "# ifdef GL_ARB_texture_gather\n"
601 "#   extension GL_ARB_texture_gather : enable\n"
602 "# else\n"
603 "#   ifdef GL_AMD_texture_texture4\n"
604 "#     extension GL_AMD_texture_texture4 : enable\n"
605 "#   endif\n"
606 "# endif\n"
607 "#endif\n"
608 "\n"
609 "//#ifdef USESHADOWSAMPLER\n"
610 "//# extension GL_ARB_shadow : enable\n"
611 "//#endif\n"
612 "\n"
613 "//#ifdef __GLSL_CG_DATA_TYPES\n"
614 "//# define myhalf half\n"
615 "//# define myhalf2 half2\n"
616 "//# define myhalf3 half3\n"
617 "//# define myhalf4 half4\n"
618 "//#else\n"
619 "# define myhalf float\n"
620 "# define myhalf2 vec2\n"
621 "# define myhalf3 vec3\n"
622 "# define myhalf4 vec4\n"
623 "//#endif\n"
624 "\n"
625 "#ifdef VERTEX_SHADER\n"
626 "uniform mat4 ModelViewProjectionMatrix;\n"
627 "#endif\n"
628 "\n"
629 "#ifdef MODE_DEPTH_OR_SHADOW\n"
630 "#ifdef VERTEX_SHADER\n"
631 "void main(void)\n"
632 "{\n"
633 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
634 "}\n"
635 "#endif\n"
636 "#else // !MODE_DEPTH_ORSHADOW\n"
637 "\n"
638 "\n"
639 "\n"
640 "\n"
641 "#ifdef MODE_SHOWDEPTH\n"
642 "#ifdef VERTEX_SHADER\n"
643 "void main(void)\n"
644 "{\n"
645 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
646 "       gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
647 "}\n"
648 "#endif\n"
649 "\n"
650 "#ifdef FRAGMENT_SHADER\n"
651 "void main(void)\n"
652 "{\n"
653 "       gl_FragColor = gl_Color;\n"
654 "}\n"
655 "#endif\n"
656 "#else // !MODE_SHOWDEPTH\n"
657 "\n"
658 "\n"
659 "\n"
660 "\n"
661 "#ifdef MODE_POSTPROCESS\n"
662 "varying vec2 TexCoord1;\n"
663 "varying vec2 TexCoord2;\n"
664 "\n"
665 "#ifdef VERTEX_SHADER\n"
666 "void main(void)\n"
667 "{\n"
668 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
669 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
670 "#ifdef USEBLOOM\n"
671 "       TexCoord2 = gl_MultiTexCoord4.xy;\n"
672 "#endif\n"
673 "}\n"
674 "#endif\n"
675 "\n"
676 "#ifdef FRAGMENT_SHADER\n"
677 "uniform sampler2D Texture_First;\n"
678 "#ifdef USEBLOOM\n"
679 "uniform sampler2D Texture_Second;\n"
680 "uniform vec4 BloomColorSubtract;\n"
681 "#endif\n"
682 "#ifdef USEGAMMARAMPS\n"
683 "uniform sampler2D Texture_GammaRamps;\n"
684 "#endif\n"
685 "#ifdef USESATURATION\n"
686 "uniform float Saturation;\n"
687 "#endif\n"
688 "#ifdef USEVIEWTINT\n"
689 "uniform vec4 ViewTintColor;\n"
690 "#endif\n"
691 "//uncomment these if you want to use them:\n"
692 "uniform vec4 UserVec1;\n"
693 "uniform vec4 UserVec2;\n"
694 "// uniform vec4 UserVec3;\n"
695 "// uniform vec4 UserVec4;\n"
696 "// uniform float ClientTime;\n"
697 "uniform vec2 PixelSize;\n"
698 "void main(void)\n"
699 "{\n"
700 "       gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
701 "#ifdef USEBLOOM\n"
702 "       gl_FragColor += max(vec4(0,0,0,0), texture2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
703 "#endif\n"
704 "#ifdef USEVIEWTINT\n"
705 "       gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
706 "#endif\n"
707 "\n"
708 "#ifdef USEPOSTPROCESSING\n"
709 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
710 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
711 "       float sobel = 1.0;\n"
712 "       // vec2 ts = textureSize(Texture_First, 0);\n"
713 "       // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
714 "       vec2 px = PixelSize;\n"
715 "       vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
716 "       vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,  0.0)).rgb;\n"
717 "       vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
718 "       vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
719 "       vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x,  0.0)).rgb;\n"
720 "       vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
721 "       vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
722 "       vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2(  0.0,-px.y)).rgb;\n"
723 "       vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
724 "       vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
725 "       vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2(  0.0, px.y)).rgb;\n"
726 "       vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
727 "       float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
728 "       float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
729 "       float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
730 "       float px4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
731 "       float px5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
732 "       float px6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
733 "       float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
734 "       float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
735 "       float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
736 "       float py4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
737 "       float py5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
738 "       float py6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
739 "       sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
740 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
741 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
742 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
743 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107,  0.707107)) * UserVec1.y;\n"
744 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990,  0.891007)) * UserVec1.y;\n"
745 "       gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
746 "       gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
747 "#endif\n"
748 "\n"
749 "#ifdef USESATURATION\n"
750 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
751 "       float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
752 "       //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
753 "       gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
754 "#endif\n"
755 "\n"
756 "#ifdef USEGAMMARAMPS\n"
757 "       gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
758 "       gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
759 "       gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
760 "#endif\n"
761 "}\n"
762 "#endif\n"
763 "#else // !MODE_POSTPROCESS\n"
764 "\n"
765 "\n"
766 "\n"
767 "\n"
768 "#ifdef MODE_GENERIC\n"
769 "#ifdef USEDIFFUSE\n"
770 "varying vec2 TexCoord1;\n"
771 "#endif\n"
772 "#ifdef USESPECULAR\n"
773 "varying vec2 TexCoord2;\n"
774 "#endif\n"
775 "#ifdef VERTEX_SHADER\n"
776 "void main(void)\n"
777 "{\n"
778 "       gl_FrontColor = gl_Color;\n"
779 "#ifdef USEDIFFUSE\n"
780 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
781 "#endif\n"
782 "#ifdef USESPECULAR\n"
783 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
784 "#endif\n"
785 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
786 "}\n"
787 "#endif\n"
788 "\n"
789 "#ifdef FRAGMENT_SHADER\n"
790 "#ifdef USEDIFFUSE\n"
791 "uniform sampler2D Texture_First;\n"
792 "#endif\n"
793 "#ifdef USESPECULAR\n"
794 "uniform sampler2D Texture_Second;\n"
795 "#endif\n"
796 "\n"
797 "void main(void)\n"
798 "{\n"
799 "       gl_FragColor = gl_Color;\n"
800 "#ifdef USEDIFFUSE\n"
801 "       gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
802 "#endif\n"
803 "\n"
804 "#ifdef USESPECULAR\n"
805 "       vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
806 "# ifdef USECOLORMAPPING\n"
807 "       gl_FragColor *= tex2;\n"
808 "# endif\n"
809 "# ifdef USEGLOW\n"
810 "       gl_FragColor += tex2;\n"
811 "# endif\n"
812 "# ifdef USEVERTEXTEXTUREBLEND\n"
813 "       gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
814 "# endif\n"
815 "#endif\n"
816 "}\n"
817 "#endif\n"
818 "#else // !MODE_GENERIC\n"
819 "\n"
820 "\n"
821 "\n"
822 "\n"
823 "#ifdef MODE_BLOOMBLUR\n"
824 "varying TexCoord;\n"
825 "#ifdef VERTEX_SHADER\n"
826 "void main(void)\n"
827 "{\n"
828 "       gl_FrontColor = gl_Color;\n"
829 "       TexCoord = gl_MultiTexCoord0.xy;\n"
830 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
831 "}\n"
832 "#endif\n"
833 "\n"
834 "#ifdef FRAGMENT_SHADER\n"
835 "uniform sampler2D Texture_First;\n"
836 "uniform vec4 BloomBlur_Parameters;\n"
837 "\n"
838 "void main(void)\n"
839 "{\n"
840 "       int i;\n"
841 "       vec2 tc = TexCoord;\n"
842 "       vec3 color = texture2D(Texture_First, tc).rgb;\n"
843 "       tc += BloomBlur_Parameters.xy;\n"
844 "       for (i = 1;i < SAMPLES;i++)\n"
845 "       {\n"
846 "               color += texture2D(Texture_First, tc).rgb;\n"
847 "               tc += BloomBlur_Parameters.xy;\n"
848 "       }\n"
849 "       gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
850 "}\n"
851 "#endif\n"
852 "#else // !MODE_BLOOMBLUR\n"
853 "#ifdef MODE_REFRACTION\n"
854 "varying vec2 TexCoord;\n"
855 "varying vec4 ModelViewProjectionPosition;\n"
856 "uniform mat4 TexMatrix;\n"
857 "#ifdef VERTEX_SHADER\n"
858 "\n"
859 "void main(void)\n"
860 "{\n"
861 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
862 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
863 "       ModelViewProjectionPosition = gl_Position;\n"
864 "}\n"
865 "#endif\n"
866 "\n"
867 "#ifdef FRAGMENT_SHADER\n"
868 "uniform sampler2D Texture_Normal;\n"
869 "uniform sampler2D Texture_Refraction;\n"
870 "uniform sampler2D Texture_Reflection;\n"
871 "\n"
872 "uniform vec4 DistortScaleRefractReflect;\n"
873 "uniform vec4 ScreenScaleRefractReflect;\n"
874 "uniform vec4 ScreenCenterRefractReflect;\n"
875 "uniform vec4 RefractColor;\n"
876 "uniform vec4 ReflectColor;\n"
877 "uniform float ReflectFactor;\n"
878 "uniform float ReflectOffset;\n"
879 "\n"
880 "void main(void)\n"
881 "{\n"
882 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
883 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
884 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
885 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
886 "       // FIXME temporary hack to detect the case that the reflection\n"
887 "       // gets blackened at edges due to leaving the area that contains actual\n"
888 "       // content.\n"
889 "       // Remove this 'ack once we have a better way to stop this thing from\n"
890 "       // 'appening.\n"
891 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
892 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
893 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
894 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
895 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
896 "       gl_FragColor = vec4(texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
897 "}\n"
898 "#endif\n"
899 "#else // !MODE_REFRACTION\n"
900 "\n"
901 "\n"
902 "\n"
903 "\n"
904 "#ifdef MODE_WATER\n"
905 "varying vec2 TexCoord;\n"
906 "varying vec3 EyeVector;\n"
907 "varying vec4 ModelViewProjectionPosition;\n"
908 "#ifdef VERTEX_SHADER\n"
909 "uniform vec3 EyePosition;\n"
910 "uniform mat4 TexMatrix;\n"
911 "\n"
912 "void main(void)\n"
913 "{\n"
914 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
915 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
916 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
917 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
918 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
919 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
920 "       ModelViewProjectionPosition = gl_Position;\n"
921 "}\n"
922 "#endif\n"
923 "\n"
924 "#ifdef FRAGMENT_SHADER\n"
925 "uniform sampler2D Texture_Normal;\n"
926 "uniform sampler2D Texture_Refraction;\n"
927 "uniform sampler2D Texture_Reflection;\n"
928 "\n"
929 "uniform vec4 DistortScaleRefractReflect;\n"
930 "uniform vec4 ScreenScaleRefractReflect;\n"
931 "uniform vec4 ScreenCenterRefractReflect;\n"
932 "uniform vec4 RefractColor;\n"
933 "uniform vec4 ReflectColor;\n"
934 "uniform float ReflectFactor;\n"
935 "uniform float ReflectOffset;\n"
936 "\n"
937 "void main(void)\n"
938 "{\n"
939 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
940 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
941 "       vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
942 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
943 "       vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
944 "       // FIXME temporary hack to detect the case that the reflection\n"
945 "       // gets blackened at edges due to leaving the area that contains actual\n"
946 "       // content.\n"
947 "       // Remove this 'ack once we have a better way to stop this thing from\n"
948 "       // 'appening.\n"
949 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
950 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
951 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
952 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
953 "       ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
954 "       f       = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
955 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
956 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
957 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
958 "       ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
959 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
960 "       gl_FragColor = mix(vec4(texture2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, vec4(texture2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
961 "}\n"
962 "#endif\n"
963 "#else // !MODE_WATER\n"
964 "\n"
965 "\n"
966 "\n"
967 "\n"
968 "// common definitions between vertex shader and fragment shader:\n"
969 "\n"
970 "varying vec2 TexCoord;\n"
971 "#ifdef USEVERTEXTEXTUREBLEND\n"
972 "varying vec2 TexCoord2;\n"
973 "#endif\n"
974 "#ifdef USELIGHTMAP\n"
975 "varying vec2 TexCoordLightmap;\n"
976 "#endif\n"
977 "\n"
978 "#ifdef MODE_LIGHTSOURCE\n"
979 "varying vec3 CubeVector;\n"
980 "#endif\n"
981 "\n"
982 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
983 "varying vec3 LightVector;\n"
984 "#endif\n"
985 "\n"
986 "#ifdef USEEYEVECTOR\n"
987 "varying vec3 EyeVector;\n"
988 "#endif\n"
989 "#ifdef USEFOG\n"
990 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
991 "#endif\n"
992 "\n"
993 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
994 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
995 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
996 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
997 "#endif\n"
998 "\n"
999 "#ifdef USEREFLECTION\n"
1000 "varying vec4 ModelViewProjectionPosition;\n"
1001 "#endif\n"
1002 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1003 "uniform vec3 LightPosition;\n"
1004 "varying vec4 ModelViewPosition;\n"
1005 "#endif\n"
1006 "\n"
1007 "#ifdef MODE_LIGHTSOURCE\n"
1008 "uniform vec3 LightPosition;\n"
1009 "#endif\n"
1010 "uniform vec3 EyePosition;\n"
1011 "#ifdef MODE_LIGHTDIRECTION\n"
1012 "uniform vec3 LightDir;\n"
1013 "#endif\n"
1014 "uniform vec4 FogPlane;\n"
1015 "\n"
1016 "#ifdef USESHADOWMAPORTHO\n"
1017 "varying vec3 ShadowMapTC;\n"
1018 "#endif\n"
1019 "\n"
1020 "\n"
1021 "\n"
1022 "\n"
1023 "\n"
1024 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
1025 "\n"
1026 "// fragment shader specific:\n"
1027 "#ifdef FRAGMENT_SHADER\n"
1028 "\n"
1029 "uniform sampler2D Texture_Normal;\n"
1030 "uniform sampler2D Texture_Color;\n"
1031 "uniform sampler2D Texture_Gloss;\n"
1032 "#ifdef USEGLOW\n"
1033 "uniform sampler2D Texture_Glow;\n"
1034 "#endif\n"
1035 "#ifdef USEVERTEXTEXTUREBLEND\n"
1036 "uniform sampler2D Texture_SecondaryNormal;\n"
1037 "uniform sampler2D Texture_SecondaryColor;\n"
1038 "uniform sampler2D Texture_SecondaryGloss;\n"
1039 "#ifdef USEGLOW\n"
1040 "uniform sampler2D Texture_SecondaryGlow;\n"
1041 "#endif\n"
1042 "#endif\n"
1043 "#ifdef USECOLORMAPPING\n"
1044 "uniform sampler2D Texture_Pants;\n"
1045 "uniform sampler2D Texture_Shirt;\n"
1046 "#endif\n"
1047 "#ifdef USEFOG\n"
1048 "#ifdef USEFOGHEIGHTTEXTURE\n"
1049 "uniform sampler2D Texture_FogHeightTexture;\n"
1050 "#endif\n"
1051 "uniform sampler2D Texture_FogMask;\n"
1052 "#endif\n"
1053 "#ifdef USELIGHTMAP\n"
1054 "uniform sampler2D Texture_Lightmap;\n"
1055 "#endif\n"
1056 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1057 "uniform sampler2D Texture_Deluxemap;\n"
1058 "#endif\n"
1059 "#ifdef USEREFLECTION\n"
1060 "uniform sampler2D Texture_Reflection;\n"
1061 "#endif\n"
1062 "\n"
1063 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1064 "uniform sampler2D Texture_ScreenDepth;\n"
1065 "uniform sampler2D Texture_ScreenNormalMap;\n"
1066 "#endif\n"
1067 "#ifdef USEDEFERREDLIGHTMAP\n"
1068 "uniform sampler2D Texture_ScreenDiffuse;\n"
1069 "uniform sampler2D Texture_ScreenSpecular;\n"
1070 "#endif\n"
1071 "\n"
1072 "uniform myhalf3 Color_Pants;\n"
1073 "uniform myhalf3 Color_Shirt;\n"
1074 "uniform myhalf3 FogColor;\n"
1075 "\n"
1076 "#ifdef USEFOG\n"
1077 "uniform float FogRangeRecip;\n"
1078 "uniform float FogPlaneViewDist;\n"
1079 "uniform float FogHeightFade;\n"
1080 "vec3 FogVertex(vec3 surfacecolor)\n"
1081 "{\n"
1082 "       vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1083 "       float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1084 "       float fogfrac;\n"
1085 "#ifdef USEFOGHEIGHTTEXTURE\n"
1086 "       vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1087 "       fogfrac = fogheightpixel.a;\n"
1088 "       return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1089 "#else\n"
1090 "# ifdef USEFOGOUTSIDE\n"
1091 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1092 "# else\n"
1093 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1094 "# endif\n"
1095 "       return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1096 "#endif\n"
1097 "}\n"
1098 "#endif\n"
1099 "\n"
1100 "#ifdef USEOFFSETMAPPING\n"
1101 "uniform float OffsetMapping_Scale;\n"
1102 "vec2 OffsetMapping(vec2 TexCoord)\n"
1103 "{\n"
1104 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1105 "       // 14 sample relief mapping: linear search and then binary search\n"
1106 "       // this basically steps forward a small amount repeatedly until it finds\n"
1107 "       // itself inside solid, then jitters forward and back using decreasing\n"
1108 "       // amounts to find the impact\n"
1109 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1110 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1111 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1112 "       vec3 RT = vec3(TexCoord, 1);\n"
1113 "       OffsetVector *= 0.1;\n"
1114 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1115 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1116 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1117 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1118 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1119 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1120 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1121 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1122 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1123 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
1124 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
1125 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
1126 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
1127 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1128 "       return RT.xy;\n"
1129 "#else\n"
1130 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1131 "       // this basically moves forward the full distance, and then backs up based\n"
1132 "       // on height of samples\n"
1133 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1134 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1135 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1136 "       TexCoord += OffsetVector;\n"
1137 "       OffsetVector *= 0.333;\n"
1138 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1139 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1140 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1141 "       return TexCoord;\n"
1142 "#endif\n"
1143 "}\n"
1144 "#endif // USEOFFSETMAPPING\n"
1145 "\n"
1146 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1147 "uniform sampler2D Texture_Attenuation;\n"
1148 "uniform samplerCube Texture_Cube;\n"
1149 "#endif\n"
1150 "\n"
1151 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1152 "\n"
1153 "#ifdef USESHADOWMAP2D\n"
1154 "# ifdef USESHADOWSAMPLER\n"
1155 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1156 "# else\n"
1157 "uniform sampler2D Texture_ShadowMap2D;\n"
1158 "# endif\n"
1159 "#endif\n"
1160 "\n"
1161 "#ifdef USESHADOWMAPVSDCT\n"
1162 "uniform samplerCube Texture_CubeProjection;\n"
1163 "#endif\n"
1164 "\n"
1165 "#if defined(USESHADOWMAP2D)\n"
1166 "uniform vec2 ShadowMap_TextureScale;\n"
1167 "uniform vec4 ShadowMap_Parameters;\n"
1168 "#endif\n"
1169 "\n"
1170 "#if defined(USESHADOWMAP2D)\n"
1171 "# ifdef USESHADOWMAPORTHO\n"
1172 "#  define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1173 "# else\n"
1174 "#  ifdef USESHADOWMAPVSDCT\n"
1175 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1176 "{\n"
1177 "       vec3 adir = abs(dir);\n"
1178 "       vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1179 "       vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1180 "       return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1181 "}\n"
1182 "#  else\n"
1183 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1184 "{\n"
1185 "       vec3 adir = abs(dir);\n"
1186 "       float ma = adir.z;\n"
1187 "       vec4 proj = vec4(dir, 2.5);\n"
1188 "       if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1189 "       if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1190 "       vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1191 "       return vec3(proj.xy * aparams.x + vec2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1192 "}\n"
1193 "#  endif\n"
1194 "# endif\n"
1195 "#endif // defined(USESHADOWMAP2D)\n"
1196 "\n"
1197 "# ifdef USESHADOWMAP2D\n"
1198 "float ShadowMapCompare(vec3 dir)\n"
1199 "{\n"
1200 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1201 "       float f;\n"
1202 "\n"
1203 "#  ifdef USESHADOWSAMPLER\n"
1204 "#    ifdef USESHADOWMAPPCF\n"
1205 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
1206 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1207 "       f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1208 "#    else\n"
1209 "       f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1210 "#    endif\n"
1211 "#  else\n"
1212 "#    ifdef USESHADOWMAPPCF\n"
1213 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1214 "#      ifdef GL_ARB_texture_gather\n"
1215 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1216 "#      else\n"
1217 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1218 "#      endif\n"
1219 "       vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1220 "#      if USESHADOWMAPPCF > 1\n"
1221 "   vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1222 "   vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1223 "   vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1224 "   vec4 group4 = step(shadowmaptc.z, texval(-2.0,  0.0));\n"
1225 "   vec4 group5 = step(shadowmaptc.z, texval( 0.0,  0.0));\n"
1226 "   vec4 group6 = step(shadowmaptc.z, texval( 2.0,  0.0));\n"
1227 "   vec4 group7 = step(shadowmaptc.z, texval(-2.0,  2.0));\n"
1228 "   vec4 group8 = step(shadowmaptc.z, texval( 0.0,  2.0));\n"
1229 "   vec4 group9 = step(shadowmaptc.z, texval( 2.0,  2.0));\n"
1230 "       vec4 locols = vec4(group1.ab, group3.ab);\n"
1231 "       vec4 hicols = vec4(group7.rg, group9.rg);\n"
1232 "       locols.yz += group2.ab;\n"
1233 "       hicols.yz += group8.rg;\n"
1234 "       vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1235 "                               vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1236 "                               mix(locols, hicols, offset.y);\n"
1237 "       vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1238 "       cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1239 "       f = dot(cols, vec4(1.0/25.0));\n"
1240 "#      else\n"
1241 "       vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1242 "       vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1243 "       vec4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
1244 "       vec4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
1245 "       vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1246 "                               mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1247 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1248 "#      endif\n"
1249 "#     else\n"
1250 "#      ifdef GL_EXT_gpu_shader4\n"
1251 "#        define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1252 "#      else\n"
1253 "#        define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r  \n"
1254 "#      endif\n"
1255 "#      if USESHADOWMAPPCF > 1\n"
1256 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1257 "       center *= ShadowMap_TextureScale;\n"
1258 "       vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1259 "       vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1260 "       vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1261 "       vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1262 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1263 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1264 "#      else\n"
1265 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1266 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1267 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1268 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1269 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1270 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1271 "#      endif\n"
1272 "#     endif\n"
1273 "#    else\n"
1274 "       f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1275 "#    endif\n"
1276 "#  endif\n"
1277 "#  ifdef USESHADOWMAPORTHO\n"
1278 "       return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1279 "#  else\n"
1280 "       return f;\n"
1281 "#  endif\n"
1282 "}\n"
1283 "# endif\n"
1284 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1285 "#endif // FRAGMENT_SHADER\n"
1286 "\n"
1287 "\n"
1288 "\n"
1289 "\n"
1290 "#ifdef MODE_DEFERREDGEOMETRY\n"
1291 "#ifdef VERTEX_SHADER\n"
1292 "uniform mat4 TexMatrix;\n"
1293 "#ifdef USEVERTEXTEXTUREBLEND\n"
1294 "uniform mat4 BackgroundTexMatrix;\n"
1295 "#endif\n"
1296 "uniform mat4 ModelViewMatrix;\n"
1297 "void main(void)\n"
1298 "{\n"
1299 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1300 "#ifdef USEVERTEXTEXTUREBLEND\n"
1301 "       gl_FrontColor = gl_Color;\n"
1302 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1303 "#endif\n"
1304 "\n"
1305 "       // transform unnormalized eye direction into tangent space\n"
1306 "#ifdef USEOFFSETMAPPING\n"
1307 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1308 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1309 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1310 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1311 "#endif\n"
1312 "\n"
1313 "       VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1314 "       VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1315 "       VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1316 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1317 "}\n"
1318 "#endif // VERTEX_SHADER\n"
1319 "\n"
1320 "#ifdef FRAGMENT_SHADER\n"
1321 "void main(void)\n"
1322 "{\n"
1323 "#ifdef USEOFFSETMAPPING\n"
1324 "       // apply offsetmapping\n"
1325 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1326 "#define TexCoord TexCoordOffset\n"
1327 "#endif\n"
1328 "\n"
1329 "#ifdef USEALPHAKILL\n"
1330 "       if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1331 "               discard;\n"
1332 "#endif\n"
1333 "\n"
1334 "#ifdef USEVERTEXTEXTUREBLEND\n"
1335 "       float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1336 "       float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1337 "       //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1338 "       //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1339 "#endif\n"
1340 "\n"
1341 "#ifdef USEVERTEXTEXTUREBLEND\n"
1342 "       vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1343 "       float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1344 "#else\n"
1345 "       vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1346 "       float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1347 "#endif\n"
1348 "\n"
1349 "       gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1350 "}\n"
1351 "#endif // FRAGMENT_SHADER\n"
1352 "#else // !MODE_DEFERREDGEOMETRY\n"
1353 "\n"
1354 "\n"
1355 "\n"
1356 "\n"
1357 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1358 "#ifdef VERTEX_SHADER\n"
1359 "uniform mat4 ModelViewMatrix;\n"
1360 "void main(void)\n"
1361 "{\n"
1362 "       ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1363 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1364 "}\n"
1365 "#endif // VERTEX_SHADER\n"
1366 "\n"
1367 "#ifdef FRAGMENT_SHADER\n"
1368 "uniform mat4 ViewToLight;\n"
1369 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1370 "uniform vec2 ScreenToDepth;\n"
1371 "uniform myhalf3 DeferredColor_Ambient;\n"
1372 "uniform myhalf3 DeferredColor_Diffuse;\n"
1373 "#ifdef USESPECULAR\n"
1374 "uniform myhalf3 DeferredColor_Specular;\n"
1375 "uniform myhalf SpecularPower;\n"
1376 "#endif\n"
1377 "uniform myhalf2 PixelToScreenTexCoord;\n"
1378 "void main(void)\n"
1379 "{\n"
1380 "       // calculate viewspace pixel position\n"
1381 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1382 "       vec3 position;\n"
1383 "       position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1384 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1385 "       // decode viewspace pixel normal\n"
1386 "       myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1387 "       myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1388 "       // surfacenormal = pixel normal in viewspace\n"
1389 "       // LightVector = pixel to light in viewspace\n"
1390 "       // CubeVector = position in lightspace\n"
1391 "       // eyevector = pixel to view in viewspace\n"
1392 "       vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1393 "       myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1394 "#ifdef USEDIFFUSE\n"
1395 "       // calculate diffuse shading\n"
1396 "       myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1397 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1398 "#endif\n"
1399 "#ifdef USESPECULAR\n"
1400 "       // calculate directional shading\n"
1401 "       vec3 eyevector = position * -1.0;\n"
1402 "#  ifdef USEEXACTSPECULARMATH\n"
1403 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1404 "#  else\n"
1405 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1406 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1407 "#  endif\n"
1408 "#endif\n"
1409 "\n"
1410 "#if defined(USESHADOWMAP2D)\n"
1411 "       fade *= ShadowMapCompare(CubeVector);\n"
1412 "#endif\n"
1413 "\n"
1414 "#ifdef USEDIFFUSE\n"
1415 "       gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1416 "#else\n"
1417 "       gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1418 "#endif\n"
1419 "#ifdef USESPECULAR\n"
1420 "       gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1421 "#else\n"
1422 "       gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1423 "#endif\n"
1424 "\n"
1425 "# ifdef USECUBEFILTER\n"
1426 "       vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1427 "       gl_FragData[0].rgb *= cubecolor;\n"
1428 "       gl_FragData[1].rgb *= cubecolor;\n"
1429 "# endif\n"
1430 "}\n"
1431 "#endif // FRAGMENT_SHADER\n"
1432 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1433 "\n"
1434 "\n"
1435 "\n"
1436 "\n"
1437 "#ifdef VERTEX_SHADER\n"
1438 "uniform mat4 TexMatrix;\n"
1439 "#ifdef USEVERTEXTEXTUREBLEND\n"
1440 "uniform mat4 BackgroundTexMatrix;\n"
1441 "#endif\n"
1442 "#ifdef MODE_LIGHTSOURCE\n"
1443 "uniform mat4 ModelToLight;\n"
1444 "#endif\n"
1445 "#ifdef USESHADOWMAPORTHO\n"
1446 "uniform mat4 ShadowMapMatrix;\n"
1447 "#endif\n"
1448 "void main(void)\n"
1449 "{\n"
1450 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1451 "       gl_FrontColor = gl_Color;\n"
1452 "#endif\n"
1453 "       // copy the surface texcoord\n"
1454 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1455 "#ifdef USEVERTEXTEXTUREBLEND\n"
1456 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1457 "#endif\n"
1458 "#ifdef USELIGHTMAP\n"
1459 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1460 "#endif\n"
1461 "\n"
1462 "#ifdef MODE_LIGHTSOURCE\n"
1463 "       // transform vertex position into light attenuation/cubemap space\n"
1464 "       // (-1 to +1 across the light box)\n"
1465 "       CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1466 "\n"
1467 "# ifdef USEDIFFUSE\n"
1468 "       // transform unnormalized light direction into tangent space\n"
1469 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
1470 "       //  normalize it per pixel)\n"
1471 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1472 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1473 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1474 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1475 "# endif\n"
1476 "#endif\n"
1477 "\n"
1478 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1479 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1480 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1481 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1482 "#endif\n"
1483 "\n"
1484 "       // transform unnormalized eye direction into tangent space\n"
1485 "#ifdef USEEYEVECTOR\n"
1486 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1487 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1488 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1489 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1490 "#endif\n"
1491 "\n"
1492 "#ifdef USEFOG\n"
1493 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1494 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1495 "#endif\n"
1496 "\n"
1497 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1498 "       VectorS = gl_MultiTexCoord1.xyz;\n"
1499 "       VectorT = gl_MultiTexCoord2.xyz;\n"
1500 "       VectorR = gl_MultiTexCoord3.xyz;\n"
1501 "#endif\n"
1502 "\n"
1503 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1504 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1505 "\n"
1506 "#ifdef USESHADOWMAPORTHO\n"
1507 "       ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1508 "#endif\n"
1509 "\n"
1510 "#ifdef USEREFLECTION\n"
1511 "       ModelViewProjectionPosition = gl_Position;\n"
1512 "#endif\n"
1513 "}\n"
1514 "#endif // VERTEX_SHADER\n"
1515 "\n"
1516 "\n"
1517 "\n"
1518 "\n"
1519 "#ifdef FRAGMENT_SHADER\n"
1520 "#ifdef USEDEFERREDLIGHTMAP\n"
1521 "uniform myhalf2 PixelToScreenTexCoord;\n"
1522 "uniform myhalf3 DeferredMod_Diffuse;\n"
1523 "uniform myhalf3 DeferredMod_Specular;\n"
1524 "#endif\n"
1525 "uniform myhalf3 Color_Ambient;\n"
1526 "uniform myhalf3 Color_Diffuse;\n"
1527 "uniform myhalf3 Color_Specular;\n"
1528 "uniform myhalf SpecularPower;\n"
1529 "#ifdef USEGLOW\n"
1530 "uniform myhalf3 Color_Glow;\n"
1531 "#endif\n"
1532 "uniform myhalf Alpha;\n"
1533 "#ifdef USEREFLECTION\n"
1534 "uniform vec4 DistortScaleRefractReflect;\n"
1535 "uniform vec4 ScreenScaleRefractReflect;\n"
1536 "uniform vec4 ScreenCenterRefractReflect;\n"
1537 "uniform myhalf4 ReflectColor;\n"
1538 "#endif\n"
1539 "#ifdef USEREFLECTCUBE\n"
1540 "uniform mat4 ModelToReflectCube;\n"
1541 "uniform sampler2D Texture_ReflectMask;\n"
1542 "uniform samplerCube Texture_ReflectCube;\n"
1543 "#endif\n"
1544 "#ifdef MODE_LIGHTDIRECTION\n"
1545 "uniform myhalf3 LightColor;\n"
1546 "#endif\n"
1547 "#ifdef MODE_LIGHTSOURCE\n"
1548 "uniform myhalf3 LightColor;\n"
1549 "#endif\n"
1550 "void main(void)\n"
1551 "{\n"
1552 "#ifdef USEOFFSETMAPPING\n"
1553 "       // apply offsetmapping\n"
1554 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1555 "#define TexCoord TexCoordOffset\n"
1556 "#endif\n"
1557 "\n"
1558 "       // combine the diffuse textures (base, pants, shirt)\n"
1559 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1560 "#ifdef USEALPHAKILL\n"
1561 "       if (color.a < 0.5)\n"
1562 "               discard;\n"
1563 "#endif\n"
1564 "       color.a *= Alpha;\n"
1565 "#ifdef USECOLORMAPPING\n"
1566 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1567 "#endif\n"
1568 "#ifdef USEVERTEXTEXTUREBLEND\n"
1569 "       myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1570 "       //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1571 "       //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1572 "       color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1573 "       color.a = 1.0;\n"
1574 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1575 "#endif\n"
1576 "\n"
1577 "       // get the surface normal\n"
1578 "#ifdef USEVERTEXTEXTUREBLEND\n"
1579 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1580 "#else\n"
1581 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1582 "#endif\n"
1583 "\n"
1584 "       // get the material colors\n"
1585 "       myhalf3 diffusetex = color.rgb;\n"
1586 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1587 "# ifdef USEVERTEXTEXTUREBLEND\n"
1588 "       myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1589 "# else\n"
1590 "       myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1591 "# endif\n"
1592 "#endif\n"
1593 "\n"
1594 "#ifdef USEREFLECTCUBE\n"
1595 "       vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1596 "       vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1597 "       vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1598 "       diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1599 "#endif\n"
1600 "\n"
1601 "\n"
1602 "\n"
1603 "\n"
1604 "#ifdef MODE_LIGHTSOURCE\n"
1605 "       // light source\n"
1606 "#ifdef USEDIFFUSE\n"
1607 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1608 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1609 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1610 "#ifdef USESPECULAR\n"
1611 "#ifdef USEEXACTSPECULARMATH\n"
1612 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1613 "#else\n"
1614 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1615 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1616 "#endif\n"
1617 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1618 "#endif\n"
1619 "#else\n"
1620 "       color.rgb = diffusetex * Color_Ambient;\n"
1621 "#endif\n"
1622 "       color.rgb *= LightColor;\n"
1623 "       color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1624 "#if defined(USESHADOWMAP2D)\n"
1625 "       color.rgb *= ShadowMapCompare(CubeVector);\n"
1626 "#endif\n"
1627 "# ifdef USECUBEFILTER\n"
1628 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1629 "# endif\n"
1630 "#endif // MODE_LIGHTSOURCE\n"
1631 "\n"
1632 "\n"
1633 "\n"
1634 "\n"
1635 "#ifdef MODE_LIGHTDIRECTION\n"
1636 "#define SHADING\n"
1637 "#ifdef USEDIFFUSE\n"
1638 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1639 "#endif\n"
1640 "#define lightcolor LightColor\n"
1641 "#endif // MODE_LIGHTDIRECTION\n"
1642 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1643 "#define SHADING\n"
1644 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1645 "       myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1646 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1647 "       // convert modelspace light vector to tangentspace\n"
1648 "       myhalf3 lightnormal;\n"
1649 "       lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1650 "       lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1651 "       lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1652 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1653 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1654 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1655 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1656 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1657 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1658 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1659 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1660 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1661 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1662 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1663 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1664 "#define SHADING\n"
1665 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1666 "       myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1667 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1668 "#endif\n"
1669 "\n"
1670 "\n"
1671 "\n"
1672 "\n"
1673 "#ifdef MODE_FAKELIGHT\n"
1674 "#define SHADING\n"
1675 "myhalf3 lightnormal = myhalf3(normalize(EyeVector));\n"
1676 "myhalf3 lightcolor = myhalf3(1.0);\n"
1677 "#endif // MODE_FAKELIGHT\n"
1678 "\n"
1679 "\n"
1680 "\n"
1681 "\n"
1682 "#ifdef MODE_LIGHTMAP\n"
1683 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1684 "#endif // MODE_LIGHTMAP\n"
1685 "#ifdef MODE_VERTEXCOLOR\n"
1686 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1687 "#endif // MODE_VERTEXCOLOR\n"
1688 "#ifdef MODE_FLATCOLOR\n"
1689 "       color.rgb = diffusetex * Color_Ambient;\n"
1690 "#endif // MODE_FLATCOLOR\n"
1691 "\n"
1692 "\n"
1693 "\n"
1694 "\n"
1695 "#ifdef SHADING\n"
1696 "# ifdef USEDIFFUSE\n"
1697 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1698 "#  ifdef USESPECULAR\n"
1699 "#   ifdef USEEXACTSPECULARMATH\n"
1700 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1701 "#   else\n"
1702 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1703 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1704 "#   endif\n"
1705 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1706 "#  else\n"
1707 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1708 "#  endif\n"
1709 "# else\n"
1710 "       color.rgb = diffusetex * Color_Ambient;\n"
1711 "# endif\n"
1712 "#endif\n"
1713 "\n"
1714 "#ifdef USESHADOWMAPORTHO\n"
1715 "       color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1716 "#endif\n"
1717 "\n"
1718 "#ifdef USEDEFERREDLIGHTMAP\n"
1719 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1720 "       color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1721 "       color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1722 "#endif\n"
1723 "\n"
1724 "#ifdef USEGLOW\n"
1725 "#ifdef USEVERTEXTEXTUREBLEND\n"
1726 "       color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1727 "#else\n"
1728 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1729 "#endif\n"
1730 "#endif\n"
1731 "\n"
1732 "#ifdef USEFOG\n"
1733 "       color.rgb = FogVertex(color.rgb);\n"
1734 "#endif\n"
1735 "\n"
1736 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1737 "#ifdef USEREFLECTION\n"
1738 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1739 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1740 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1741 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1742 "       // FIXME temporary hack to detect the case that the reflection\n"
1743 "       // gets blackened at edges due to leaving the area that contains actual\n"
1744 "       // content.\n"
1745 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1746 "       // 'appening.\n"
1747 "       float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1748 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1749 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1750 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1751 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1752 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1753 "#endif\n"
1754 "\n"
1755 "       gl_FragColor = vec4(color);\n"
1756 "}\n"
1757 "#endif // FRAGMENT_SHADER\n"
1758 "\n"
1759 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1760 "#endif // !MODE_DEFERREDGEOMETRY\n"
1761 "#endif // !MODE_WATER\n"
1762 "#endif // !MODE_REFRACTION\n"
1763 "#endif // !MODE_BLOOMBLUR\n"
1764 "#endif // !MODE_GENERIC\n"
1765 "#endif // !MODE_POSTPROCESS\n"
1766 "#endif // !MODE_SHOWDEPTH\n"
1767 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1768 ;
1769
1770 /*
1771 =========================================================================================================================================================
1772
1773
1774
1775 =========================================================================================================================================================
1776
1777
1778
1779 =========================================================================================================================================================
1780
1781
1782
1783 =========================================================================================================================================================
1784
1785
1786
1787 =========================================================================================================================================================
1788
1789
1790
1791 =========================================================================================================================================================
1792
1793
1794
1795 =========================================================================================================================================================
1796 */
1797
1798 const char *builtincgshaderstring =
1799 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1800 "// written by Forest 'LordHavoc' Hale\n"
1801 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1802 "\n"
1803 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1804 "#if defined(USEREFLECTION)\n"
1805 "#undef USESHADOWMAPORTHO\n"
1806 "#endif\n"
1807 "\n"
1808 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1809 "# define USEFOG\n"
1810 "#endif\n"
1811 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1812 "#define USELIGHTMAP\n"
1813 "#endif\n"
1814 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
1815 "#define USEEYEVECTOR\n"
1816 "#endif\n"
1817 "\n"
1818 "#ifdef FRAGMENT_SHADER\n"
1819 "#ifdef HLSL\n"
1820 "//#undef USESHADOWMAPPCF\n"
1821 "//#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1822 "#define texDepth2D(tex,texcoord) dot(tex2D(tex,texcoord).rgb, float3(1.0, 255.0/65536.0, 255.0/16777216.0))\n"
1823 "#else\n"
1824 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1825 "#endif\n"
1826 "#endif\n"
1827 "\n"
1828 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1829 "#ifdef VERTEX_SHADER\n"
1830 "void main\n"
1831 "(\n"
1832 "float4 gl_Vertex : POSITION,\n"
1833 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1834 "out float4 gl_Position : POSITION,\n"
1835 "out float Depth : TEXCOORD0\n"
1836 ")\n"
1837 "{\n"
1838 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1839 "       Depth = gl_Position.z;\n"
1840 "}\n"
1841 "#endif\n"
1842 "\n"
1843 "#ifdef FRAGMENT_SHADER\n"
1844 "void main\n"
1845 "(\n"
1846 "float Depth : TEXCOORD0,\n"
1847 "out float4 gl_FragColor : COLOR\n"
1848 ")\n"
1849 "{\n"
1850 "//     float3 temp = float3(Depth,Depth*(65536.0/255.0),Depth*(16777216.0/255.0));\n"
1851 "       float4 temp = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
1852 "       temp.yz -= floor(temp.yz);\n"
1853 "       gl_FragColor = temp;\n"
1854 "//     gl_FragColor = float4(Depth,0,0,0);\n"
1855 "}\n"
1856 "#endif\n"
1857 "#else // !MODE_DEPTH_ORSHADOW\n"
1858 "\n"
1859 "\n"
1860 "\n"
1861 "\n"
1862 "#ifdef MODE_SHOWDEPTH\n"
1863 "#ifdef VERTEX_SHADER\n"
1864 "void main\n"
1865 "(\n"
1866 "float4 gl_Vertex : POSITION,\n"
1867 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1868 "out float4 gl_Position : POSITION,\n"
1869 "out float4 gl_FrontColor : COLOR0\n"
1870 ")\n"
1871 "{\n"
1872 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1873 "       gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1874 "}\n"
1875 "#endif\n"
1876 "\n"
1877 "#ifdef FRAGMENT_SHADER\n"
1878 "void main\n"
1879 "(\n"
1880 "float4 gl_FrontColor : COLOR0,\n"
1881 "out float4 gl_FragColor : COLOR\n"
1882 ")\n"
1883 "{\n"
1884 "       gl_FragColor = gl_FrontColor;\n"
1885 "}\n"
1886 "#endif\n"
1887 "#else // !MODE_SHOWDEPTH\n"
1888 "\n"
1889 "\n"
1890 "\n"
1891 "\n"
1892 "#ifdef MODE_POSTPROCESS\n"
1893 "\n"
1894 "#ifdef VERTEX_SHADER\n"
1895 "void main\n"
1896 "(\n"
1897 "float4 gl_Vertex : POSITION,\n"
1898 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1899 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1900 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
1901 "out float4 gl_Position : POSITION,\n"
1902 "out float2 TexCoord1 : TEXCOORD0,\n"
1903 "out float2 TexCoord2 : TEXCOORD1\n"
1904 ")\n"
1905 "{\n"
1906 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1907 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
1908 "#ifdef USEBLOOM\n"
1909 "       TexCoord2 = gl_MultiTexCoord4.xy;\n"
1910 "#endif\n"
1911 "}\n"
1912 "#endif\n"
1913 "\n"
1914 "#ifdef FRAGMENT_SHADER\n"
1915 "void main\n"
1916 "(\n"
1917 "float2 TexCoord1 : TEXCOORD0,\n"
1918 "float2 TexCoord2 : TEXCOORD1,\n"
1919 "uniform sampler Texture_First : register(s0),\n"
1920 "#ifdef USEBLOOM\n"
1921 "uniform sampler Texture_Second : register(s1),\n"
1922 "#endif\n"
1923 "#ifdef USEGAMMARAMPS\n"
1924 "uniform sampler Texture_GammaRamps : register(s2),\n"
1925 "#endif\n"
1926 "#ifdef USESATURATION\n"
1927 "uniform float Saturation : register(c30),\n"
1928 "#endif\n"
1929 "#ifdef USEVIEWTINT\n"
1930 "uniform float4 ViewTintColor : register(c41),\n"
1931 "#endif\n"
1932 "uniform float4 UserVec1 : register(c37),\n"
1933 "uniform float4 UserVec2 : register(c38),\n"
1934 "uniform float4 UserVec3 : register(c39),\n"
1935 "uniform float4 UserVec4 : register(c40),\n"
1936 "uniform float ClientTime : register(c2),\n"
1937 "uniform float2 PixelSize : register(c25),\n"
1938 "uniform float4 BloomColorSubtract : register(c43),\n"
1939 "out float4 gl_FragColor : COLOR\n"
1940 ")\n"
1941 "{\n"
1942 "       gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1943 "#ifdef USEBLOOM\n"
1944 "       gl_FragColor += max(float4(0,0,0,0), tex2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
1945 "#endif\n"
1946 "#ifdef USEVIEWTINT\n"
1947 "       gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1948 "#endif\n"
1949 "\n"
1950 "#ifdef USEPOSTPROCESSING\n"
1951 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1952 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
1953 "       float sobel = 1.0;\n"
1954 "       // float2 ts = textureSize(Texture_First, 0);\n"
1955 "       // float2 px = float2(1/ts.x, 1/ts.y);\n"
1956 "       float2 px = PixelSize;\n"
1957 "       float3 x1 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
1958 "       float3 x2 = tex2D(Texture_First, TexCoord1 + float2(-px.x,  0.0)).rgb;\n"
1959 "       float3 x3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
1960 "       float3 x4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
1961 "       float3 x5 = tex2D(Texture_First, TexCoord1 + float2( px.x,  0.0)).rgb;\n"
1962 "       float3 x6 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
1963 "       float3 y1 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
1964 "       float3 y2 = tex2D(Texture_First, TexCoord1 + float2(  0.0,-px.y)).rgb;\n"
1965 "       float3 y3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
1966 "       float3 y4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
1967 "       float3 y5 = tex2D(Texture_First, TexCoord1 + float2(  0.0, px.y)).rgb;\n"
1968 "       float3 y6 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
1969 "       float px1 = -1.0 * dot(float3(0.3, 0.59, 0.11), x1);\n"
1970 "       float px2 = -2.0 * dot(float3(0.3, 0.59, 0.11), x2);\n"
1971 "       float px3 = -1.0 * dot(float3(0.3, 0.59, 0.11), x3);\n"
1972 "       float px4 =  1.0 * dot(float3(0.3, 0.59, 0.11), x4);\n"
1973 "       float px5 =  2.0 * dot(float3(0.3, 0.59, 0.11), x5);\n"
1974 "       float px6 =  1.0 * dot(float3(0.3, 0.59, 0.11), x6);\n"
1975 "       float py1 = -1.0 * dot(float3(0.3, 0.59, 0.11), y1);\n"
1976 "       float py2 = -2.0 * dot(float3(0.3, 0.59, 0.11), y2);\n"
1977 "       float py3 = -1.0 * dot(float3(0.3, 0.59, 0.11), y3);\n"
1978 "       float py4 =  1.0 * dot(float3(0.3, 0.59, 0.11), y4);\n"
1979 "       float py5 =  2.0 * dot(float3(0.3, 0.59, 0.11), y5);\n"
1980 "       float py6 =  1.0 * dot(float3(0.3, 0.59, 0.11), y6);\n"
1981 "       sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
1982 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1983 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1984 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1985 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107,  0.707107)) * UserVec1.y;\n"
1986 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990,  0.891007)) * UserVec1.y;\n"
1987 "       gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
1988 "       gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + float3(1,1,1)*max(0.0, sobel - UserVec2.z)*UserVec2.y;\n"
1989 "#endif\n"
1990 "\n"
1991 "#ifdef USESATURATION\n"
1992 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
1993 "       float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
1994 "       //gl_FragColor = float3(y,y,y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
1995 "       gl_FragColor.rgb = lerp(float3(y,y,y), gl_FragColor.rgb, Saturation);\n"
1996 "#endif\n"
1997 "\n"
1998 "#ifdef USEGAMMARAMPS\n"
1999 "       gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2000 "       gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2001 "       gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2002 "#endif\n"
2003 "}\n"
2004 "#endif\n"
2005 "#else // !MODE_POSTPROCESS\n"
2006 "\n"
2007 "\n"
2008 "\n"
2009 "\n"
2010 "#ifdef MODE_GENERIC\n"
2011 "#ifdef VERTEX_SHADER\n"
2012 "void main\n"
2013 "(\n"
2014 "float4 gl_Vertex : POSITION,\n"
2015 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2016 "float4 gl_Color : COLOR0,\n"
2017 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2018 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2019 "out float4 gl_Position : POSITION,\n"
2020 "#ifdef USEDIFFUSE\n"
2021 "out float2 TexCoord1 : TEXCOORD0,\n"
2022 "#endif\n"
2023 "#ifdef USESPECULAR\n"
2024 "out float2 TexCoord2 : TEXCOORD1,\n"
2025 "#endif\n"
2026 "out float4 gl_FrontColor : COLOR\n"
2027 ")\n"
2028 "{\n"
2029 "#ifdef HLSL\n"
2030 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2031 "#else\n"
2032 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2033 "#endif\n"
2034 "#ifdef USEDIFFUSE\n"
2035 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
2036 "#endif\n"
2037 "#ifdef USESPECULAR\n"
2038 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
2039 "#endif\n"
2040 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2041 "}\n"
2042 "#endif\n"
2043 "\n"
2044 "#ifdef FRAGMENT_SHADER\n"
2045 "\n"
2046 "void main\n"
2047 "(\n"
2048 "float4 gl_FrontColor : COLOR0,\n"
2049 "float2 TexCoord1 : TEXCOORD0,\n"
2050 "float2 TexCoord2 : TEXCOORD1,\n"
2051 "#ifdef USEDIFFUSE\n"
2052 "uniform sampler Texture_First : register(s0),\n"
2053 "#endif\n"
2054 "#ifdef USESPECULAR\n"
2055 "uniform sampler Texture_Second : register(s1),\n"
2056 "#endif\n"
2057 "out float4 gl_FragColor : COLOR\n"
2058 ")\n"
2059 "{\n"
2060 "       gl_FragColor = gl_FrontColor;\n"
2061 "#ifdef USEDIFFUSE\n"
2062 "       gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2063 "#endif\n"
2064 "\n"
2065 "#ifdef USESPECULAR\n"
2066 "       float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2067 "# ifdef USECOLORMAPPING\n"
2068 "       gl_FragColor *= tex2;\n"
2069 "# endif\n"
2070 "# ifdef USEGLOW\n"
2071 "       gl_FragColor += tex2;\n"
2072 "# endif\n"
2073 "# ifdef USEVERTEXTEXTUREBLEND\n"
2074 "       gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2075 "# endif\n"
2076 "#endif\n"
2077 "}\n"
2078 "#endif\n"
2079 "#else // !MODE_GENERIC\n"
2080 "\n"
2081 "\n"
2082 "\n"
2083 "\n"
2084 "#ifdef MODE_BLOOMBLUR\n"
2085 "#ifdef VERTEX_SHADER\n"
2086 "void main\n"
2087 "(\n"
2088 "float4 gl_Vertex : POSITION,\n"
2089 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2090 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2091 "out float4 gl_Position : POSITION,\n"
2092 "out float2 TexCoord : TEXCOORD0\n"
2093 ")\n"
2094 "{\n"
2095 "       TexCoord = gl_MultiTexCoord0.xy;\n"
2096 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2097 "}\n"
2098 "#endif\n"
2099 "\n"
2100 "#ifdef FRAGMENT_SHADER\n"
2101 "\n"
2102 "void main\n"
2103 "(\n"
2104 "float2 TexCoord : TEXCOORD0,\n"
2105 "uniform sampler Texture_First : register(s0),\n"
2106 "uniform float4 BloomBlur_Parameters : register(c1),\n"
2107 "out float4 gl_FragColor : COLOR\n"
2108 ")\n"
2109 "{\n"
2110 "       int i;\n"
2111 "       float2 tc = TexCoord;\n"
2112 "       float3 color = tex2D(Texture_First, tc).rgb;\n"
2113 "       tc += BloomBlur_Parameters.xy;\n"
2114 "       for (i = 1;i < SAMPLES;i++)\n"
2115 "       {\n"
2116 "               color += tex2D(Texture_First, tc).rgb;\n"
2117 "               tc += BloomBlur_Parameters.xy;\n"
2118 "       }\n"
2119 "       gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2120 "}\n"
2121 "#endif\n"
2122 "#else // !MODE_BLOOMBLUR\n"
2123 "#ifdef MODE_REFRACTION\n"
2124 "#ifdef VERTEX_SHADER\n"
2125 "void main\n"
2126 "(\n"
2127 "float4 gl_Vertex : POSITION,\n"
2128 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2129 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2130 "uniform float4x4 TexMatrix : register(c0),\n"
2131 "uniform float3 EyePosition : register(c24),\n"
2132 "out float4 gl_Position : POSITION,\n"
2133 "out float2 TexCoord : TEXCOORD0,\n"
2134 "out float3 EyeVector : TEXCOORD1,\n"
2135 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2136 ")\n"
2137 "{\n"
2138 "       TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2139 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2140 "       ModelViewProjectionPosition = gl_Position;\n"
2141 "}\n"
2142 "#endif\n"
2143 "\n"
2144 "#ifdef FRAGMENT_SHADER\n"
2145 "void main\n"
2146 "(\n"
2147 "float2 TexCoord : TEXCOORD0,\n"
2148 "float3 EyeVector : TEXCOORD1,\n"
2149 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2150 "uniform sampler Texture_Normal : register(s0),\n"
2151 "uniform sampler Texture_Refraction : register(s3),\n"
2152 "uniform sampler Texture_Reflection : register(s7),\n"
2153 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2154 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2155 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2156 "uniform float4 RefractColor : register(c29),\n"
2157 "out float4 gl_FragColor : COLOR\n"
2158 ")\n"
2159 "{\n"
2160 "       float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2161 "       //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2162 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2163 "       float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.xy;\n"
2164 "       // FIXME temporary hack to detect the case that the reflection\n"
2165 "       // gets blackened at edges due to leaving the area that contains actual\n"
2166 "       // content.\n"
2167 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2168 "       // 'appening.\n"
2169 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2170 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2171 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2172 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2173 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2174 "       gl_FragColor = float4(tex2D(Texture_Refraction, ScreenTexCoord).rgb, 1) * RefractColor;\n"
2175 "}\n"
2176 "#endif\n"
2177 "#else // !MODE_REFRACTION\n"
2178 "\n"
2179 "\n"
2180 "\n"
2181 "\n"
2182 "#ifdef MODE_WATER\n"
2183 "#ifdef VERTEX_SHADER\n"
2184 "\n"
2185 "void main\n"
2186 "(\n"
2187 "float4 gl_Vertex : POSITION,\n"
2188 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2189 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2190 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2191 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2192 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2193 "uniform float4x4 TexMatrix : register(c0),\n"
2194 "uniform float3 EyePosition : register(c24),\n"
2195 "out float4 gl_Position : POSITION,\n"
2196 "out float2 TexCoord : TEXCOORD0,\n"
2197 "out float3 EyeVector : TEXCOORD1,\n"
2198 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2199 ")\n"
2200 "{\n"
2201 "       TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2202 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2203 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2204 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2205 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2206 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2207 "       ModelViewProjectionPosition = gl_Position;\n"
2208 "}\n"
2209 "#endif\n"
2210 "\n"
2211 "#ifdef FRAGMENT_SHADER\n"
2212 "void main\n"
2213 "(\n"
2214 "float2 TexCoord : TEXCOORD0,\n"
2215 "float3 EyeVector : TEXCOORD1,\n"
2216 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2217 "uniform sampler Texture_Normal : register(s0),\n"
2218 "uniform sampler Texture_Refraction : register(s3),\n"
2219 "uniform sampler Texture_Reflection : register(s7),\n"
2220 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2221 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2222 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2223 "uniform float4 RefractColor : register(c29),\n"
2224 "uniform float4 ReflectColor : register(c26),\n"
2225 "uniform float ReflectFactor : register(c27),\n"
2226 "uniform float ReflectOffset : register(c28),\n"
2227 "out float4 gl_FragColor : COLOR\n"
2228 ")\n"
2229 "{\n"
2230 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2231 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2232 "       float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2233 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * float4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
2234 "       float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy).xyxy * DistortScaleRefractReflect;\n"
2235 "       // FIXME temporary hack to detect the case that the reflection\n"
2236 "       // gets blackened at edges due to leaving the area that contains actual\n"
2237 "       // content.\n"
2238 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2239 "       // 'appening.\n"
2240 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2241 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2242 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2243 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2244 "       ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2245 "       f       = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2246 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2247 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2248 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2249 "       ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2250 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2251 "       gl_FragColor = lerp(float4(tex2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, float4(tex2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
2252 "}\n"
2253 "#endif\n"
2254 "#else // !MODE_WATER\n"
2255 "\n"
2256 "\n"
2257 "\n"
2258 "\n"
2259 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
2260 "\n"
2261 "// fragment shader specific:\n"
2262 "#ifdef FRAGMENT_SHADER\n"
2263 "\n"
2264 "#ifdef USEFOG\n"
2265 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler Texture_FogMask, sampler Texture_FogHeightTexture)\n"
2266 "{\n"
2267 "       float fogfrac;\n"
2268 "#ifdef USEFOGHEIGHTTEXTURE\n"
2269 "       float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2270 "       fogfrac = fogheightpixel.a;\n"
2271 "       return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2272 "#else\n"
2273 "# ifdef USEFOGOUTSIDE\n"
2274 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2275 "# else\n"
2276 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2277 "# endif\n"
2278 "       return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2279 "#endif\n"
2280 "}\n"
2281 "#endif\n"
2282 "\n"
2283 "#ifdef USEOFFSETMAPPING\n"
2284 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler Texture_Normal)\n"
2285 "{\n"
2286 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2287 "       // 14 sample relief mapping: linear search and then binary search\n"
2288 "       // this basically steps forward a small amount repeatedly until it finds\n"
2289 "       // itself inside solid, then jitters forward and back using decreasing\n"
2290 "       // amounts to find the impact\n"
2291 "       //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2292 "       //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2293 "       float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2294 "       float3 RT = float3(TexCoord, 1);\n"
2295 "       OffsetVector *= 0.1;\n"
2296 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2297 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2298 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2299 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2300 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2301 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2302 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2303 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2304 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2305 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
2306 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
2307 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
2308 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
2309 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2310 "       return RT.xy;\n"
2311 "#else\n"
2312 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2313 "       // this basically moves forward the full distance, and then backs up based\n"
2314 "       // on height of samples\n"
2315 "       //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2316 "       //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2317 "       float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2318 "       TexCoord += OffsetVector;\n"
2319 "       OffsetVector *= 0.333;\n"
2320 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2321 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2322 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2323 "       return TexCoord;\n"
2324 "#endif\n"
2325 "}\n"
2326 "#endif // USEOFFSETMAPPING\n"
2327 "\n"
2328 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2329 "#if defined(USESHADOWMAP2D)\n"
2330 "# ifdef USESHADOWMAPORTHO\n"
2331 "#  define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2332 "# else\n"
2333 "#  ifdef USESHADOWMAPVSDCT\n"
2334 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2335 "{\n"
2336 "       float3 adir = abs(dir);\n"
2337 "       float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2338 "       float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2339 "       return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2340 "}\n"
2341 "#  else\n"
2342 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2343 "{\n"
2344 "       float3 adir = abs(dir);\n"
2345 "       float ma = adir.z;\n"
2346 "       float4 proj = float4(dir, 2.5);\n"
2347 "       if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2348 "       if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2349 "#ifdef HLSL\n"
2350 "       return float3(proj.xy * ShadowMap_Parameters.x / ma + float2(0.5,0.5) + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, ma + 64 * ShadowMap_Parameters.w);\n"
2351 "#else\n"
2352 "       float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2353 "       return float3(proj.xy * aparams.x + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2354 "#endif\n"
2355 "}\n"
2356 "#  endif\n"
2357 "# endif\n"
2358 "#endif // defined(USESHADOWMAP2D)\n"
2359 "\n"
2360 "# ifdef USESHADOWMAP2D\n"
2361 "#ifdef USESHADOWMAPVSDCT\n"
2362 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2363 "#else\n"
2364 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2365 "#endif\n"
2366 "{\n"
2367 "#ifdef USESHADOWMAPVSDCT\n"
2368 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2369 "#else\n"
2370 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2371 "#endif\n"
2372 "       float f;\n"
2373 "\n"
2374 "#  ifdef USESHADOWSAMPLER\n"
2375 "#    ifdef USESHADOWMAPPCF\n"
2376 "#      define texval(x, y) tex2Dproj(Texture_ShadowMap2D, float4(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r  \n"
2377 "       float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2378 "       f = dot(float4(0.25,0.25,0.25,0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2379 "#    else\n"
2380 "       f = tex2Dproj(Texture_ShadowMap2D, float4(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r;\n"
2381 "#    endif\n"
2382 "#  else\n"
2383 "#    ifdef USESHADOWMAPPCF\n"
2384 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2385 "#      ifdef GL_ARB_texture_gather\n"
2386 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, int2(x, y))\n"
2387 "#      else\n"
2388 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)\n"
2389 "#      endif\n"
2390 "       float2 offset = frac(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
2391 "#      if USESHADOWMAPPCF > 1\n"
2392 "       float4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
2393 "       float4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
2394 "       float4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
2395 "       float4 group4 = step(shadowmaptc.z, texval(-2.0,  0.0));\n"
2396 "       float4 group5 = step(shadowmaptc.z, texval( 0.0,  0.0));\n"
2397 "       float4 group6 = step(shadowmaptc.z, texval( 2.0,  0.0));\n"
2398 "       float4 group7 = step(shadowmaptc.z, texval(-2.0,  2.0));\n"
2399 "       float4 group8 = step(shadowmaptc.z, texval( 0.0,  2.0));\n"
2400 "       float4 group9 = step(shadowmaptc.z, texval( 2.0,  2.0));\n"
2401 "       float4 locols = float4(group1.ab, group3.ab);\n"
2402 "       float4 hicols = float4(group7.rg, group9.rg);\n"
2403 "       locols.yz += group2.ab;\n"
2404 "       hicols.yz += group8.rg;\n"
2405 "       float4 midcols = float4(group1.rg, group3.rg) + float4(group7.ab, group9.ab) +\n"
2406 "                               float4(group4.rg, group6.rg) + float4(group4.ab, group6.ab) +\n"
2407 "                               lerp(locols, hicols, offset.y);\n"
2408 "       float4 cols = group5 + float4(group2.rg, group8.ab);\n"
2409 "       cols.xyz += lerp(midcols.xyz, midcols.yzw, offset.x);\n"
2410 "       f = dot(cols, float4(1.0/25.0));\n"
2411 "#      else\n"
2412 "       float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2413 "       float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2414 "       float4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
2415 "       float4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
2416 "       float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2417 "                               lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2418 "       f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2419 "#      endif\n"
2420 "#     else\n"
2421 "#      ifdef GL_EXT_gpu_shader4\n"
2422 "#        define texval(x, y) tex2DOffset(Texture_ShadowMap2D, center, int2(x, y)).r\n"
2423 "#      else\n"
2424 "#        define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale).r  \n"
2425 "#      endif\n"
2426 "#      if USESHADOWMAPPCF > 1\n"
2427 "       float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2428 "       center *= ShadowMap_TextureScale;\n"
2429 "       float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2430 "       float4 row2 = step(shadowmaptc.z, float4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
2431 "       float4 row3 = step(shadowmaptc.z, float4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
2432 "       float4 row4 = step(shadowmaptc.z, float4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
2433 "       float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2434 "       f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2435 "#      else\n"
2436 "       float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2437 "       float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2438 "       float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2439 "       float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2440 "       float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2441 "       f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25,0.25));\n"
2442 "#      endif\n"
2443 "#     endif\n"
2444 "#    else\n"
2445 "       f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2446 "#    endif\n"
2447 "#  endif\n"
2448 "#  ifdef USESHADOWMAPORTHO\n"
2449 "       return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2450 "#  else\n"
2451 "       return f;\n"
2452 "#  endif\n"
2453 "}\n"
2454 "# endif\n"
2455 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
2456 "#endif // FRAGMENT_SHADER\n"
2457 "\n"
2458 "\n"
2459 "\n"
2460 "\n"
2461 "#ifdef MODE_DEFERREDGEOMETRY\n"
2462 "#ifdef VERTEX_SHADER\n"
2463 "void main\n"
2464 "(\n"
2465 "float4 gl_Vertex : POSITION,\n"
2466 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2467 "#ifdef USEVERTEXTEXTUREBLEND\n"
2468 "float4 gl_Color : COLOR0,\n"
2469 "#endif\n"
2470 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2471 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2472 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2473 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2474 "uniform float4x4 TexMatrix : register(c0),\n"
2475 "#ifdef USEVERTEXTEXTUREBLEND\n"
2476 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2477 "#endif\n"
2478 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2479 "#ifdef USEOFFSETMAPPING\n"
2480 "uniform float3 EyePosition : register(c24),\n"
2481 "#endif\n"
2482 "out float4 gl_Position : POSITION,\n"
2483 "#ifdef USEVERTEXTEXTUREBLEND\n"
2484 "out float4 gl_FrontColor : COLOR,\n"
2485 "#endif\n"
2486 "out float4 TexCoordBoth : TEXCOORD0,\n"
2487 "#ifdef USEOFFSETMAPPING\n"
2488 "out float3 EyeVector : TEXCOORD2,\n"
2489 "#endif\n"
2490 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2491 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2492 "out float4 VectorR : TEXCOORD7 // direction of R texcoord (surface normal), Depth value\n"
2493 ")\n"
2494 "{\n"
2495 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2496 "#ifdef USEVERTEXTEXTUREBLEND\n"
2497 "#ifdef HLSL\n"
2498 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2499 "#else\n"
2500 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2501 "#endif\n"
2502 "       TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2503 "#endif\n"
2504 "\n"
2505 "       // transform unnormalized eye direction into tangent space\n"
2506 "#ifdef USEOFFSETMAPPING\n"
2507 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2508 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2509 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2510 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2511 "#endif\n"
2512 "\n"
2513 "       VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2514 "       VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2515 "       VectorR.xyz = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2516 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2517 "       VectorR.w = gl_Position.z;\n"
2518 "}\n"
2519 "#endif // VERTEX_SHADER\n"
2520 "\n"
2521 "#ifdef FRAGMENT_SHADER\n"
2522 "void main\n"
2523 "(\n"
2524 "float4 TexCoordBoth : TEXCOORD0,\n"
2525 "float3 EyeVector : TEXCOORD2,\n"
2526 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2527 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2528 "float4 VectorR : TEXCOORD7, // direction of R texcoord (surface normal), Depth value\n"
2529 "uniform sampler Texture_Normal : register(s0),\n"
2530 "#ifdef USEALPHAKILL\n"
2531 "uniform sampler Texture_Color : register(s1),\n"
2532 "#endif\n"
2533 "uniform sampler Texture_Gloss : register(s2),\n"
2534 "#ifdef USEVERTEXTEXTUREBLEND\n"
2535 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
2536 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
2537 "#endif\n"
2538 "#ifdef USEOFFSETMAPPING\n"
2539 "uniform float OffsetMapping_Scale : register(c24),\n"
2540 "#endif\n"
2541 "uniform half SpecularPower : register(c36),\n"
2542 "#ifdef HLSL\n"
2543 "out float4 gl_FragData0 : COLOR0,\n"
2544 "out float4 gl_FragData1 : COLOR1\n"
2545 "#else\n"
2546 "out float4 gl_FragColor : COLOR\n"
2547 "#endif\n"
2548 ")\n"
2549 "{\n"
2550 "       float2 TexCoord = TexCoordBoth.xy;\n"
2551 "#ifdef USEOFFSETMAPPING\n"
2552 "       // apply offsetmapping\n"
2553 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2554 "#define TexCoord TexCoordOffset\n"
2555 "#endif\n"
2556 "\n"
2557 "#ifdef USEALPHAKILL\n"
2558 "       if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2559 "               discard;\n"
2560 "#endif\n"
2561 "\n"
2562 "#ifdef USEVERTEXTEXTUREBLEND\n"
2563 "       float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2564 "       float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2565 "       //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2566 "       //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2567 "#endif\n"
2568 "\n"
2569 "#ifdef USEVERTEXTEXTUREBLEND\n"
2570 "       float3 surfacenormal = lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend) - float3(0.5, 0.5, 0.5);\n"
2571 "       float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2).a, tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2572 "#else\n"
2573 "       float3 surfacenormal = tex2D(Texture_Normal, TexCoord).rgb - float3(0.5, 0.5, 0.5);\n"
2574 "       float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2575 "#endif\n"
2576 "\n"
2577 "#ifdef HLSL\n"
2578 "       gl_FragData0 = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR.xyz) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2579 "       float Depth = VectorR.w / 256.0;\n"
2580 "       float4 depthcolor = float4(Depth,Depth*65536.0/255.0,Depth*16777216.0/255.0,0.0);\n"
2581 "//     float4 depthcolor = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
2582 "       depthcolor.yz -= floor(depthcolor.yz);\n"
2583 "       gl_FragData1 = depthcolor;\n"
2584 "#else\n"
2585 "       gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2586 "#endif\n"
2587 "}\n"
2588 "#endif // FRAGMENT_SHADER\n"
2589 "#else // !MODE_DEFERREDGEOMETRY\n"
2590 "\n"
2591 "\n"
2592 "\n"
2593 "\n"
2594 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2595 "#ifdef VERTEX_SHADER\n"
2596 "void main\n"
2597 "(\n"
2598 "float4 gl_Vertex : POSITION,\n"
2599 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2600 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2601 "out float4 gl_Position : POSITION,\n"
2602 "out float4 ModelViewPosition : TEXCOORD0\n"
2603 ")\n"
2604 "{\n"
2605 "       ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2606 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2607 "}\n"
2608 "#endif // VERTEX_SHADER\n"
2609 "\n"
2610 "#ifdef FRAGMENT_SHADER\n"
2611 "void main\n"
2612 "(\n"
2613 "#ifdef HLSL\n"
2614 "float2 Pixel : VPOS,\n"
2615 "#else\n"
2616 "float2 Pixel : WPOS,\n"
2617 "#endif\n"
2618 "float4 ModelViewPosition : TEXCOORD0,\n"
2619 "uniform float4x4 ViewToLight : register(c44),\n"
2620 "uniform float2 ScreenToDepth : register(c33), // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2621 "uniform float3 LightPosition : register(c23),\n"
2622 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
2623 "uniform half3 DeferredColor_Ambient : register(c9),\n"
2624 "uniform half3 DeferredColor_Diffuse : register(c10),\n"
2625 "#ifdef USESPECULAR\n"
2626 "uniform half3 DeferredColor_Specular : register(c11),\n"
2627 "uniform half SpecularPower : register(c36),\n"
2628 "#endif\n"
2629 "uniform sampler Texture_Attenuation : register(s9),\n"
2630 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2631 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2632 "\n"
2633 "#ifdef USECUBEFILTER\n"
2634 "uniform samplerCUBE Texture_Cube : register(s10),\n"
2635 "#endif\n"
2636 "\n"
2637 "#ifdef USESHADOWMAP2D\n"
2638 "# ifdef USESHADOWSAMPLER\n"
2639 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2640 "# else\n"
2641 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2642 "# endif\n"
2643 "#endif\n"
2644 "\n"
2645 "#ifdef USESHADOWMAPVSDCT\n"
2646 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
2647 "#endif\n"
2648 "\n"
2649 "#if defined(USESHADOWMAP2D)\n"
2650 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
2651 "uniform float4 ShadowMap_Parameters : register(c34),\n"
2652 "#endif\n"
2653 "\n"
2654 "out float4 gl_FragData0 : COLOR0,\n"
2655 "out float4 gl_FragData1 : COLOR1\n"
2656 ")\n"
2657 "{\n"
2658 "       // calculate viewspace pixel position\n"
2659 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2660 "       //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2661 "       float3 position;\n"
2662 "#ifdef HLSL\n"
2663 "       position.z = texDepth2D(Texture_ScreenDepth, ScreenTexCoord) * 256.0;\n"
2664 "#else\n"
2665 "       position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2666 "#endif\n"
2667 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2668 "       // decode viewspace pixel normal\n"
2669 "       half4 normalmap = half4(tex2D(Texture_ScreenNormalMap, ScreenTexCoord));\n"
2670 "       half3 surfacenormal = half3(normalize(normalmap.rgb - half3(0.5,0.5,0.5)));\n"
2671 "       // surfacenormal = pixel normal in viewspace\n"
2672 "       // LightVector = pixel to light in viewspace\n"
2673 "       // CubeVector = position in lightspace\n"
2674 "       // eyevector = pixel to view in viewspace\n"
2675 "       float3 CubeVector = mul(ViewToLight, float4(position,1)).xyz;\n"
2676 "       half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
2677 "#ifdef USEDIFFUSE\n"
2678 "       // calculate diffuse shading\n"
2679 "       half3 lightnormal = half3(normalize(LightPosition - position));\n"
2680 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2681 "#endif\n"
2682 "#ifdef USESPECULAR\n"
2683 "       // calculate directional shading\n"
2684 "       float3 eyevector = position * -1.0;\n"
2685 "#  ifdef USEEXACTSPECULARMATH\n"
2686 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a));\n"
2687 "#  else\n"
2688 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(eyevector))));\n"
2689 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a));\n"
2690 "#  endif\n"
2691 "#endif\n"
2692 "\n"
2693 "#if defined(USESHADOWMAP2D)\n"
2694 "       fade *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2695 "#ifdef USESHADOWMAPVSDCT\n"
2696 ", Texture_CubeProjection\n"
2697 "#endif\n"
2698 "       ));\n"
2699 "#endif\n"
2700 "\n"
2701 "#ifdef USEDIFFUSE\n"
2702 "       gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2703 "#else\n"
2704 "       gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2705 "#endif\n"
2706 "#ifdef USESPECULAR\n"
2707 "       gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2708 "#else\n"
2709 "       gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2710 "#endif\n"
2711 "\n"
2712 "# ifdef USECUBEFILTER\n"
2713 "       float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2714 "       gl_FragData0.rgb *= cubecolor;\n"
2715 "       gl_FragData1.rgb *= cubecolor;\n"
2716 "# endif\n"
2717 "}\n"
2718 "#endif // FRAGMENT_SHADER\n"
2719 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2720 "\n"
2721 "\n"
2722 "\n"
2723 "\n"
2724 "#ifdef VERTEX_SHADER\n"
2725 "void main\n"
2726 "(\n"
2727 "float4 gl_Vertex : POSITION,\n"
2728 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2729 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2730 "float4 gl_Color : COLOR0,\n"
2731 "#endif\n"
2732 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2733 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2734 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2735 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2736 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2737 "\n"
2738 "uniform float3 EyePosition : register(c24),\n"
2739 "uniform float4x4 TexMatrix : register(c0),\n"
2740 "#ifdef USEVERTEXTEXTUREBLEND\n"
2741 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2742 "#endif\n"
2743 "#ifdef MODE_LIGHTSOURCE\n"
2744 "uniform float4x4 ModelToLight : register(c20),\n"
2745 "#endif\n"
2746 "#ifdef MODE_LIGHTSOURCE\n"
2747 "uniform float3 LightPosition : register(c27),\n"
2748 "#endif\n"
2749 "#ifdef MODE_LIGHTDIRECTION\n"
2750 "uniform float3 LightDir : register(c26),\n"
2751 "#endif\n"
2752 "uniform float4 FogPlane : register(c25),\n"
2753 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2754 "uniform float3 LightPosition : register(c27),\n"
2755 "#endif\n"
2756 "#ifdef USESHADOWMAPORTHO\n"
2757 "uniform float4x4 ShadowMapMatrix : register(c16),\n"
2758 "#endif\n"
2759 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2760 "out float4 gl_FrontColor : COLOR,\n"
2761 "#endif\n"
2762 "out float4 TexCoordBoth : TEXCOORD0,\n"
2763 "#ifdef USELIGHTMAP\n"
2764 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2765 "#endif\n"
2766 "#ifdef USEEYEVECTOR\n"
2767 "out float3 EyeVector : TEXCOORD2,\n"
2768 "#endif\n"
2769 "#ifdef USEREFLECTION\n"
2770 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2771 "#endif\n"
2772 "#ifdef USEFOG\n"
2773 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2774 "#endif\n"
2775 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE) || defined(USEDIFFUSE)\n"
2776 "out float3 LightVector : TEXCOORD1,\n"
2777 "#endif\n"
2778 "#ifdef MODE_LIGHTSOURCE\n"
2779 "out float3 CubeVector : TEXCOORD3,\n"
2780 "#endif\n"
2781 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2782 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2783 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2784 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2785 "#endif\n"
2786 "#ifdef USESHADOWMAPORTHO\n"
2787 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2788 "#endif\n"
2789 "out float4 gl_Position : POSITION\n"
2790 ")\n"
2791 "{\n"
2792 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2793 "#ifdef HLSL\n"
2794 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2795 "#else\n"
2796 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2797 "#endif\n"
2798 "#endif\n"
2799 "       // copy the surface texcoord\n"
2800 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2801 "#ifdef USEVERTEXTEXTUREBLEND\n"
2802 "       TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2803 "#endif\n"
2804 "#ifdef USELIGHTMAP\n"
2805 "       TexCoordLightmap = gl_MultiTexCoord4.xy;\n"
2806 "#endif\n"
2807 "\n"
2808 "#ifdef MODE_LIGHTSOURCE\n"
2809 "       // transform vertex position into light attenuation/cubemap space\n"
2810 "       // (-1 to +1 across the light box)\n"
2811 "       CubeVector = mul(ModelToLight, gl_Vertex).xyz;\n"
2812 "\n"
2813 "# ifdef USEDIFFUSE\n"
2814 "       // transform unnormalized light direction into tangent space\n"
2815 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
2816 "       //  normalize it per pixel)\n"
2817 "       float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2818 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2819 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2820 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2821 "# endif\n"
2822 "#endif\n"
2823 "\n"
2824 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2825 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2826 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2827 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2828 "#endif\n"
2829 "\n"
2830 "       // transform unnormalized eye direction into tangent space\n"
2831 "#ifdef USEEYEVECTOR\n"
2832 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2833 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2834 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2835 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2836 "#endif\n"
2837 "\n"
2838 "#ifdef USEFOG\n"
2839 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2840 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2841 "#endif\n"
2842 "\n"
2843 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2844 "       VectorS = gl_MultiTexCoord1.xyz;\n"
2845 "       VectorT = gl_MultiTexCoord2.xyz;\n"
2846 "       VectorR = gl_MultiTexCoord3.xyz;\n"
2847 "#endif\n"
2848 "\n"
2849 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2850 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2851 "\n"
2852 "#ifdef USESHADOWMAPORTHO\n"
2853 "       ShadowMapTC = mul(ShadowMapMatrix, gl_Position).xyz;\n"
2854 "#endif\n"
2855 "\n"
2856 "#ifdef USEREFLECTION\n"
2857 "       ModelViewProjectionPosition = gl_Position;\n"
2858 "#endif\n"
2859 "}\n"
2860 "#endif // VERTEX_SHADER\n"
2861 "\n"
2862 "\n"
2863 "\n"
2864 "\n"
2865 "#ifdef FRAGMENT_SHADER\n"
2866 "void main\n"
2867 "(\n"
2868 "#ifdef USEDEFERREDLIGHTMAP\n"
2869 "#ifdef HLSL\n"
2870 "float2 Pixel : VPOS,\n"
2871 "#else\n"
2872 "float2 Pixel : WPOS,\n"
2873 "#endif\n"
2874 "#endif\n"
2875 "float4 gl_FrontColor : COLOR,\n"
2876 "float4 TexCoordBoth : TEXCOORD0,\n"
2877 "#ifdef USELIGHTMAP\n"
2878 "float2 TexCoordLightmap : TEXCOORD1,\n"
2879 "#endif\n"
2880 "#ifdef USEEYEVECTOR\n"
2881 "float3 EyeVector : TEXCOORD2,\n"
2882 "#endif\n"
2883 "#ifdef USEREFLECTION\n"
2884 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2885 "#endif\n"
2886 "#ifdef USEFOG\n"
2887 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2888 "#endif\n"
2889 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2890 "float3 LightVector : TEXCOORD1,\n"
2891 "#endif\n"
2892 "#ifdef MODE_LIGHTSOURCE\n"
2893 "float3 CubeVector : TEXCOORD3,\n"
2894 "#endif\n"
2895 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2896 "float4 ModelViewPosition : TEXCOORD0,\n"
2897 "#endif\n"
2898 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2899 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2900 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2901 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2902 "#endif\n"
2903 "#ifdef USESHADOWMAPORTHO\n"
2904 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2905 "#endif\n"
2906 "\n"
2907 "uniform sampler Texture_Normal : register(s0),\n"
2908 "uniform sampler Texture_Color : register(s1),\n"
2909 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2910 "uniform sampler Texture_Gloss : register(s2),\n"
2911 "#endif\n"
2912 "#ifdef USEGLOW\n"
2913 "uniform sampler Texture_Glow : register(s3),\n"
2914 "#endif\n"
2915 "#ifdef USEVERTEXTEXTUREBLEND\n"
2916 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
2917 "uniform sampler Texture_SecondaryColor : register(s5),\n"
2918 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2919 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
2920 "#endif\n"
2921 "#ifdef USEGLOW\n"
2922 "uniform sampler Texture_SecondaryGlow : register(s7),\n"
2923 "#endif\n"
2924 "#endif\n"
2925 "#ifdef USECOLORMAPPING\n"
2926 "uniform sampler Texture_Pants : register(s4),\n"
2927 "uniform sampler Texture_Shirt : register(s7),\n"
2928 "#endif\n"
2929 "#ifdef USEFOG\n"
2930 "uniform sampler Texture_FogHeightTexture : register(s14),\n"
2931 "uniform sampler Texture_FogMask : register(s8),\n"
2932 "#endif\n"
2933 "#ifdef USELIGHTMAP\n"
2934 "uniform sampler Texture_Lightmap : register(s9),\n"
2935 "#endif\n"
2936 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2937 "uniform sampler Texture_Deluxemap : register(s10),\n"
2938 "#endif\n"
2939 "#ifdef USEREFLECTION\n"
2940 "uniform sampler Texture_Reflection : register(s7),\n"
2941 "#endif\n"
2942 "\n"
2943 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2944 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2945 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2946 "#endif\n"
2947 "#ifdef USEDEFERREDLIGHTMAP\n"
2948 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2949 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2950 "uniform sampler Texture_ScreenDiffuse : register(s11),\n"
2951 "uniform sampler Texture_ScreenSpecular : register(s12),\n"
2952 "#endif\n"
2953 "\n"
2954 "#ifdef USECOLORMAPPING\n"
2955 "uniform half3 Color_Pants : register(c7),\n"
2956 "uniform half3 Color_Shirt : register(c8),\n"
2957 "#endif\n"
2958 "#ifdef USEFOG\n"
2959 "uniform float3 FogColor : register(c16),\n"
2960 "uniform float FogRangeRecip : register(c20),\n"
2961 "uniform float FogPlaneViewDist : register(c19),\n"
2962 "uniform float FogHeightFade : register(c17),\n"
2963 "#endif\n"
2964 "\n"
2965 "#ifdef USEOFFSETMAPPING\n"
2966 "uniform float OffsetMapping_Scale : register(c24),\n"
2967 "#endif\n"
2968 "\n"
2969 "#ifdef USEDEFERREDLIGHTMAP\n"
2970 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
2971 "uniform half3 DeferredMod_Diffuse : register(c12),\n"
2972 "uniform half3 DeferredMod_Specular : register(c13),\n"
2973 "#endif\n"
2974 "uniform half3 Color_Ambient : register(c3),\n"
2975 "uniform half3 Color_Diffuse : register(c4),\n"
2976 "uniform half3 Color_Specular : register(c5),\n"
2977 "uniform half SpecularPower : register(c36),\n"
2978 "#ifdef USEGLOW\n"
2979 "uniform half3 Color_Glow : register(c6),\n"
2980 "#endif\n"
2981 "uniform half Alpha : register(c0),\n"
2982 "#ifdef USEREFLECTION\n"
2983 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2984 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2985 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2986 "uniform half4 ReflectColor : register(c26),\n"
2987 "#endif\n"
2988 "#ifdef USEREFLECTCUBE\n"
2989 "uniform float4x4 ModelToReflectCube : register(c48),\n"
2990 "uniform sampler Texture_ReflectMask : register(s5),\n"
2991 "uniform samplerCUBE Texture_ReflectCube : register(s6),\n"
2992 "#endif\n"
2993 "#ifdef MODE_LIGHTDIRECTION\n"
2994 "uniform half3 LightColor : register(c21),\n"
2995 "#endif\n"
2996 "#ifdef MODE_LIGHTSOURCE\n"
2997 "uniform half3 LightColor : register(c21),\n"
2998 "#endif\n"
2999 "\n"
3000 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3001 "uniform sampler Texture_Attenuation : register(s9),\n"
3002 "uniform samplerCUBE Texture_Cube : register(s10),\n"
3003 "#endif\n"
3004 "\n"
3005 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3006 "\n"
3007 "#ifdef USESHADOWMAP2D\n"
3008 "# ifdef USESHADOWSAMPLER\n"
3009 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3010 "# else\n"
3011 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3012 "# endif\n"
3013 "#endif\n"
3014 "\n"
3015 "#ifdef USESHADOWMAPVSDCT\n"
3016 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
3017 "#endif\n"
3018 "\n"
3019 "#if defined(USESHADOWMAP2D)\n"
3020 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
3021 "uniform float4 ShadowMap_Parameters : register(c34),\n"
3022 "#endif\n"
3023 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3024 "\n"
3025 "out float4 gl_FragColor : COLOR\n"
3026 ")\n"
3027 "{\n"
3028 "       float2 TexCoord = TexCoordBoth.xy;\n"
3029 "#ifdef USEVERTEXTEXTUREBLEND\n"
3030 "       float2 TexCoord2 = TexCoordBoth.zw;\n"
3031 "#endif\n"
3032 "#ifdef USEOFFSETMAPPING\n"
3033 "       // apply offsetmapping\n"
3034 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3035 "#define TexCoord TexCoordOffset\n"
3036 "#endif\n"
3037 "\n"
3038 "       // combine the diffuse textures (base, pants, shirt)\n"
3039 "       half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3040 "#ifdef USEALPHAKILL\n"
3041 "       if (color.a < 0.5)\n"
3042 "               discard;\n"
3043 "#endif\n"
3044 "       color.a *= Alpha;\n"
3045 "#ifdef USECOLORMAPPING\n"
3046 "       color.rgb += half3(tex2D(Texture_Pants, TexCoord).rgb) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord).rgb) * Color_Shirt;\n"
3047 "#endif\n"
3048 "#ifdef USEVERTEXTEXTUREBLEND\n"
3049 "       half terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3050 "       //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3051 "       //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3052 "       color.rgb = half3(lerp(tex2D(Texture_SecondaryColor, TexCoord2).rgb, float3(color.rgb), terrainblend));\n"
3053 "       color.a = 1.0;\n"
3054 "       //color = half4(lerp(float4(1, 0, 0, 1), color, terrainblend));\n"
3055 "#endif\n"
3056 "\n"
3057 "       // get the surface normal\n"
3058 "#ifdef USEVERTEXTEXTUREBLEND\n"
3059 "       half3 surfacenormal = normalize(half3(lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3060 "#else\n"
3061 "       half3 surfacenormal = half3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5, 0.5, 0.5)));\n"
3062 "#endif\n"
3063 "\n"
3064 "       // get the material colors\n"
3065 "       half3 diffusetex = color.rgb;\n"
3066 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3067 "# ifdef USEVERTEXTEXTUREBLEND\n"
3068 "       half4 glosstex = half4(lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord), terrainblend));\n"
3069 "# else\n"
3070 "       half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3071 "# endif\n"
3072 "#endif\n"
3073 "\n"
3074 "#ifdef USEREFLECTCUBE\n"
3075 "       float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3076 "       float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3077 "       float3 ReflectCubeTexCoord = mul(ModelToReflectCube, float4(ModelReflectVector, 0)).xyz;\n"
3078 "       diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord).rgb) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord).rgb);\n"
3079 "#endif\n"
3080 "\n"
3081 "\n"
3082 "\n"
3083 "\n"
3084 "#ifdef MODE_LIGHTSOURCE\n"
3085 "       // light source\n"
3086 "#ifdef USEDIFFUSE\n"
3087 "       half3 lightnormal = half3(normalize(LightVector));\n"
3088 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3089 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3090 "#ifdef USESPECULAR\n"
3091 "#ifdef USEEXACTSPECULARMATH\n"
3092 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3093 "#else\n"
3094 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3095 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3096 "#endif\n"
3097 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3098 "#endif\n"
3099 "#else\n"
3100 "       color.rgb = diffusetex * Color_Ambient;\n"
3101 "#endif\n"
3102 "       color.rgb *= LightColor;\n"
3103 "       color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
3104 "#if defined(USESHADOWMAP2D)\n"
3105 "       color.rgb *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3106 "#ifdef USESHADOWMAPVSDCT\n"
3107 ", Texture_CubeProjection\n"
3108 "#endif\n"
3109 "       ));\n"
3110 "\n"
3111 "#endif\n"
3112 "# ifdef USECUBEFILTER\n"
3113 "       color.rgb *= half3(texCUBE(Texture_Cube, CubeVector).rgb);\n"
3114 "# endif\n"
3115 "\n"
3116 "#ifdef USESHADOWMAP2D\n"
3117 "#ifdef USESHADOWMAPVSDCT\n"
3118 "//     float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection);\n"
3119 "#else\n"
3120 "//     float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters);\n"
3121 "#endif\n"
3122 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3123 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3124 "//     color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3125 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3126 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3127 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3128 "//     color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3129 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3130 "//     color.r = half(shadowmaptc.z - texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3131 "//     color.r = half(shadowmaptc.z);\n"
3132 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3133 "//     color.r = half(shadowmaptc.z);\n"
3134 "//     color.r = 1;\n"
3135 "//     color.rgb = abs(CubeVector);\n"
3136 "#endif\n"
3137 "//     color.rgb = half3(1,1,1);\n"
3138 "#endif // MODE_LIGHTSOURCE\n"
3139 "\n"
3140 "\n"
3141 "\n"
3142 "\n"
3143 "#ifdef MODE_LIGHTDIRECTION\n"
3144 "#define SHADING\n"
3145 "#ifdef USEDIFFUSE\n"
3146 "       half3 lightnormal = half3(normalize(LightVector));\n"
3147 "#endif\n"
3148 "#define lightcolor LightColor\n"
3149 "#endif // MODE_LIGHTDIRECTION\n"
3150 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3151 "#define SHADING\n"
3152 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3153 "       half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3154 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3155 "       // convert modelspace light vector to tangentspace\n"
3156 "       half3 lightnormal;\n"
3157 "       lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3158 "       lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3159 "       lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3160 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3161 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3162 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3163 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3164 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3165 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3166 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3167 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3168 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3169 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3170 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3171 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3172 "#define SHADING\n"
3173 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3174 "       half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3175 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3176 "#endif\n"
3177 "\n"
3178 "\n"
3179 "\n"
3180 "\n"
3181 "#ifdef MODE_FAKELIGHT\n"
3182 "#define SHADING\n"
3183 "half3 lightnormal = half3(normalize(EyeVector));\n"
3184 "half3 lightcolor = half3(1.0);\n"
3185 "#endif // MODE_FAKELIGHT\n"
3186 "\n"
3187 "\n"
3188 "\n"
3189 "\n"
3190 "#ifdef MODE_LIGHTMAP\n"
3191 "       color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb) * Color_Diffuse);\n"
3192 "#endif // MODE_LIGHTMAP\n"
3193 "#ifdef MODE_VERTEXCOLOR\n"
3194 "       color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3195 "#endif // MODE_VERTEXCOLOR\n"
3196 "#ifdef MODE_FLATCOLOR\n"
3197 "       color.rgb = diffusetex * Color_Ambient;\n"
3198 "#endif // MODE_FLATCOLOR\n"
3199 "\n"
3200 "\n"
3201 "\n"
3202 "\n"
3203 "#ifdef SHADING\n"
3204 "# ifdef USEDIFFUSE\n"
3205 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3206 "#  ifdef USESPECULAR\n"
3207 "#   ifdef USEEXACTSPECULARMATH\n"
3208 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3209 "#   else\n"
3210 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3211 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3212 "#   endif\n"
3213 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3214 "#  else\n"
3215 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3216 "#  endif\n"
3217 "# else\n"
3218 "       color.rgb = diffusetex * Color_Ambient;\n"
3219 "# endif\n"
3220 "#endif\n"
3221 "\n"
3222 "#ifdef USESHADOWMAPORTHO\n"
3223 "       color.rgb *= half(ShadowMapCompare(ShadowMapTC, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale));\n"
3224 "#endif\n"
3225 "\n"
3226 "#ifdef USEDEFERREDLIGHTMAP\n"
3227 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3228 "       color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord).rgb) * DeferredMod_Diffuse;\n"
3229 "       color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord).rgb) * DeferredMod_Specular;\n"
3230 "//     color.rgb = half3(tex2D(Texture_ScreenDepth, ScreenTexCoord).rgb);\n"
3231 "//     color.r = half(texDepth2D(Texture_ScreenDepth, ScreenTexCoord)) * 1.0;\n"
3232 "#endif\n"
3233 "\n"
3234 "#ifdef USEGLOW\n"
3235 "#ifdef USEVERTEXTEXTUREBLEND\n"
3236 "       color.rgb += half3(lerp(tex2D(Texture_SecondaryGlow, TexCoord2).rgb, tex2D(Texture_Glow, TexCoord).rgb, terrainblend)) * Color_Glow;\n"
3237 "#else\n"
3238 "       color.rgb += half3(tex2D(Texture_Glow, TexCoord).rgb) * Color_Glow;\n"
3239 "#endif\n"
3240 "#endif\n"
3241 "\n"
3242 "#ifdef USEFOG\n"
3243 "       color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3244 "#endif\n"
3245 "\n"
3246 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
3247 "#ifdef USEREFLECTION\n"
3248 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3249 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3250 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3251 "       float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.zw;\n"
3252 "       // FIXME temporary hack to detect the case that the reflection\n"
3253 "       // gets blackened at edges due to leaving the area that contains actual\n"
3254 "       // content.\n"
3255 "       // Remove this 'ack once we have a better way to stop this thing from\n"
3256 "       // 'appening.\n"
3257 "       float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3258 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3259 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3260 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3261 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3262 "       color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord).rgb) * ReflectColor.rgb, ReflectColor.a);\n"
3263 "#endif\n"
3264 "\n"
3265 "       gl_FragColor = float4(color);\n"
3266 "}\n"
3267 "#endif // FRAGMENT_SHADER\n"
3268 "\n"
3269 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3270 "#endif // !MODE_DEFERREDGEOMETRY\n"
3271 "#endif // !MODE_WATER\n"
3272 "#endif // !MODE_REFRACTION\n"
3273 "#endif // !MODE_BLOOMBLUR\n"
3274 "#endif // !MODE_GENERIC\n"
3275 "#endif // !MODE_POSTPROCESS\n"
3276 "#endif // !MODE_SHOWDEPTH\n"
3277 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3278 ;
3279
3280 char *glslshaderstring = NULL;
3281 char *cgshaderstring = NULL;
3282 char *hlslshaderstring = NULL;
3283
3284 //=======================================================================================================================================================
3285
3286 typedef struct shaderpermutationinfo_s
3287 {
3288         const char *pretext;
3289         const char *name;
3290 }
3291 shaderpermutationinfo_t;
3292
3293 typedef struct shadermodeinfo_s
3294 {
3295         const char *vertexfilename;
3296         const char *geometryfilename;
3297         const char *fragmentfilename;
3298         const char *pretext;
3299         const char *name;
3300 }
3301 shadermodeinfo_t;
3302
3303 typedef enum shaderpermutation_e
3304 {
3305         SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3306         SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3307         SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3308         SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3309         SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3310         SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3311         SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3312         SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3313         SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3314         SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3315         SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3316         SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3317         SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3318         SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3319         SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3320         SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3321         SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3322         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3323         SHADERPERMUTATION_SHADOWMAP2D = 1<<18, ///< (lightsource) use shadowmap texture as light filter
3324         SHADERPERMUTATION_SHADOWMAPPCF = 1<<19, ///< (lightsource) use percentage closer filtering on shadowmap test results
3325         SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<20, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3326         SHADERPERMUTATION_SHADOWSAMPLER = 1<<21, ///< (lightsource) use hardware shadowmap test
3327         SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<22, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3328         SHADERPERMUTATION_SHADOWMAPORTHO = 1<<23, //< (lightsource) use orthographic shadowmap projection
3329         SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<24, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3330         SHADERPERMUTATION_ALPHAKILL = 1<<25, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3331         SHADERPERMUTATION_REFLECTCUBE = 1<<26, ///< fake reflections using global cubemap (not HDRI light probe)
3332         SHADERPERMUTATION_LIMIT = 1<<27, ///< size of permutations array
3333         SHADERPERMUTATION_COUNT = 27 ///< size of shaderpermutationinfo array
3334 }
3335 shaderpermutation_t;
3336
3337 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3338 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3339 {
3340         {"#define USEDIFFUSE\n", " diffuse"},
3341         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3342         {"#define USEVIEWTINT\n", " viewtint"},
3343         {"#define USECOLORMAPPING\n", " colormapping"},
3344         {"#define USESATURATION\n", " saturation"},
3345         {"#define USEFOGINSIDE\n", " foginside"},
3346         {"#define USEFOGOUTSIDE\n", " fogoutside"},
3347         {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3348         {"#define USEGAMMARAMPS\n", " gammaramps"},
3349         {"#define USECUBEFILTER\n", " cubefilter"},
3350         {"#define USEGLOW\n", " glow"},
3351         {"#define USEBLOOM\n", " bloom"},
3352         {"#define USESPECULAR\n", " specular"},
3353         {"#define USEPOSTPROCESSING\n", " postprocessing"},
3354         {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3355         {"#define USEREFLECTION\n", " reflection"},
3356         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3357         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3358         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3359         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3360         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3361         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3362         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3363         {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3364         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3365         {"#define USEALPHAKILL\n", " alphakill"},
3366         {"#define USEREFLECTCUBE\n", " reflectcube"},
3367 };
3368
3369 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3370 typedef enum shadermode_e
3371 {
3372         SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3373         SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3374         SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3375         SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3376         SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3377         SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3378         SHADERMODE_FAKELIGHT, ///< (fakelight) modulate texture by "fake" lighting (no lightmaps, no nothing)
3379         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3380         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3381         SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3382         SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3383         SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3384         SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3385         SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3386         SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3387         SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3388         SHADERMODE_COUNT
3389 }
3390 shadermode_t;
3391
3392 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3393 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3394 {
3395         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3396         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3397         {"glsl/default.glsl", NULL, NULL               , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3398         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3399         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3400         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3401         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3402         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3403         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3404         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3405         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3406         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3407         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3408         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3409         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3410         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3411 };
3412
3413 #ifdef SUPPORTCG
3414 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3415 {
3416         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3417         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3418         {"cg/default.cg", NULL, NULL           , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3419         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3420         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3421         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3422         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FAKELIGHT\n", " fakelight"},
3423         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3424         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3425         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3426         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3427         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3428         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3429         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3430         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3431         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3432 };
3433 #endif
3434
3435 #ifdef SUPPORTD3D
3436 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
3437 {
3438         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
3439         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3440         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3441         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3442         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3443         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3444         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3445         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3446         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3447         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3448         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
3449         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
3450         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3451         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3452         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3453 };
3454 #endif
3455
3456 struct r_glsl_permutation_s;
3457 typedef struct r_glsl_permutation_s
3458 {
3459         /// hash lookup data
3460         struct r_glsl_permutation_s *hashnext;
3461         unsigned int mode;
3462         unsigned int permutation;
3463
3464         /// indicates if we have tried compiling this permutation already
3465         qboolean compiled;
3466         /// 0 if compilation failed
3467         int program;
3468         /// locations of detected uniforms in program object, or -1 if not found
3469         int loc_Texture_First;
3470         int loc_Texture_Second;
3471         int loc_Texture_GammaRamps;
3472         int loc_Texture_Normal;
3473         int loc_Texture_Color;
3474         int loc_Texture_Gloss;
3475         int loc_Texture_Glow;
3476         int loc_Texture_SecondaryNormal;
3477         int loc_Texture_SecondaryColor;
3478         int loc_Texture_SecondaryGloss;
3479         int loc_Texture_SecondaryGlow;
3480         int loc_Texture_Pants;
3481         int loc_Texture_Shirt;
3482         int loc_Texture_FogHeightTexture;
3483         int loc_Texture_FogMask;
3484         int loc_Texture_Lightmap;
3485         int loc_Texture_Deluxemap;
3486         int loc_Texture_Attenuation;
3487         int loc_Texture_Cube;
3488         int loc_Texture_Refraction;
3489         int loc_Texture_Reflection;
3490         int loc_Texture_ShadowMap2D;
3491         int loc_Texture_CubeProjection;
3492         int loc_Texture_ScreenDepth;
3493         int loc_Texture_ScreenNormalMap;
3494         int loc_Texture_ScreenDiffuse;
3495         int loc_Texture_ScreenSpecular;
3496         int loc_Texture_ReflectMask;
3497         int loc_Texture_ReflectCube;
3498         int loc_Alpha;
3499         int loc_BloomBlur_Parameters;
3500         int loc_ClientTime;
3501         int loc_Color_Ambient;
3502         int loc_Color_Diffuse;
3503         int loc_Color_Specular;
3504         int loc_Color_Glow;
3505         int loc_Color_Pants;
3506         int loc_Color_Shirt;
3507         int loc_DeferredColor_Ambient;
3508         int loc_DeferredColor_Diffuse;
3509         int loc_DeferredColor_Specular;
3510         int loc_DeferredMod_Diffuse;
3511         int loc_DeferredMod_Specular;
3512         int loc_DistortScaleRefractReflect;
3513         int loc_EyePosition;
3514         int loc_FogColor;
3515         int loc_FogHeightFade;
3516         int loc_FogPlane;
3517         int loc_FogPlaneViewDist;
3518         int loc_FogRangeRecip;
3519         int loc_LightColor;
3520         int loc_LightDir;
3521         int loc_LightPosition;
3522         int loc_OffsetMapping_Scale;
3523         int loc_PixelSize;
3524         int loc_ReflectColor;
3525         int loc_ReflectFactor;
3526         int loc_ReflectOffset;
3527         int loc_RefractColor;
3528         int loc_Saturation;
3529         int loc_ScreenCenterRefractReflect;
3530         int loc_ScreenScaleRefractReflect;
3531         int loc_ScreenToDepth;
3532         int loc_ShadowMap_Parameters;
3533         int loc_ShadowMap_TextureScale;
3534         int loc_SpecularPower;
3535         int loc_UserVec1;
3536         int loc_UserVec2;
3537         int loc_UserVec3;
3538         int loc_UserVec4;
3539         int loc_ViewTintColor;
3540         int loc_ViewToLight;
3541         int loc_ModelToLight;
3542         int loc_TexMatrix;
3543         int loc_BackgroundTexMatrix;
3544         int loc_ModelViewProjectionMatrix;
3545         int loc_ModelViewMatrix;
3546         int loc_PixelToScreenTexCoord;
3547         int loc_ModelToReflectCube;
3548         int loc_ShadowMapMatrix;
3549         int loc_BloomColorSubtract;
3550 }
3551 r_glsl_permutation_t;
3552
3553 #define SHADERPERMUTATION_HASHSIZE 256
3554
3555 /// information about each possible shader permutation
3556 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3557 /// currently selected permutation
3558 r_glsl_permutation_t *r_glsl_permutation;
3559 /// storage for permutations linked in the hash table
3560 memexpandablearray_t r_glsl_permutationarray;
3561
3562 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3563 {
3564         //unsigned int hashdepth = 0;
3565         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3566         r_glsl_permutation_t *p;
3567         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3568         {
3569                 if (p->mode == mode && p->permutation == permutation)
3570                 {
3571                         //if (hashdepth > 10)
3572                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3573                         return p;
3574                 }
3575                 //hashdepth++;
3576         }
3577         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3578         p->mode = mode;
3579         p->permutation = permutation;
3580         p->hashnext = r_glsl_permutationhash[mode][hashindex];
3581         r_glsl_permutationhash[mode][hashindex] = p;
3582         //if (hashdepth > 10)
3583         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3584         return p;
3585 }
3586
3587 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3588 {
3589         char *shaderstring;
3590         if (!filename || !filename[0])
3591                 return NULL;
3592         if (!strcmp(filename, "glsl/default.glsl"))
3593         {
3594                 if (!glslshaderstring)
3595                 {
3596                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3597                         if (glslshaderstring)
3598                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
3599                         else
3600                                 glslshaderstring = (char *)builtinshaderstring;
3601                 }
3602                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3603                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3604                 return shaderstring;
3605         }
3606         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3607         if (shaderstring)
3608         {
3609                 if (printfromdisknotice)
3610                         Con_DPrintf("from disk %s... ", filename);
3611                 return shaderstring;
3612         }
3613         return shaderstring;
3614 }
3615
3616 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3617 {
3618         int i;
3619         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3620         int vertstrings_count = 0;
3621         int geomstrings_count = 0;
3622         int fragstrings_count = 0;
3623         char *vertexstring, *geometrystring, *fragmentstring;
3624         const char *vertstrings_list[32+3];
3625         const char *geomstrings_list[32+3];
3626         const char *fragstrings_list[32+3];
3627         char permutationname[256];
3628
3629         if (p->compiled)
3630                 return;
3631         p->compiled = true;
3632         p->program = 0;
3633
3634         permutationname[0] = 0;
3635         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
3636         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3637         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3638
3639         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3640
3641         // the first pretext is which type of shader to compile as
3642         // (later these will all be bound together as a program object)
3643         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3644         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3645         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3646
3647         // the second pretext is the mode (for example a light source)
3648         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3649         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3650         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3651         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3652
3653         // now add all the permutation pretexts
3654         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3655         {
3656                 if (permutation & (1<<i))
3657                 {
3658                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3659                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3660                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3661                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3662                 }
3663                 else
3664                 {
3665                         // keep line numbers correct
3666                         vertstrings_list[vertstrings_count++] = "\n";
3667                         geomstrings_list[geomstrings_count++] = "\n";
3668                         fragstrings_list[fragstrings_count++] = "\n";
3669                 }
3670         }
3671
3672         // now append the shader text itself
3673         vertstrings_list[vertstrings_count++] = vertexstring;
3674         geomstrings_list[geomstrings_count++] = geometrystring;
3675         fragstrings_list[fragstrings_count++] = fragmentstring;
3676
3677         // if any sources were NULL, clear the respective list
3678         if (!vertexstring)
3679                 vertstrings_count = 0;
3680         if (!geometrystring)
3681                 geomstrings_count = 0;
3682         if (!fragmentstring)
3683                 fragstrings_count = 0;
3684
3685         // compile the shader program
3686         if (vertstrings_count + geomstrings_count + fragstrings_count)
3687                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3688         if (p->program)
3689         {
3690                 CHECKGLERROR
3691                 qglUseProgramObjectARB(p->program);CHECKGLERROR
3692                 // look up all the uniform variable names we care about, so we don't
3693                 // have to look them up every time we set them
3694
3695                 p->loc_Texture_First              = qglGetUniformLocationARB(p->program, "Texture_First");
3696                 p->loc_Texture_Second             = qglGetUniformLocationARB(p->program, "Texture_Second");
3697                 p->loc_Texture_GammaRamps         = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3698                 p->loc_Texture_Normal             = qglGetUniformLocationARB(p->program, "Texture_Normal");
3699                 p->loc_Texture_Color              = qglGetUniformLocationARB(p->program, "Texture_Color");
3700                 p->loc_Texture_Gloss              = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3701                 p->loc_Texture_Glow               = qglGetUniformLocationARB(p->program, "Texture_Glow");
3702                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3703                 p->loc_Texture_SecondaryColor     = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3704                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3705                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3706                 p->loc_Texture_Pants              = qglGetUniformLocationARB(p->program, "Texture_Pants");
3707                 p->loc_Texture_Shirt              = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3708                 p->loc_Texture_FogHeightTexture   = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3709                 p->loc_Texture_FogMask            = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3710                 p->loc_Texture_Lightmap           = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3711                 p->loc_Texture_Deluxemap          = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3712                 p->loc_Texture_Attenuation        = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3713                 p->loc_Texture_Cube               = qglGetUniformLocationARB(p->program, "Texture_Cube");
3714                 p->loc_Texture_Refraction         = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3715                 p->loc_Texture_Reflection         = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3716                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3717                 p->loc_Texture_CubeProjection     = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3718                 p->loc_Texture_ScreenDepth        = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3719                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3720                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3721                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3722                 p->loc_Texture_ReflectMask        = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3723                 p->loc_Texture_ReflectCube        = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3724                 p->loc_Alpha                      = qglGetUniformLocationARB(p->program, "Alpha");
3725                 p->loc_BloomBlur_Parameters       = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3726                 p->loc_ClientTime                 = qglGetUniformLocationARB(p->program, "ClientTime");
3727                 p->loc_Color_Ambient              = qglGetUniformLocationARB(p->program, "Color_Ambient");
3728                 p->loc_Color_Diffuse              = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3729                 p->loc_Color_Specular             = qglGetUniformLocationARB(p->program, "Color_Specular");
3730                 p->loc_Color_Glow                 = qglGetUniformLocationARB(p->program, "Color_Glow");
3731                 p->loc_Color_Pants                = qglGetUniformLocationARB(p->program, "Color_Pants");
3732                 p->loc_Color_Shirt                = qglGetUniformLocationARB(p->program, "Color_Shirt");
3733                 p->loc_DeferredColor_Ambient      = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3734                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3735                 p->loc_DeferredColor_Specular     = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3736                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3737                 p->loc_DeferredMod_Specular       = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3738                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3739                 p->loc_EyePosition                = qglGetUniformLocationARB(p->program, "EyePosition");
3740                 p->loc_FogColor                   = qglGetUniformLocationARB(p->program, "FogColor");
3741                 p->loc_FogHeightFade              = qglGetUniformLocationARB(p->program, "FogHeightFade");
3742                 p->loc_FogPlane                   = qglGetUniformLocationARB(p->program, "FogPlane");
3743                 p->loc_FogPlaneViewDist           = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3744                 p->loc_FogRangeRecip              = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3745                 p->loc_LightColor                 = qglGetUniformLocationARB(p->program, "LightColor");
3746                 p->loc_LightDir                   = qglGetUniformLocationARB(p->program, "LightDir");
3747                 p->loc_LightPosition              = qglGetUniformLocationARB(p->program, "LightPosition");
3748                 p->loc_OffsetMapping_Scale        = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3749                 p->loc_PixelSize                  = qglGetUniformLocationARB(p->program, "PixelSize");
3750                 p->loc_ReflectColor               = qglGetUniformLocationARB(p->program, "ReflectColor");
3751                 p->loc_ReflectFactor              = qglGetUniformLocationARB(p->program, "ReflectFactor");
3752                 p->loc_ReflectOffset              = qglGetUniformLocationARB(p->program, "ReflectOffset");
3753                 p->loc_RefractColor               = qglGetUniformLocationARB(p->program, "RefractColor");
3754                 p->loc_Saturation                 = qglGetUniformLocationARB(p->program, "Saturation");
3755                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3756                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3757                 p->loc_ScreenToDepth              = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3758                 p->loc_ShadowMap_Parameters       = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3759                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3760                 p->loc_SpecularPower              = qglGetUniformLocationARB(p->program, "SpecularPower");
3761                 p->loc_UserVec1                   = qglGetUniformLocationARB(p->program, "UserVec1");
3762                 p->loc_UserVec2                   = qglGetUniformLocationARB(p->program, "UserVec2");
3763                 p->loc_UserVec3                   = qglGetUniformLocationARB(p->program, "UserVec3");
3764                 p->loc_UserVec4                   = qglGetUniformLocationARB(p->program, "UserVec4");
3765                 p->loc_ViewTintColor              = qglGetUniformLocationARB(p->program, "ViewTintColor");
3766                 p->loc_ViewToLight                = qglGetUniformLocationARB(p->program, "ViewToLight");
3767                 p->loc_ModelToLight               = qglGetUniformLocationARB(p->program, "ModelToLight");
3768                 p->loc_TexMatrix                  = qglGetUniformLocationARB(p->program, "TexMatrix");
3769                 p->loc_BackgroundTexMatrix        = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3770                 p->loc_ModelViewMatrix            = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3771                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3772                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3773                 p->loc_ModelToReflectCube         = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3774                 p->loc_ShadowMapMatrix            = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3775                 p->loc_BloomColorSubtract         = qglGetUniformLocationARB(p->program, "BloomColorSubtract");
3776                 // initialize the samplers to refer to the texture units we use
3777                 if (p->loc_Texture_First           >= 0) qglUniform1iARB(p->loc_Texture_First          , GL20TU_FIRST);
3778                 if (p->loc_Texture_Second          >= 0) qglUniform1iARB(p->loc_Texture_Second         , GL20TU_SECOND);
3779                 if (p->loc_Texture_GammaRamps      >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps     , GL20TU_GAMMARAMPS);
3780                 if (p->loc_Texture_Normal          >= 0) qglUniform1iARB(p->loc_Texture_Normal         , GL20TU_NORMAL);
3781                 if (p->loc_Texture_Color           >= 0) qglUniform1iARB(p->loc_Texture_Color          , GL20TU_COLOR);
3782                 if (p->loc_Texture_Gloss           >= 0) qglUniform1iARB(p->loc_Texture_Gloss          , GL20TU_GLOSS);
3783                 if (p->loc_Texture_Glow            >= 0) qglUniform1iARB(p->loc_Texture_Glow           , GL20TU_GLOW);
3784                 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3785                 if (p->loc_Texture_SecondaryColor  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3786                 if (p->loc_Texture_SecondaryGloss  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3787                 if (p->loc_Texture_SecondaryGlow   >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow  , GL20TU_SECONDARY_GLOW);
3788                 if (p->loc_Texture_Pants           >= 0) qglUniform1iARB(p->loc_Texture_Pants          , GL20TU_PANTS);
3789                 if (p->loc_Texture_Shirt           >= 0) qglUniform1iARB(p->loc_Texture_Shirt          , GL20TU_SHIRT);
3790                 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3791                 if (p->loc_Texture_FogMask         >= 0) qglUniform1iARB(p->loc_Texture_FogMask        , GL20TU_FOGMASK);
3792                 if (p->loc_Texture_Lightmap        >= 0) qglUniform1iARB(p->loc_Texture_Lightmap       , GL20TU_LIGHTMAP);
3793                 if (p->loc_Texture_Deluxemap       >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap      , GL20TU_DELUXEMAP);
3794                 if (p->loc_Texture_Attenuation     >= 0) qglUniform1iARB(p->loc_Texture_Attenuation    , GL20TU_ATTENUATION);
3795                 if (p->loc_Texture_Cube            >= 0) qglUniform1iARB(p->loc_Texture_Cube           , GL20TU_CUBE);
3796                 if (p->loc_Texture_Refraction      >= 0) qglUniform1iARB(p->loc_Texture_Refraction     , GL20TU_REFRACTION);
3797                 if (p->loc_Texture_Reflection      >= 0) qglUniform1iARB(p->loc_Texture_Reflection     , GL20TU_REFLECTION);
3798                 if (p->loc_Texture_ShadowMap2D     >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D    , GL20TU_SHADOWMAP2D);
3799                 if (p->loc_Texture_CubeProjection  >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3800                 if (p->loc_Texture_ScreenDepth     >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth    , GL20TU_SCREENDEPTH);
3801                 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3802                 if (p->loc_Texture_ScreenDiffuse   >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse  , GL20TU_SCREENDIFFUSE);
3803                 if (p->loc_Texture_ScreenSpecular  >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3804                 if (p->loc_Texture_ReflectMask     >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask    , GL20TU_REFLECTMASK);
3805                 if (p->loc_Texture_ReflectCube     >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube    , GL20TU_REFLECTCUBE);
3806                 CHECKGLERROR
3807                 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3808         }
3809         else
3810                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
3811
3812         // free the strings
3813         if (vertexstring)
3814                 Mem_Free(vertexstring);
3815         if (geometrystring)
3816                 Mem_Free(geometrystring);
3817         if (fragmentstring)
3818                 Mem_Free(fragmentstring);
3819 }
3820
3821 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3822 {
3823         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3824         if (r_glsl_permutation != perm)
3825         {
3826                 r_glsl_permutation = perm;
3827                 if (!r_glsl_permutation->program)
3828                 {
3829                         if (!r_glsl_permutation->compiled)
3830                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3831                         if (!r_glsl_permutation->program)
3832                         {
3833                                 // remove features until we find a valid permutation
3834                                 int i;
3835                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3836                                 {
3837                                         // reduce i more quickly whenever it would not remove any bits
3838                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3839                                         if (!(permutation & j))
3840                                                 continue;
3841                                         permutation -= j;
3842                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3843                                         if (!r_glsl_permutation->compiled)
3844                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3845                                         if (r_glsl_permutation->program)
3846                                                 break;
3847                                 }
3848                                 if (i >= SHADERPERMUTATION_COUNT)
3849                                 {
3850                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3851                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3852                                         qglUseProgramObjectARB(0);CHECKGLERROR
3853                                         return; // no bit left to clear, entire mode is broken
3854                                 }
3855                         }
3856                 }
3857                 CHECKGLERROR
3858                 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3859         }
3860         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3861         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3862         if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3863 }
3864
3865 #ifdef SUPPORTCG
3866 #include <Cg/cgGL.h>
3867 struct r_cg_permutation_s;
3868 typedef struct r_cg_permutation_s
3869 {
3870         /// hash lookup data
3871         struct r_cg_permutation_s *hashnext;
3872         unsigned int mode;
3873         unsigned int permutation;
3874
3875         /// indicates if we have tried compiling this permutation already
3876         qboolean compiled;
3877         /// 0 if compilation failed
3878         CGprogram vprogram;
3879         CGprogram fprogram;
3880         /// locations of detected parameters in programs, or NULL if not found
3881         CGparameter vp_EyePosition;
3882         CGparameter vp_FogPlane;
3883         CGparameter vp_LightDir;
3884         CGparameter vp_LightPosition;
3885         CGparameter vp_ModelToLight;
3886         CGparameter vp_TexMatrix;
3887         CGparameter vp_BackgroundTexMatrix;
3888         CGparameter vp_ModelViewProjectionMatrix;
3889         CGparameter vp_ModelViewMatrix;
3890         CGparameter vp_ShadowMapMatrix;
3891
3892         CGparameter fp_Texture_First;
3893         CGparameter fp_Texture_Second;
3894         CGparameter fp_Texture_GammaRamps;
3895         CGparameter fp_Texture_Normal;
3896         CGparameter fp_Texture_Color;
3897         CGparameter fp_Texture_Gloss;
3898         CGparameter fp_Texture_Glow;
3899         CGparameter fp_Texture_SecondaryNormal;
3900         CGparameter fp_Texture_SecondaryColor;
3901         CGparameter fp_Texture_SecondaryGloss;
3902         CGparameter fp_Texture_SecondaryGlow;
3903         CGparameter fp_Texture_Pants;
3904         CGparameter fp_Texture_Shirt;
3905         CGparameter fp_Texture_FogHeightTexture;
3906         CGparameter fp_Texture_FogMask;
3907         CGparameter fp_Texture_Lightmap;
3908         CGparameter fp_Texture_Deluxemap;
3909         CGparameter fp_Texture_Attenuation;
3910         CGparameter fp_Texture_Cube;
3911         CGparameter fp_Texture_Refraction;
3912         CGparameter fp_Texture_Reflection;
3913         CGparameter fp_Texture_ShadowMap2D;
3914         CGparameter fp_Texture_CubeProjection;
3915         CGparameter fp_Texture_ScreenDepth;
3916         CGparameter fp_Texture_ScreenNormalMap;
3917         CGparameter fp_Texture_ScreenDiffuse;
3918         CGparameter fp_Texture_ScreenSpecular;
3919         CGparameter fp_Texture_ReflectMask;
3920         CGparameter fp_Texture_ReflectCube;
3921         CGparameter fp_Alpha;
3922         CGparameter fp_BloomBlur_Parameters;
3923         CGparameter fp_ClientTime;
3924         CGparameter fp_Color_Ambient;
3925         CGparameter fp_Color_Diffuse;
3926         CGparameter fp_Color_Specular;
3927         CGparameter fp_Color_Glow;
3928         CGparameter fp_Color_Pants;
3929         CGparameter fp_Color_Shirt;
3930         CGparameter fp_DeferredColor_Ambient;
3931         CGparameter fp_DeferredColor_Diffuse;
3932         CGparameter fp_DeferredColor_Specular;
3933         CGparameter fp_DeferredMod_Diffuse;
3934         CGparameter fp_DeferredMod_Specular;
3935         CGparameter fp_DistortScaleRefractReflect;
3936         CGparameter fp_EyePosition;
3937         CGparameter fp_FogColor;
3938         CGparameter fp_FogHeightFade;
3939         CGparameter fp_FogPlane;
3940         CGparameter fp_FogPlaneViewDist;
3941         CGparameter fp_FogRangeRecip;
3942         CGparameter fp_LightColor;
3943         CGparameter fp_LightDir;
3944         CGparameter fp_LightPosition;
3945         CGparameter fp_OffsetMapping_Scale;
3946         CGparameter fp_PixelSize;
3947         CGparameter fp_ReflectColor;
3948         CGparameter fp_ReflectFactor;
3949         CGparameter fp_ReflectOffset;
3950         CGparameter fp_RefractColor;
3951         CGparameter fp_Saturation;
3952         CGparameter fp_ScreenCenterRefractReflect;
3953         CGparameter fp_ScreenScaleRefractReflect;
3954         CGparameter fp_ScreenToDepth;
3955         CGparameter fp_ShadowMap_Parameters;
3956         CGparameter fp_ShadowMap_TextureScale;
3957         CGparameter fp_SpecularPower;
3958         CGparameter fp_UserVec1;
3959         CGparameter fp_UserVec2;
3960         CGparameter fp_UserVec3;
3961         CGparameter fp_UserVec4;
3962         CGparameter fp_ViewTintColor;
3963         CGparameter fp_ViewToLight;
3964         CGparameter fp_PixelToScreenTexCoord;
3965         CGparameter fp_ModelToReflectCube;
3966         CGparameter fp_BloomColorSubtract;
3967 }
3968 r_cg_permutation_t;
3969
3970 /// information about each possible shader permutation
3971 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3972 /// currently selected permutation
3973 r_cg_permutation_t *r_cg_permutation;
3974 /// storage for permutations linked in the hash table
3975 memexpandablearray_t r_cg_permutationarray;
3976
3977 #define CHECKCGERROR {CGerror err = cgGetError(), err2 = err;if (err){Con_Printf("%s:%i CG error %i: %s : %s\n", __FILE__, __LINE__, err, cgGetErrorString(err), cgGetLastErrorString(&err2));if (err == 1) Con_Printf("last listing:\n%s\n", cgGetLastListing(vid.cgcontext));}}
3978
3979 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
3980 {
3981         //unsigned int hashdepth = 0;
3982         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3983         r_cg_permutation_t *p;
3984         for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
3985         {
3986                 if (p->mode == mode && p->permutation == permutation)
3987                 {
3988                         //if (hashdepth > 10)
3989                         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3990                         return p;
3991                 }
3992                 //hashdepth++;
3993         }
3994         p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
3995         p->mode = mode;
3996         p->permutation = permutation;
3997         p->hashnext = r_cg_permutationhash[mode][hashindex];
3998         r_cg_permutationhash[mode][hashindex] = p;
3999         //if (hashdepth > 10)
4000         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4001         return p;
4002 }
4003
4004 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4005 {
4006         char *shaderstring;
4007         if (!filename || !filename[0])
4008                 return NULL;
4009         if (!strcmp(filename, "cg/default.cg"))
4010         {
4011                 if (!cgshaderstring)
4012                 {
4013                         cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4014                         if (cgshaderstring)
4015                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
4016                         else
4017                                 cgshaderstring = (char *)builtincgshaderstring;
4018                 }
4019                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4020                 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4021                 return shaderstring;
4022         }
4023         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4024         if (shaderstring)
4025         {
4026                 if (printfromdisknotice)
4027                         Con_DPrintf("from disk %s... ", filename);
4028                 return shaderstring;
4029         }
4030         return shaderstring;
4031 }
4032
4033 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4034 {
4035         // TODO: load or create .fp and .vp shader files
4036 }
4037
4038 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4039 {
4040         int i;
4041         shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4042         int vertstrings_count = 0, vertstring_length = 0;
4043         int geomstrings_count = 0, geomstring_length = 0;
4044         int fragstrings_count = 0, fragstring_length = 0;
4045         char *t;
4046         char *vertexstring, *geometrystring, *fragmentstring;
4047         char *vertstring, *geomstring, *fragstring;
4048         const char *vertstrings_list[32+3];
4049         const char *geomstrings_list[32+3];
4050         const char *fragstrings_list[32+3];
4051         char permutationname[256];
4052         char cachename[256];
4053         CGprofile vertexProfile;
4054         CGprofile fragmentProfile;
4055
4056         if (p->compiled)
4057                 return;
4058         p->compiled = true;
4059         p->vprogram = NULL;
4060         p->fprogram = NULL;
4061
4062         permutationname[0] = 0;
4063         cachename[0] = 0;
4064         vertexstring   = R_CG_GetText(modeinfo->vertexfilename, true);
4065         geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4066         fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4067
4068         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4069         strlcat(cachename, "cg/", sizeof(cachename));
4070
4071         // the first pretext is which type of shader to compile as
4072         // (later these will all be bound together as a program object)
4073         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4074         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4075         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4076
4077         // the second pretext is the mode (for example a light source)
4078         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4079         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4080         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4081         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4082         strlcat(cachename, modeinfo->name, sizeof(cachename));
4083
4084         // now add all the permutation pretexts
4085         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4086         {
4087                 if (permutation & (1<<i))
4088                 {
4089                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4090                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4091                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4092                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4093                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4094                 }
4095                 else
4096                 {
4097                         // keep line numbers correct
4098                         vertstrings_list[vertstrings_count++] = "\n";
4099                         geomstrings_list[geomstrings_count++] = "\n";
4100                         fragstrings_list[fragstrings_count++] = "\n";
4101                 }
4102         }
4103
4104         // replace spaces in the cachename with _ characters
4105         for (i = 0;cachename[i];i++)
4106                 if (cachename[i] == ' ')
4107                         cachename[i] = '_';
4108
4109         // now append the shader text itself
4110         vertstrings_list[vertstrings_count++] = vertexstring;
4111         geomstrings_list[geomstrings_count++] = geometrystring;
4112         fragstrings_list[fragstrings_count++] = fragmentstring;
4113
4114         // if any sources were NULL, clear the respective list
4115         if (!vertexstring)
4116                 vertstrings_count = 0;
4117         if (!geometrystring)
4118                 geomstrings_count = 0;
4119         if (!fragmentstring)
4120                 fragstrings_count = 0;
4121
4122         vertstring_length = 0;
4123         for (i = 0;i < vertstrings_count;i++)
4124                 vertstring_length += strlen(vertstrings_list[i]);
4125         vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4126         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4127                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4128
4129         geomstring_length = 0;
4130         for (i = 0;i < geomstrings_count;i++)
4131                 geomstring_length += strlen(geomstrings_list[i]);
4132         geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4133         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4134                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4135
4136         fragstring_length = 0;
4137         for (i = 0;i < fragstrings_count;i++)
4138                 fragstring_length += strlen(fragstrings_list[i]);
4139         fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4140         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4141                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4142
4143         CHECKGLERROR
4144         CHECKCGERROR
4145         //vertexProfile = CG_PROFILE_ARBVP1;
4146         //fragmentProfile = CG_PROFILE_ARBFP1;
4147         vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4148         fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4149         //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4150         //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4151         //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4152         CHECKGLERROR
4153
4154         // try to load the cached shader, or generate one
4155         R_CG_CacheShader(p, cachename, vertstring, fragstring);
4156
4157         // if caching failed, do a dynamic compile for now
4158         CHECKCGERROR
4159         if (vertstring[0] && !p->vprogram)
4160                 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4161         CHECKCGERROR
4162         if (fragstring[0] && !p->fprogram)
4163                 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4164         CHECKCGERROR
4165
4166         // look up all the uniform variable names we care about, so we don't
4167         // have to look them up every time we set them
4168         if (p->vprogram)
4169         {
4170                 CHECKCGERROR
4171                 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4172                 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4173                 p->vp_EyePosition                = cgGetNamedParameter(p->vprogram, "EyePosition");
4174                 p->vp_FogPlane                   = cgGetNamedParameter(p->vprogram, "FogPlane");
4175                 p->vp_LightDir                   = cgGetNamedParameter(p->vprogram, "LightDir");
4176                 p->vp_LightPosition              = cgGetNamedParameter(p->vprogram, "LightPosition");
4177                 p->vp_ModelToLight               = cgGetNamedParameter(p->vprogram, "ModelToLight");
4178                 p->vp_TexMatrix                  = cgGetNamedParameter(p->vprogram, "TexMatrix");
4179                 p->vp_BackgroundTexMatrix        = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4180                 p->vp_ModelViewProjectionMatrix  = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4181                 p->vp_ModelViewMatrix            = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4182                 p->vp_ShadowMapMatrix            = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4183                 CHECKCGERROR
4184         }
4185         if (p->fprogram)
4186         {
4187                 CHECKCGERROR
4188                 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4189                 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4190                 p->fp_Texture_First              = cgGetNamedParameter(p->fprogram, "Texture_First");
4191                 p->fp_Texture_Second             = cgGetNamedParameter(p->fprogram, "Texture_Second");
4192                 p->fp_Texture_GammaRamps         = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4193                 p->fp_Texture_Normal             = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4194                 p->fp_Texture_Color              = cgGetNamedParameter(p->fprogram, "Texture_Color");
4195                 p->fp_Texture_Gloss              = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4196                 p->fp_Texture_Glow               = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4197                 p->fp_Texture_SecondaryNormal    = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4198                 p->fp_Texture_SecondaryColor     = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4199                 p->fp_Texture_SecondaryGloss     = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4200                 p->fp_Texture_SecondaryGlow      = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4201                 p->fp_Texture_Pants              = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4202                 p->fp_Texture_Shirt              = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4203                 p->fp_Texture_FogHeightTexture   = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4204                 p->fp_Texture_FogMask            = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4205                 p->fp_Texture_Lightmap           = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4206                 p->fp_Texture_Deluxemap          = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4207                 p->fp_Texture_Attenuation        = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4208                 p->fp_Texture_Cube               = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4209                 p->fp_Texture_Refraction         = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4210                 p->fp_Texture_Reflection         = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4211                 p->fp_Texture_ShadowMap2D        = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4212                 p->fp_Texture_CubeProjection     = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4213                 p->fp_Texture_ScreenDepth        = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4214                 p->fp_Texture_ScreenNormalMap    = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4215                 p->fp_Texture_ScreenDiffuse      = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4216                 p->fp_Texture_ScreenSpecular     = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4217                 p->fp_Texture_ReflectMask        = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4218                 p->fp_Texture_ReflectCube        = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4219                 p->fp_Alpha                      = cgGetNamedParameter(p->fprogram, "Alpha");
4220                 p->fp_BloomBlur_Parameters       = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4221                 p->fp_ClientTime                 = cgGetNamedParameter(p->fprogram, "ClientTime");
4222                 p->fp_Color_Ambient              = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4223                 p->fp_Color_Diffuse              = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4224                 p->fp_Color_Specular             = cgGetNamedParameter(p->fprogram, "Color_Specular");
4225                 p->fp_Color_Glow                 = cgGetNamedParameter(p->fprogram, "Color_Glow");
4226                 p->fp_Color_Pants                = cgGetNamedParameter(p->fprogram, "Color_Pants");
4227                 p->fp_Color_Shirt                = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4228                 p->fp_DeferredColor_Ambient      = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4229                 p->fp_DeferredColor_Diffuse      = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4230                 p->fp_DeferredColor_Specular     = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4231                 p->fp_DeferredMod_Diffuse        = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4232                 p->fp_DeferredMod_Specular       = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4233                 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4234                 p->fp_EyePosition                = cgGetNamedParameter(p->fprogram, "EyePosition");
4235                 p->fp_FogColor                   = cgGetNamedParameter(p->fprogram, "FogColor");
4236                 p->fp_FogHeightFade              = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4237                 p->fp_FogPlane                   = cgGetNamedParameter(p->fprogram, "FogPlane");
4238                 p->fp_FogPlaneViewDist           = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4239                 p->fp_FogRangeRecip              = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4240                 p->fp_LightColor                 = cgGetNamedParameter(p->fprogram, "LightColor");
4241                 p->fp_LightDir                   = cgGetNamedParameter(p->fprogram, "LightDir");
4242                 p->fp_LightPosition              = cgGetNamedParameter(p->fprogram, "LightPosition");
4243                 p->fp_OffsetMapping_Scale        = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4244                 p->fp_PixelSize                  = cgGetNamedParameter(p->fprogram, "PixelSize");
4245                 p->fp_ReflectColor               = cgGetNamedParameter(p->fprogram, "ReflectColor");
4246                 p->fp_ReflectFactor              = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4247                 p->fp_ReflectOffset              = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4248                 p->fp_RefractColor               = cgGetNamedParameter(p->fprogram, "RefractColor");
4249                 p->fp_Saturation                 = cgGetNamedParameter(p->fprogram, "Saturation");
4250                 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4251                 p->fp_ScreenScaleRefractReflect  = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4252                 p->fp_ScreenToDepth              = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4253                 p->fp_ShadowMap_Parameters       = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4254                 p->fp_ShadowMap_TextureScale     = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4255                 p->fp_SpecularPower              = cgGetNamedParameter(p->fprogram, "SpecularPower");
4256                 p->fp_UserVec1                   = cgGetNamedParameter(p->fprogram, "UserVec1");
4257                 p->fp_UserVec2                   = cgGetNamedParameter(p->fprogram, "UserVec2");
4258                 p->fp_UserVec3                   = cgGetNamedParameter(p->fprogram, "UserVec3");
4259                 p->fp_UserVec4                   = cgGetNamedParameter(p->fprogram, "UserVec4");
4260                 p->fp_ViewTintColor              = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4261                 p->fp_ViewToLight                = cgGetNamedParameter(p->fprogram, "ViewToLight");
4262                 p->fp_PixelToScreenTexCoord      = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4263                 p->fp_ModelToReflectCube         = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4264                 p->fp_BloomColorSubtract         = cgGetNamedParameter(p->fprogram, "BloomColorSubtract");
4265                 CHECKCGERROR
4266         }
4267
4268         if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4269                 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4270         else
4271                 Con_Printf("^1CG shader %s failed!  some features may not work properly.\n", permutationname);
4272
4273         // free the strings
4274         if (vertstring)
4275                 Mem_Free(vertstring);
4276         if (geomstring)
4277                 Mem_Free(geomstring);
4278         if (fragstring)
4279                 Mem_Free(fragstring);
4280         if (vertexstring)
4281                 Mem_Free(vertexstring);
4282         if (geometrystring)
4283                 Mem_Free(geometrystring);
4284         if (fragmentstring)
4285                 Mem_Free(fragmentstring);
4286 }
4287
4288 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4289 {
4290         r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4291         CHECKGLERROR
4292         CHECKCGERROR
4293         if (r_cg_permutation != perm)
4294         {
4295                 r_cg_permutation = perm;
4296                 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4297                 {
4298                         if (!r_cg_permutation->compiled)
4299                                 R_CG_CompilePermutation(perm, mode, permutation);
4300                         if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4301                         {
4302                                 // remove features until we find a valid permutation
4303                                 int i;
4304                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4305                                 {
4306                                         // reduce i more quickly whenever it would not remove any bits
4307                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4308                                         if (!(permutation & j))
4309                                                 continue;
4310                                         permutation -= j;
4311                                         r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4312                                         if (!r_cg_permutation->compiled)
4313                                                 R_CG_CompilePermutation(perm, mode, permutation);
4314                                         if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4315                                                 break;
4316                                 }
4317                                 if (i >= SHADERPERMUTATION_COUNT)
4318                                 {
4319                                         //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4320                                         r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4321                                         return; // no bit left to clear, entire mode is broken
4322                                 }
4323                         }
4324                 }
4325                 CHECKGLERROR
4326                 CHECKCGERROR
4327                 if (r_cg_permutation->vprogram)
4328                 {
4329                         cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4330                         cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4331                         cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4332                 }
4333                 else
4334                 {
4335                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4336                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4337                 }
4338                 if (r_cg_permutation->fprogram)
4339                 {
4340                         cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4341                         cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4342                         cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4343                 }
4344                 else
4345                 {
4346                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4347                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4348                 }
4349         }
4350         CHECKCGERROR
4351         if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4352         if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4353         if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4354 }
4355
4356 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4357 {
4358         cgGLSetTextureParameter(param, R_GetTexture(tex));
4359         cgGLEnableTextureParameter(param);
4360 }
4361 #endif
4362
4363 #ifdef SUPPORTD3D
4364
4365 #ifdef SUPPORTD3D
4366 #include <d3d9.h>
4367 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
4368 extern D3DCAPS9 vid_d3d9caps;
4369 #endif
4370
4371 struct r_hlsl_permutation_s;
4372 typedef struct r_hlsl_permutation_s
4373 {
4374         /// hash lookup data
4375         struct r_hlsl_permutation_s *hashnext;
4376         unsigned int mode;
4377         unsigned int permutation;
4378
4379         /// indicates if we have tried compiling this permutation already
4380         qboolean compiled;
4381         /// NULL if compilation failed
4382         IDirect3DVertexShader9 *vertexshader;
4383         IDirect3DPixelShader9 *pixelshader;
4384 }
4385 r_hlsl_permutation_t;
4386
4387 typedef enum D3DVSREGISTER_e
4388 {
4389         D3DVSREGISTER_TexMatrix = 0, // float4x4
4390         D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
4391         D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
4392         D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
4393         D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
4394         D3DVSREGISTER_ModelToLight = 20, // float4x4
4395         D3DVSREGISTER_EyePosition = 24,
4396         D3DVSREGISTER_FogPlane = 25,
4397         D3DVSREGISTER_LightDir = 26,
4398         D3DVSREGISTER_LightPosition = 27,
4399 }
4400 D3DVSREGISTER_t;
4401
4402 typedef enum D3DPSREGISTER_e
4403 {
4404         D3DPSREGISTER_Alpha = 0,
4405         D3DPSREGISTER_BloomBlur_Parameters = 1,
4406         D3DPSREGISTER_ClientTime = 2,
4407         D3DPSREGISTER_Color_Ambient = 3,
4408         D3DPSREGISTER_Color_Diffuse = 4,
4409         D3DPSREGISTER_Color_Specular = 5,
4410         D3DPSREGISTER_Color_Glow = 6,
4411         D3DPSREGISTER_Color_Pants = 7,
4412         D3DPSREGISTER_Color_Shirt = 8,
4413         D3DPSREGISTER_DeferredColor_Ambient = 9,
4414         D3DPSREGISTER_DeferredColor_Diffuse = 10,
4415         D3DPSREGISTER_DeferredColor_Specular = 11,
4416         D3DPSREGISTER_DeferredMod_Diffuse = 12,
4417         D3DPSREGISTER_DeferredMod_Specular = 13,
4418         D3DPSREGISTER_DistortScaleRefractReflect = 14,
4419         D3DPSREGISTER_EyePosition = 15, // unused
4420         D3DPSREGISTER_FogColor = 16,
4421         D3DPSREGISTER_FogHeightFade = 17,
4422         D3DPSREGISTER_FogPlane = 18,
4423         D3DPSREGISTER_FogPlaneViewDist = 19,
4424         D3DPSREGISTER_FogRangeRecip = 20,
4425         D3DPSREGISTER_LightColor = 21,
4426         D3DPSREGISTER_LightDir = 22, // unused
4427         D3DPSREGISTER_LightPosition = 23,
4428         D3DPSREGISTER_OffsetMapping_Scale = 24,
4429         D3DPSREGISTER_PixelSize = 25,
4430         D3DPSREGISTER_ReflectColor = 26,
4431         D3DPSREGISTER_ReflectFactor = 27,
4432         D3DPSREGISTER_ReflectOffset = 28,
4433         D3DPSREGISTER_RefractColor = 29,
4434         D3DPSREGISTER_Saturation = 30,
4435         D3DPSREGISTER_ScreenCenterRefractReflect = 31,
4436         D3DPSREGISTER_ScreenScaleRefractReflect = 32,
4437         D3DPSREGISTER_ScreenToDepth = 33,
4438         D3DPSREGISTER_ShadowMap_Parameters = 34,
4439         D3DPSREGISTER_ShadowMap_TextureScale = 35,
4440         D3DPSREGISTER_SpecularPower = 36,
4441         D3DPSREGISTER_UserVec1 = 37,
4442         D3DPSREGISTER_UserVec2 = 38,
4443         D3DPSREGISTER_UserVec3 = 39,
4444         D3DPSREGISTER_UserVec4 = 40,
4445         D3DPSREGISTER_ViewTintColor = 41,
4446         D3DPSREGISTER_PixelToScreenTexCoord = 42,
4447         D3DPSREGISTER_BloomColorSubtract = 43,
4448         D3DPSREGISTER_ViewToLight = 44, // float4x4
4449         D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
4450         // next at 52
4451 }
4452 D3DPSREGISTER_t;
4453
4454 /// information about each possible shader permutation
4455 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4456 /// currently selected permutation
4457 r_hlsl_permutation_t *r_hlsl_permutation;
4458 /// storage for permutations linked in the hash table
4459 memexpandablearray_t r_hlsl_permutationarray;
4460
4461 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
4462 {
4463         //unsigned int hashdepth = 0;
4464         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4465         r_hlsl_permutation_t *p;
4466         for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
4467         {
4468                 if (p->mode == mode && p->permutation == permutation)
4469                 {
4470                         //if (hashdepth > 10)
4471                         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4472                         return p;
4473                 }
4474                 //hashdepth++;
4475         }
4476         p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
4477         p->mode = mode;
4478         p->permutation = permutation;
4479         p->hashnext = r_hlsl_permutationhash[mode][hashindex];
4480         r_hlsl_permutationhash[mode][hashindex] = p;
4481         //if (hashdepth > 10)
4482         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4483         return p;
4484 }
4485
4486 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
4487 {
4488         char *shaderstring;
4489         if (!filename || !filename[0])
4490                 return NULL;
4491         if (!strcmp(filename, "hlsl/default.hlsl"))
4492         {
4493                 if (!hlslshaderstring)
4494                 {
4495                         hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4496                         if (hlslshaderstring)
4497                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
4498                         else
4499                                 hlslshaderstring = (char *)builtincgshaderstring;
4500                 }
4501                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
4502                 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
4503                 return shaderstring;
4504         }
4505         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4506         if (shaderstring)
4507         {
4508                 if (printfromdisknotice)
4509                         Con_DPrintf("from disk %s... ", filename);
4510                 return shaderstring;
4511         }
4512         return shaderstring;
4513 }
4514
4515 #include <d3dx9.h>
4516 //#include <d3dx9shader.h>
4517 //#include <d3dx9mesh.h>
4518
4519 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4520 {
4521         DWORD *vsbin = NULL;
4522         DWORD *psbin = NULL;
4523         fs_offset_t vsbinsize;
4524         fs_offset_t psbinsize;
4525 //      IDirect3DVertexShader9 *vs = NULL;
4526 //      IDirect3DPixelShader9 *ps = NULL;
4527         ID3DXBuffer *vslog = NULL;
4528         ID3DXBuffer *vsbuffer = NULL;
4529         ID3DXConstantTable *vsconstanttable = NULL;
4530         ID3DXBuffer *pslog = NULL;
4531         ID3DXBuffer *psbuffer = NULL;
4532         ID3DXConstantTable *psconstanttable = NULL;
4533         int vsresult = 0;
4534         int psresult = 0;
4535         char temp[MAX_INPUTLINE];
4536         const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
4537         qboolean debugshader = gl_paranoid.integer != 0;
4538         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4539         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4540         if (!debugshader)
4541         {
4542                 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
4543                 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
4544         }
4545         if ((!vsbin && vertstring) || (!psbin && fragstring))
4546         {
4547                 const char* dllnames_d3dx9 [] =
4548                 {
4549                         "d3dx9_43.dll",
4550                         "d3dx9_42.dll",
4551                         "d3dx9_41.dll",
4552                         "d3dx9_40.dll",
4553                         "d3dx9_39.dll",
4554                         "d3dx9_38.dll",
4555                         "d3dx9_37.dll",
4556                         "d3dx9_36.dll",
4557                         "d3dx9_35.dll",
4558                         "d3dx9_34.dll",
4559                         "d3dx9_33.dll",
4560                         "d3dx9_32.dll",
4561                         "d3dx9_31.dll",
4562                         "d3dx9_30.dll",
4563                         "d3dx9_29.dll",
4564                         "d3dx9_28.dll",
4565                         "d3dx9_27.dll",
4566                         "d3dx9_26.dll",
4567                         "d3dx9_25.dll",
4568                         "d3dx9_24.dll",
4569                         NULL
4570                 };
4571                 dllhandle_t d3dx9_dll = NULL;
4572                 HRESULT (WINAPI *qD3DXCompileShaderFromFileA)(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4573                 HRESULT (WINAPI *qD3DXPreprocessShader)(LPCSTR pSrcData, UINT SrcDataSize, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPD3DXBUFFER* ppShaderText, LPD3DXBUFFER* ppErrorMsgs);
4574                 HRESULT (WINAPI *qD3DXCompileShader)(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4575                 dllfunction_t d3dx9_dllfuncs[] =
4576                 {
4577                         {"D3DXCompileShaderFromFileA",  (void **) &qD3DXCompileShaderFromFileA},
4578                         {"D3DXPreprocessShader",                (void **) &qD3DXPreprocessShader},
4579                         {"D3DXCompileShader",                   (void **) &qD3DXCompileShader},
4580                         {NULL, NULL}
4581                 };
4582                 if (Sys_LoadLibrary(dllnames_d3dx9, &d3dx9_dll, d3dx9_dllfuncs))
4583                 {
4584                         DWORD shaderflags = 0;
4585                         if (debugshader)
4586                                 shaderflags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION;
4587                         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4588                         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4589                         if (vertstring && vertstring[0])
4590                         {
4591                                 if (debugshader)
4592                                 {
4593 //                                      vsresult = qD3DXPreprocessShader(vertstring, strlen(vertstring), NULL, NULL, &vsbuffer, &vslog);
4594 //                                      FS_WriteFile(va("%s_vs.fx", cachename), vsbuffer->GetBufferPointer(), vsbuffer->GetBufferSize());
4595                                         FS_WriteFile(va("%s_vs.fx", cachename), vertstring, strlen(vertstring));
4596                                         vsresult = qD3DXCompileShaderFromFileA(va("%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4597                                 }
4598                                 else
4599                                         vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4600                                 if (vsbuffer)
4601                                 {
4602                                         vsbinsize = vsbuffer->GetBufferSize();
4603                                         vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
4604                                         memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
4605                                         vsbuffer->Release();
4606                                 }
4607                                 if (vslog)
4608                                 {
4609                                         strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
4610                                         Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
4611                                         vslog->Release();
4612                                 }
4613                         }
4614                         if (fragstring && fragstring[0])
4615                         {
4616                                 if (debugshader)
4617                                 {
4618 //                                      psresult = qD3DXPreprocessShader(fragstring, strlen(fragstring), NULL, NULL, &psbuffer, &pslog);
4619 //                                      FS_WriteFile(va("%s_ps.fx", cachename), psbuffer->GetBufferPointer(), psbuffer->GetBufferSize());
4620                                         FS_WriteFile(va("%s_ps.fx", cachename), fragstring, strlen(fragstring));
4621                                         psresult = qD3DXCompileShaderFromFileA(va("%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4622                                 }
4623                                 else
4624                                         psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4625                                 if (psbuffer)
4626                                 {
4627                                         psbinsize = psbuffer->GetBufferSize();
4628                                         psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
4629                                         memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
4630                                         psbuffer->Release();
4631                                 }
4632                                 if (pslog)
4633                                 {
4634                                         strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
4635                                         Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
4636                                         pslog->Release();
4637                                 }
4638                         }
4639                         Sys_UnloadLibrary(&d3dx9_dll);
4640                 }
4641                 else
4642                         Con_Printf("Unable to compile shader - D3DXCompileShader function not found\n");
4643         }
4644         if (vsbin && psbin)
4645         {
4646                 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
4647                 if (FAILED(vsresult))
4648                         Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
4649                 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
4650                 if (FAILED(psresult))
4651                         Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
4652         }
4653         // free the shader data
4654         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4655         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4656 }
4657
4658 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
4659 {
4660         int i;
4661         shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
4662         int vertstrings_count = 0, vertstring_length = 0;
4663         int geomstrings_count = 0, geomstring_length = 0;
4664         int fragstrings_count = 0, fragstring_length = 0;
4665         char *t;
4666         char *vertexstring, *geometrystring, *fragmentstring;
4667         char *vertstring, *geomstring, *fragstring;
4668         const char *vertstrings_list[32+3];
4669         const char *geomstrings_list[32+3];
4670         const char *fragstrings_list[32+3];
4671         char permutationname[256];
4672         char cachename[256];
4673
4674         if (p->compiled)
4675                 return;
4676         p->compiled = true;
4677         p->vertexshader = NULL;
4678         p->pixelshader = NULL;
4679
4680         permutationname[0] = 0;
4681         cachename[0] = 0;
4682         vertexstring   = R_HLSL_GetText(modeinfo->vertexfilename, true);
4683         geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
4684         fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
4685
4686         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4687         strlcat(cachename, "hlsl/", sizeof(cachename));
4688
4689         // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
4690         vertstrings_list[vertstrings_count++] = "#define HLSL\n";
4691         geomstrings_list[geomstrings_count++] = "#define HLSL\n";
4692         fragstrings_list[fragstrings_count++] = "#define HLSL\n";
4693
4694         // the first pretext is which type of shader to compile as
4695         // (later these will all be bound together as a program object)
4696         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4697         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4698         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4699
4700         // the second pretext is the mode (for example a light source)
4701         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4702         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4703         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4704         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4705         strlcat(cachename, modeinfo->name, sizeof(cachename));
4706
4707         // now add all the permutation pretexts
4708         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4709         {
4710                 if (permutation & (1<<i))
4711                 {
4712                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4713                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4714                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4715                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4716                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4717                 }
4718                 else
4719                 {
4720                         // keep line numbers correct
4721                         vertstrings_list[vertstrings_count++] = "\n";
4722                         geomstrings_list[geomstrings_count++] = "\n";
4723                         fragstrings_list[fragstrings_count++] = "\n";
4724                 }
4725         }
4726
4727         // replace spaces in the cachename with _ characters
4728         for (i = 0;cachename[i];i++)
4729                 if (cachename[i] == ' ')
4730                         cachename[i] = '_';
4731
4732         // now append the shader text itself
4733         vertstrings_list[vertstrings_count++] = vertexstring;
4734         geomstrings_list[geomstrings_count++] = geometrystring;
4735         fragstrings_list[fragstrings_count++] = fragmentstring;
4736
4737         // if any sources were NULL, clear the respective list
4738         if (!vertexstring)
4739                 vertstrings_count = 0;
4740         if (!geometrystring)
4741                 geomstrings_count = 0;
4742         if (!fragmentstring)
4743                 fragstrings_count = 0;
4744
4745         vertstring_length = 0;
4746         for (i = 0;i < vertstrings_count;i++)
4747                 vertstring_length += strlen(vertstrings_list[i]);
4748         vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
4749         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4750                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4751
4752         geomstring_length = 0;
4753         for (i = 0;i < geomstrings_count;i++)
4754                 geomstring_length += strlen(geomstrings_list[i]);
4755         geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
4756         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4757                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4758
4759         fragstring_length = 0;
4760         for (i = 0;i < fragstrings_count;i++)
4761                 fragstring_length += strlen(fragstrings_list[i]);
4762         fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
4763         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4764                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4765
4766         // try to load the cached shader, or generate one
4767         R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
4768
4769         if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
4770                 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
4771         else
4772                 Con_Printf("^1HLSL shader %s failed!  some features may not work properly.\n", permutationname);
4773
4774         // free the strings
4775         if (vertstring)
4776                 Mem_Free(vertstring);
4777         if (geomstring)
4778                 Mem_Free(geomstring);
4779         if (fragstring)
4780                 Mem_Free(fragstring);
4781         if (vertexstring)
4782                 Mem_Free(vertexstring);
4783         if (geometrystring)
4784                 Mem_Free(geometrystring);
4785         if (fragmentstring)
4786                 Mem_Free(fragmentstring);
4787 }
4788
4789 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
4790 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
4791 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4792 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4793 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4794 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4795
4796 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
4797 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
4798 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4799 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4800 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4801 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4802
4803 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
4804 {
4805         r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
4806         if (r_hlsl_permutation != perm)
4807         {
4808                 r_hlsl_permutation = perm;
4809                 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4810                 {
4811                         if (!r_hlsl_permutation->compiled)
4812                                 R_HLSL_CompilePermutation(perm, mode, permutation);
4813                         if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4814                         {
4815                                 // remove features until we find a valid permutation
4816                                 int i;
4817                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4818                                 {
4819                                         // reduce i more quickly whenever it would not remove any bits
4820                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4821                                         if (!(permutation & j))
4822                                                 continue;
4823                                         permutation -= j;
4824                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4825                                         if (!r_hlsl_permutation->compiled)
4826                                                 R_HLSL_CompilePermutation(perm, mode, permutation);
4827                                         if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
4828                                                 break;
4829                                 }
4830                                 if (i >= SHADERPERMUTATION_COUNT)
4831                                 {
4832                                         //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4833                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4834                                         return; // no bit left to clear, entire mode is broken
4835                                 }
4836                         }
4837                 }
4838                 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
4839                 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
4840         }
4841         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
4842         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
4843         hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
4844 }
4845 #endif
4846
4847 void R_GLSL_Restart_f(void)
4848 {
4849         unsigned int i, limit;
4850         if (glslshaderstring && glslshaderstring != builtinshaderstring)
4851                 Mem_Free(glslshaderstring);
4852         glslshaderstring = NULL;
4853         if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4854                 Mem_Free(cgshaderstring);
4855         cgshaderstring = NULL;
4856         if (hlslshaderstring && hlslshaderstring != builtincgshaderstring)
4857                 Mem_Free(hlslshaderstring);
4858         hlslshaderstring = NULL;
4859         switch(vid.renderpath)
4860         {
4861         case RENDERPATH_D3D9:
4862 #ifdef SUPPORTD3D
4863                 {
4864                         r_hlsl_permutation_t *p;
4865                         r_hlsl_permutation = NULL;
4866 //                      cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4867 //                      cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4868 //                      cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4869 //                      cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4870                         limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
4871                         for (i = 0;i < limit;i++)
4872                         {
4873                                 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
4874                                 {
4875                                         if (p->vertexshader)
4876                                                 IDirect3DVertexShader9_Release(p->vertexshader);
4877                                         if (p->pixelshader)
4878                                                 IDirect3DPixelShader9_Release(p->pixelshader);
4879                                         Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
4880                                 }
4881                         }
4882                         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4883                 }
4884 #endif
4885                 break;
4886         case RENDERPATH_D3D10:
4887                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4888                 break;
4889         case RENDERPATH_D3D11:
4890                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4891                 break;
4892         case RENDERPATH_GL20:
4893                 {
4894                         r_glsl_permutation_t *p;
4895                         r_glsl_permutation = NULL;
4896                         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4897                         for (i = 0;i < limit;i++)
4898                         {
4899                                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4900                                 {
4901                                         GL_Backend_FreeProgram(p->program);
4902                                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4903                                 }
4904                         }
4905                         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4906                 }
4907                 break;
4908         case RENDERPATH_CGGL:
4909 #ifdef SUPPORTCG
4910                 {
4911                         r_cg_permutation_t *p;
4912                         r_cg_permutation = NULL;
4913                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4914                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4915                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4916                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4917                         limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4918                         for (i = 0;i < limit;i++)
4919                         {
4920                                 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4921                                 {
4922                                         if (p->vprogram)
4923                                                 cgDestroyProgram(p->vprogram);
4924                                         if (p->fprogram)
4925                                                 cgDestroyProgram(p->fprogram);
4926                                         Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4927                                 }
4928                         }
4929                         memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4930                 }
4931 #endif
4932                 break;
4933         case RENDERPATH_GL13:
4934         case RENDERPATH_GL11:
4935                 break;
4936         }
4937 }
4938
4939 void R_GLSL_DumpShader_f(void)
4940 {
4941         int i;
4942         qfile_t *file;
4943
4944         file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4945         if (file)
4946         {
4947                 FS_Print(file, "/* The engine may define the following macros:\n");
4948                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4949                 for (i = 0;i < SHADERMODE_COUNT;i++)
4950                         FS_Print(file, glslshadermodeinfo[i].pretext);
4951                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4952                         FS_Print(file, shaderpermutationinfo[i].pretext);
4953                 FS_Print(file, "*/\n");
4954                 FS_Print(file, builtinshaderstring);
4955                 FS_Close(file);
4956                 Con_Printf("glsl/default.glsl written\n");
4957         }
4958         else
4959                 Con_Printf("failed to write to glsl/default.glsl\n");
4960
4961 #ifdef SUPPORTCG
4962         file = FS_OpenRealFile("cg/default.cg", "w", false);
4963         if (file)
4964         {
4965                 FS_Print(file, "/* The engine may define the following macros:\n");
4966                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4967                 for (i = 0;i < SHADERMODE_COUNT;i++)
4968                         FS_Print(file, cgshadermodeinfo[i].pretext);
4969                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4970                         FS_Print(file, shaderpermutationinfo[i].pretext);
4971                 FS_Print(file, "*/\n");
4972                 FS_Print(file, builtincgshaderstring);
4973                 FS_Close(file);
4974                 Con_Printf("cg/default.cg written\n");
4975         }
4976         else
4977                 Con_Printf("failed to write to cg/default.cg\n");
4978 #endif
4979
4980 #ifdef SUPPORTD3D
4981         file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
4982         if (file)
4983         {
4984                 FS_Print(file, "/* The engine may define the following macros:\n");
4985                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4986                 for (i = 0;i < SHADERMODE_COUNT;i++)
4987                         FS_Print(file, hlslshadermodeinfo[i].pretext);
4988                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4989                         FS_Print(file, shaderpermutationinfo[i].pretext);
4990                 FS_Print(file, "*/\n");
4991                 FS_Print(file, builtincgshaderstring);
4992                 FS_Close(file);
4993                 Con_Printf("hlsl/default.hlsl written\n");
4994         }
4995         else
4996                 Con_Printf("failed to write to hlsl/default.hlsl\n");
4997 #endif
4998 }
4999
5000 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
5001 {
5002         if (!second)
5003                 texturemode = GL_MODULATE;
5004         switch (vid.renderpath)
5005         {
5006         case RENDERPATH_D3D9:
5007 #ifdef SUPPORTD3D
5008                 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
5009                 R_Mesh_TexBind(GL20TU_FIRST , first );
5010                 R_Mesh_TexBind(GL20TU_SECOND, second);
5011 #endif
5012                 break;
5013         case RENDERPATH_D3D10:
5014                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5015                 break;
5016         case RENDERPATH_D3D11:
5017                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5018                 break;
5019         case RENDERPATH_GL20:
5020                 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
5021                 R_Mesh_TexBind(GL20TU_FIRST , first );
5022                 R_Mesh_TexBind(GL20TU_SECOND, second);
5023                 break;
5024         case RENDERPATH_CGGL:
5025 #ifdef SUPPORTCG
5026                 CHECKCGERROR
5027                 R_SetupShader_SetPermutationCG(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
5028                 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
5029                 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
5030 #endif
5031                 break;
5032         case RENDERPATH_GL13:
5033                 R_Mesh_TexBind(0, first );
5034                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
5035                 R_Mesh_TexBind(1, second);
5036                 if (second)
5037                         R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
5038                 break;
5039         case RENDERPATH_GL11:
5040                 R_Mesh_TexBind(0, first );
5041                 break;
5042         }
5043 }
5044
5045 void R_SetupShader_DepthOrShadow(void)
5046 {
5047         switch (vid.renderpath)
5048         {
5049         case RENDERPATH_D3D9:
5050 #ifdef SUPPORTD3D
5051                 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5052 #endif
5053                 break;
5054         case RENDERPATH_D3D10:
5055                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5056                 break;
5057         case RENDERPATH_D3D11:
5058                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5059                 break;
5060         case RENDERPATH_GL20:
5061                 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5062                 break;
5063         case RENDERPATH_CGGL:
5064 #ifdef SUPPORTCG
5065                 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
5066 #endif
5067                 break;
5068         case RENDERPATH_GL13:
5069                 R_Mesh_TexBind(0, 0);
5070                 R_Mesh_TexBind(1, 0);
5071                 break;
5072         case RENDERPATH_GL11:
5073                 R_Mesh_TexBind(0, 0);
5074                 break;
5075         }
5076 }
5077
5078 void R_SetupShader_ShowDepth(void)
5079 {
5080         switch (vid.renderpath)
5081         {
5082         case RENDERPATH_D3D9:
5083 #ifdef SUPPORTHLSL
5084                 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
5085 #endif
5086                 break;
5087         case RENDERPATH_D3D10:
5088                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5089                 break;
5090         case RENDERPATH_D3D11:
5091                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5092                 break;
5093         case RENDERPATH_GL20:
5094                 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
5095                 break;
5096         case RENDERPATH_CGGL:
5097 #ifdef SUPPORTCG
5098                 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
5099 #endif
5100                 break;
5101         case RENDERPATH_GL13:
5102                 break;
5103         case RENDERPATH_GL11:
5104                 break;
5105         }
5106 }
5107
5108 extern qboolean r_shadow_usingdeferredprepass;
5109 extern cvar_t r_shadow_deferred_8bitrange;
5110 extern rtexture_t *r_shadow_attenuationgradienttexture;
5111 extern rtexture_t *r_shadow_attenuation2dtexture;
5112 extern rtexture_t *r_shadow_attenuation3dtexture;
5113 extern qboolean r_shadow_usingshadowmap2d;
5114 extern qboolean r_shadow_usingshadowmaportho;
5115 extern float r_shadow_shadowmap_texturescale[2];
5116 extern float r_shadow_shadowmap_parameters[4];
5117 extern qboolean r_shadow_shadowmapvsdct;
5118 extern qboolean r_shadow_shadowmapsampler;
5119 extern int r_shadow_shadowmappcf;
5120 extern rtexture_t *r_shadow_shadowmap2dtexture;
5121 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
5122 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
5123 extern matrix4x4_t r_shadow_shadowmapmatrix;
5124 extern int r_shadow_shadowmaplod; // changes for each light based on distance
5125 extern int r_shadow_prepass_width;
5126 extern int r_shadow_prepass_height;
5127 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
5128 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
5129 extern rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
5130 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
5131 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
5132 extern cvar_t gl_mesh_separatearrays;
5133 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
5134 {
5135         // a blendfunc allows colormod if:
5136         // a) it can never keep the destination pixel invariant, or
5137         // b) it can keep the destination pixel invariant, and still can do so if colormodded
5138         // this is to prevent unintended side effects from colormod
5139
5140         // in formulas:
5141         // IF there is a (s, sa) for which for all (d, da),
5142         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
5143         // THEN, for this (s, sa) and all (colormod, d, da):
5144         //   s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
5145         // OBVIOUSLY, this means that
5146         //   s*colormod * src(s*colormod, d, sa, da) = 0
5147         //   dst(s*colormod, d, sa, da)              = 1
5148
5149         // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
5150
5151         // main condition to leave dst color invariant:
5152         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
5153         //   src == GL_ZERO:
5154         //     s * 0 + d * dst(s, d, sa, da) == d
5155         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5156         //       => colormod is a problem for GL_SRC_COLOR only
5157         //   src == GL_ONE:
5158         //     s + d * dst(s, d, sa, da) == d
5159         //       => s == 0
5160         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5161         //       => colormod is never problematic for these
5162         //   src == GL_SRC_COLOR:
5163         //     s*s + d * dst(s, d, sa, da) == d
5164         //       => s == 0
5165         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5166         //       => colormod is never problematic for these
5167         //   src == GL_ONE_MINUS_SRC_COLOR:
5168         //     s*(1-s) + d * dst(s, d, sa, da) == d
5169         //       => s == 0 or s == 1
5170         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5171         //       => colormod is a problem for GL_SRC_COLOR only
5172         //   src == GL_DST_COLOR
5173         //     s*d + d * dst(s, d, sa, da) == d
5174         //       => s == 1
5175         //       => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5176         //       => colormod is always a problem
5177         //     or
5178         //       => s == 0
5179         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5180         //       => colormod is never problematic for these
5181         //       => BUT, we do not know s! We must assume it is problematic
5182         //       then... except in GL_ONE case, where we know all invariant
5183         //       cases are fine
5184         //   src == GL_ONE_MINUS_DST_COLOR
5185         //     s*(1-d) + d * dst(s, d, sa, da) == d
5186         //       => s == 0 (1-d is impossible to handle for our desired result)
5187         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5188         //       => colormod is never problematic for these
5189         //   src == GL_SRC_ALPHA
5190         //     s*sa + d * dst(s, d, sa, da) == d
5191         //       => s == 0, or sa == 0
5192         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5193         //       => colormod breaks in the case GL_SRC_COLOR only
5194         //   src == GL_ONE_MINUS_SRC_ALPHA
5195         //     s*(1-sa) + d * dst(s, d, sa, da) == d
5196         //       => s == 0, or sa == 1
5197         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5198         //       => colormod breaks in the case GL_SRC_COLOR only
5199         //   src == GL_DST_ALPHA
5200         //     s*da + d * dst(s, d, sa, da) == d
5201         //       => s == 0
5202         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
5203         //       => colormod is never problematic for these
5204
5205         switch(src)
5206         {
5207                 case GL_ZERO:
5208                 case GL_ONE_MINUS_SRC_COLOR:
5209                 case GL_SRC_ALPHA:
5210                 case GL_ONE_MINUS_SRC_ALPHA:
5211                         if(dst == GL_SRC_COLOR)
5212                                 return false;
5213                         return true;
5214                 case GL_ONE:
5215                 case GL_SRC_COLOR:
5216                 case GL_ONE_MINUS_DST_COLOR:
5217                 case GL_DST_ALPHA:
5218                 case GL_ONE_MINUS_DST_ALPHA:
5219                         return true;
5220                 case GL_DST_COLOR:
5221                         if(dst == GL_ONE)
5222                                 return true;
5223                         return false;
5224                 default:
5225                         return false;
5226         }
5227 }
5228 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
5229 {
5230         // select a permutation of the lighting shader appropriate to this
5231         // combination of texture, entity, light source, and fogging, only use the
5232         // minimum features necessary to avoid wasting rendering time in the
5233         // fragment shader on features that are not being used
5234         unsigned int permutation = 0;
5235         unsigned int mode = 0;
5236         qboolean allow_colormod;
5237         static float dummy_colormod[3] = {1, 1, 1};
5238         float *colormod = rsurface.colormod;
5239         float m16f[16];
5240         r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
5241         if (rsurfacepass == RSURFPASS_BACKGROUND)
5242         {
5243                 // distorted background
5244                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
5245                 {
5246                         mode = SHADERMODE_WATER;
5247                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5248                         allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5249                 }
5250                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
5251                 {
5252                         mode = SHADERMODE_REFRACTION;
5253                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5254                         allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5255                 }
5256                 else
5257                 {
5258                         mode = SHADERMODE_GENERIC;
5259                         permutation |= SHADERPERMUTATION_DIFFUSE;
5260                         GL_BlendFunc(GL_ONE, GL_ZERO);
5261                         allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
5262                 }
5263                 GL_AlphaTest(false);
5264         }
5265         else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
5266         {
5267                 if (r_glsl_offsetmapping.integer)
5268                 {
5269                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5270                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5271                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5272                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5273                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5274                         {
5275                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5276                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5277                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5278                         }
5279                 }
5280                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5281                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5282                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5283                         permutation |= SHADERPERMUTATION_ALPHAKILL;
5284                 // normalmap (deferred prepass), may use alpha test on diffuse
5285                 mode = SHADERMODE_DEFERREDGEOMETRY;
5286                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5287                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5288                 GL_AlphaTest(false);
5289                 GL_BlendFunc(GL_ONE, GL_ZERO);
5290                 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
5291         }
5292         else if (rsurfacepass == RSURFPASS_RTLIGHT)
5293         {
5294                 if (r_glsl_offsetmapping.integer)
5295                 {
5296                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5297                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5298                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5299                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5300                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5301                         {
5302                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5303                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5304                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5305                         }
5306                 }
5307                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5308                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5309                 // light source
5310                 mode = SHADERMODE_LIGHTSOURCE;
5311                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5312                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5313                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
5314                         permutation |= SHADERPERMUTATION_CUBEFILTER;
5315                 if (diffusescale > 0)
5316                         permutation |= SHADERPERMUTATION_DIFFUSE;
5317                 if (specularscale > 0)
5318                 {
5319                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5320                         if (r_shadow_glossexact.integer)
5321                                 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5322                 }
5323                 if (r_refdef.fogenabled)
5324                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5325                 if (rsurface.texture->colormapping)
5326                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5327                 if (r_shadow_usingshadowmap2d)
5328                 {
5329                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5330                         if(r_shadow_shadowmapvsdct)
5331                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5332
5333                         if (r_shadow_shadowmapsampler)
5334                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5335                         if (r_shadow_shadowmappcf > 1)
5336                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5337                         else if (r_shadow_shadowmappcf)
5338                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5339                 }
5340                 if (rsurface.texture->reflectmasktexture)
5341                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5342                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5343                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
5344                 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
5345         }
5346         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5347         {
5348                 if (r_glsl_offsetmapping.integer)
5349                 {
5350                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5351                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5352                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5353                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5354                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5355                         {
5356                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5357                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5358                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5359                         }
5360                 }
5361                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5362                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5363                 // unshaded geometry (fullbright or ambient model lighting)
5364                 mode = SHADERMODE_FLATCOLOR;
5365                 ambientscale = diffusescale = specularscale = 0;
5366                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5367                         permutation |= SHADERPERMUTATION_GLOW;
5368                 if (r_refdef.fogenabled)
5369                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5370                 if (rsurface.texture->colormapping)
5371                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5372                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5373                 {
5374                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5375                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5376
5377                         if (r_shadow_shadowmapsampler)
5378                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5379                         if (r_shadow_shadowmappcf > 1)
5380                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5381                         else if (r_shadow_shadowmappcf)
5382                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5383                 }
5384                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5385                         permutation |= SHADERPERMUTATION_REFLECTION;
5386                 if (rsurface.texture->reflectmasktexture)
5387                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5388                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5389                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5390                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5391         }
5392         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
5393         {
5394                 if (r_glsl_offsetmapping.integer)
5395                 {
5396                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5397                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5398                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5399                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5400                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5401                         {
5402                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5403                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5404                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5405                         }
5406                 }
5407                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5408                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5409                 // directional model lighting
5410                 mode = SHADERMODE_LIGHTDIRECTION;
5411                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5412                         permutation |= SHADERPERMUTATION_GLOW;
5413                 permutation |= SHADERPERMUTATION_DIFFUSE;
5414                 if (specularscale > 0)
5415                 {
5416                         permutation |= SHADERPERMUTATION_SPECULAR;
5417                         if (r_shadow_glossexact.integer)
5418                                 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5419                 }
5420                 if (r_refdef.fogenabled)
5421                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5422                 if (rsurface.texture->colormapping)
5423                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5424                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5425                 {
5426                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5427                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5428
5429                         if (r_shadow_shadowmapsampler)
5430                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5431                         if (r_shadow_shadowmappcf > 1)
5432                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5433                         else if (r_shadow_shadowmappcf)
5434                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5435                 }
5436                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5437                         permutation |= SHADERPERMUTATION_REFLECTION;
5438                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5439                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5440                 if (rsurface.texture->reflectmasktexture)
5441                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5442                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5443                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5444                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5445         }
5446         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5447         {
5448                 if (r_glsl_offsetmapping.integer)
5449                 {
5450                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5451                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5452                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5453                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5454                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5455                         {
5456                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5457                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5458                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5459                         }
5460                 }
5461                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5462                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5463                 // ambient model lighting
5464                 mode = SHADERMODE_LIGHTDIRECTION;
5465                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5466                         permutation |= SHADERPERMUTATION_GLOW;
5467                 if (r_refdef.fogenabled)
5468                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5469                 if (rsurface.texture->colormapping)
5470                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5471                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5472                 {
5473                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5474                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5475
5476                         if (r_shadow_shadowmapsampler)
5477                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5478                         if (r_shadow_shadowmappcf > 1)
5479                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5480                         else if (r_shadow_shadowmappcf)
5481                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5482                 }
5483                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5484                         permutation |= SHADERPERMUTATION_REFLECTION;
5485                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5486                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5487                 if (rsurface.texture->reflectmasktexture)
5488                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5489                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5490                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5491                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5492         }
5493         else
5494         {
5495                 if (r_glsl_offsetmapping.integer)
5496                 {
5497                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5498                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5499                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5500                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5501                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5502                         {
5503                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5504                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5505                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5506                         }
5507                 }
5508                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5509                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5510                 // lightmapped wall
5511                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5512                         permutation |= SHADERPERMUTATION_GLOW;
5513                 if (r_refdef.fogenabled)
5514                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5515                 if (rsurface.texture->colormapping)
5516                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5517                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5518                 {
5519                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5520                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5521
5522                         if (r_shadow_shadowmapsampler)
5523                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5524                         if (r_shadow_shadowmappcf > 1)
5525                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5526                         else if (r_shadow_shadowmappcf)
5527                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5528                 }
5529                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5530                         permutation |= SHADERPERMUTATION_REFLECTION;
5531                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5532                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5533                 if (rsurface.texture->reflectmasktexture)
5534                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5535                 if (FAKELIGHT_ENABLED)
5536                 {
5537                         // fake lightmapping (q1bsp, q3bsp, fullbright map)
5538                         mode = SHADERMODE_FAKELIGHT;
5539                         permutation |= SHADERPERMUTATION_DIFFUSE;
5540                         if (specularscale > 0)
5541                         {
5542                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5543                                 if (r_shadow_glossexact.integer)
5544                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5545                         }
5546                 }
5547                 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5548                 {
5549                         // deluxemapping (light direction texture)
5550                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5551                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5552                         else
5553                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5554                         permutation |= SHADERPERMUTATION_DIFFUSE;
5555                         if (specularscale > 0)
5556                         {
5557                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5558                                 if (r_shadow_glossexact.integer)
5559                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5560                         }
5561                 }
5562                 else if (r_glsl_deluxemapping.integer >= 2 && rsurface.uselightmaptexture)
5563                 {
5564                         // fake deluxemapping (uniform light direction in tangentspace)
5565                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5566                         permutation |= SHADERPERMUTATION_DIFFUSE;
5567                         if (specularscale > 0)
5568                         {
5569                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5570                                 if (r_shadow_glossexact.integer)
5571                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5572                         }
5573                 }
5574                 else if (rsurface.uselightmaptexture)
5575                 {
5576                         // ordinary lightmapping (q1bsp, q3bsp)
5577                         mode = SHADERMODE_LIGHTMAP;
5578                 }
5579                 else
5580                 {
5581                         // ordinary vertex coloring (q3bsp)
5582                         mode = SHADERMODE_VERTEXCOLOR;
5583                 }
5584                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5585                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5586                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5587         }
5588         if(!allow_colormod)
5589                 colormod = dummy_colormod;
5590         switch(vid.renderpath)
5591         {
5592         case RENDERPATH_D3D9:
5593 #ifdef SUPPORTD3D
5594                 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5595                 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5596                 R_SetupShader_SetPermutationHLSL(mode, permutation);
5597                 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
5598                 if (mode == SHADERMODE_LIGHTSOURCE)
5599                 {
5600                         Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
5601                         hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5602                 }
5603                 else
5604                 {
5605                         if (mode == SHADERMODE_LIGHTDIRECTION)                                   
5606                         {
5607                                 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5608                         }
5609                 }
5610                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
5611                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
5612                 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
5613                 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5614                 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5615
5616                 if (mode == SHADERMODE_LIGHTSOURCE)
5617                 {
5618                         hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5619                         hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5620                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5621                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5622                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5623
5624                         // additive passes are only darkened by fog, not tinted
5625                         hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5626                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5627                 }
5628                 else
5629                 {
5630                         if (mode == SHADERMODE_FLATCOLOR)
5631                         {
5632                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5633                         }
5634                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5635                         {
5636                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5637                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5638                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5639                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5640                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5641                                 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5642                                 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5643                         }
5644                         else
5645                         {
5646                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5647                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5648                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5649                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5650                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5651                         }
5652                         // additive passes are only darkened by fog, not tinted
5653                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5654                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5655                         else
5656                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5657                         hlslPSSetParameter4f(D3DPSREGISTER_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);
5658                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5659                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5660                         hlslPSSetParameter4f(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5661                         hlslPSSetParameter4f(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5662                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5663                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
5664                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5665                 }
5666                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5667                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5668                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5669                 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5670                 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5671                 if (rsurface.texture->pantstexture)
5672                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5673                 else
5674                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
5675                 if (rsurface.texture->shirttexture)
5676                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5677                 else
5678                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
5679                 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5680                 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
5681                 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
5682                 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
5683                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
5684                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5685                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5686
5687                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
5688                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
5689                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
5690                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
5691                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
5692                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
5693                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
5694                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
5695                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
5696                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
5697                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
5698                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5699                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
5700                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
5701                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5702                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5703                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
5704                 if (rsurfacepass == RSURFPASS_BACKGROUND)
5705                 {
5706                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5707                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5708                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5709                 }
5710                 else
5711                 {
5712                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5713                 }
5714 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
5715 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
5716                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
5717                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
5718                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5719                 {
5720                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
5721                         if (rsurface.rtlight)
5722                         {
5723                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
5724                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
5725                         }
5726                 }
5727 #endif
5728                 break;
5729         case RENDERPATH_D3D10:
5730                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5731                 break;
5732         case RENDERPATH_D3D11:
5733                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5734                 break;
5735         case RENDERPATH_GL20:
5736                 if (gl_mesh_separatearrays.integer)
5737                 {
5738                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5739                         R_Mesh_VertexPointer(     3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5740                         R_Mesh_ColorPointer(      4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5741                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5742                         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5743                         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5744                         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5745                         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5746                 }
5747                 else
5748                 {
5749                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5750                         R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5751                 }
5752                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5753                 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5754                 if (mode == SHADERMODE_LIGHTSOURCE)
5755                 {
5756                         if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5757                         if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5758                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5759                         if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5760                         if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5761                         if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5762         
5763                         // additive passes are only darkened by fog, not tinted
5764                         if (r_glsl_permutation->loc_FogColor >= 0)
5765                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5766                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5767                 }
5768                 else
5769                 {
5770                         if (mode == SHADERMODE_FLATCOLOR)
5771                         {
5772                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5773                         }
5774                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5775                         {
5776                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5777                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5778                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5779                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5780                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5781                                 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5782                                 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5783                         }
5784                         else
5785                         {
5786                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5787                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5788                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5789                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5790                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5791                         }
5792                         // additive passes are only darkened by fog, not tinted
5793                         if (r_glsl_permutation->loc_FogColor >= 0)
5794                         {
5795                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5796                                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5797                                 else
5798                                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5799                         }
5800                         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);
5801                         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]);
5802                         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]);
5803                         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5804                         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5805                         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5806                         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5807                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5808                 }
5809                 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5810                 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5811                 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5812                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5813                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5814
5815                 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5816                 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5817                 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5818                 if (r_glsl_permutation->loc_Color_Pants >= 0)
5819                 {
5820                         if (rsurface.texture->pantstexture)
5821                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5822                         else
5823                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5824                 }
5825                 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5826                 {
5827                         if (rsurface.texture->shirttexture)
5828                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5829                         else
5830                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5831                 }
5832                 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4fARB(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5833                 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5834                 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5835                 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5836                 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5837                 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5838                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5839
5840         //      if (r_glsl_permutation->loc_Texture_First           >= 0) R_Mesh_TexBind(GL20TU_FIRST             , r_texture_white                                     );
5841         //      if (r_glsl_permutation->loc_Texture_Second          >= 0) R_Mesh_TexBind(GL20TU_SECOND            , r_texture_white                                     );
5842         //      if (r_glsl_permutation->loc_Texture_GammaRamps      >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS        , r_texture_gammaramps                                );
5843                 if (r_glsl_permutation->loc_Texture_Normal          >= 0) R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
5844                 if (r_glsl_permutation->loc_Texture_Color           >= 0) R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
5845                 if (r_glsl_permutation->loc_Texture_Gloss           >= 0) R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
5846                 if (r_glsl_permutation->loc_Texture_Glow            >= 0) R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
5847                 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
5848                 if (r_glsl_permutation->loc_Texture_SecondaryColor  >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
5849                 if (r_glsl_permutation->loc_Texture_SecondaryGloss  >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
5850                 if (r_glsl_permutation->loc_Texture_SecondaryGlow   >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
5851                 if (r_glsl_permutation->loc_Texture_Pants           >= 0) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
5852                 if (r_glsl_permutation->loc_Texture_Shirt           >= 0) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
5853                 if (r_glsl_permutation->loc_Texture_ReflectMask     >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
5854                 if (r_glsl_permutation->loc_Texture_ReflectCube     >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5855                 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
5856                 if (r_glsl_permutation->loc_Texture_FogMask         >= 0) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
5857                 if (r_glsl_permutation->loc_Texture_Lightmap        >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5858                 if (r_glsl_permutation->loc_Texture_Deluxemap       >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5859                 if (r_glsl_permutation->loc_Texture_Attenuation     >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
5860                 if (rsurfacepass == RSURFPASS_BACKGROUND)
5861                 {
5862                         if(r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5863                         else if(r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5864                         if(r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5865                 }
5866                 else
5867                 {
5868                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5869                 }
5870 //              if (r_glsl_permutation->loc_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
5871 //              if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
5872                 if (r_glsl_permutation->loc_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
5873                 if (r_glsl_permutation->loc_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
5874                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5875                 {
5876                         if (r_glsl_permutation->loc_Texture_ShadowMap2D     >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture                         );
5877                         if (rsurface.rtlight)
5878                         {
5879                                 if (r_glsl_permutation->loc_Texture_Cube            >= 0) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
5880                                 if (r_glsl_permutation->loc_Texture_CubeProjection  >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
5881                         }
5882                 }
5883                 CHECKGLERROR
5884                 break;
5885         case RENDERPATH_CGGL:
5886 #ifdef SUPPORTCG
5887                 if (gl_mesh_separatearrays.integer)
5888                 {
5889                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5890                         R_Mesh_VertexPointer(     3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5891                         R_Mesh_ColorPointer(      4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5892                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5893                         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5894                         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5895                         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5896                         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5897                 }
5898                 else
5899                 {
5900                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5901                         R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5902                 }
5903                 R_SetupShader_SetPermutationCG(mode, permutation);
5904                 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5905                 if (mode == SHADERMODE_LIGHTSOURCE)
5906                 {
5907                         if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5908                         if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5909                 }
5910                 else
5911                 {
5912                         if (mode == SHADERMODE_LIGHTDIRECTION)
5913                         {
5914                                 if (r_cg_permutation->vp_LightDir) cgGLSetParameter3f(r_cg_permutation->vp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5915                         }
5916                 }
5917                 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5918                 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5919                 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5920                 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5921                 if (r_cg_permutation->vp_FogPlane) cgGLSetParameter4f(r_cg_permutation->vp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5922                 CHECKGLERROR
5923
5924                 if (mode == SHADERMODE_LIGHTSOURCE)
5925                 {
5926                         if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5927                         if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5928                         if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);CHECKCGERROR
5929                         if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);CHECKCGERROR
5930                         if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);CHECKCGERROR
5931
5932                         // additive passes are only darkened by fog, not tinted
5933                         if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5934                         if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5935                 }
5936                 else
5937                 {
5938                         if (mode == SHADERMODE_FLATCOLOR)
5939                         {
5940                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0], colormod[1], colormod[2]);CHECKCGERROR
5941                         }
5942                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5943                         {
5944                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);CHECKCGERROR
5945                                 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);CHECKCGERROR
5946                                 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5947                                 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5948                                 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5949                                 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);CHECKCGERROR
5950                                 if (r_cg_permutation->fp_LightDir) cgGLSetParameter3f(r_cg_permutation->fp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5951                         }
5952                         else
5953                         {
5954                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);CHECKCGERROR
5955                                 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);CHECKCGERROR
5956                                 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5957                                 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5958                                 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5959                         }
5960                         // additive passes are only darkened by fog, not tinted
5961                         if (r_cg_permutation->fp_FogColor)
5962                         {
5963                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5964                                         cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5965                                 else
5966                                         cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5967                                 CHECKCGERROR
5968                         }
5969                         if (r_cg_permutation->fp_DistortScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_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);CHECKCGERROR
5970                         if (r_cg_permutation->fp_ScreenScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);CHECKCGERROR
5971                         if (r_cg_permutation->fp_ScreenCenterRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);CHECKCGERROR
5972                         if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5973                         if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5974                         if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5975                         if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5976                         if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5977                 }
5978                 if (r_cg_permutation->fp_ShadowMap_TextureScale) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5979                 if (r_cg_permutation->fp_ShadowMap_Parameters) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5980                 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5981                 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));CHECKCGERROR
5982                 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5983                 if (r_cg_permutation->fp_Color_Pants)
5984                 {
5985                         if (rsurface.texture->pantstexture)
5986                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5987                         else
5988                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5989                         CHECKCGERROR
5990                 }
5991                 if (r_cg_permutation->fp_Color_Shirt)
5992                 {
5993                         if (rsurface.texture->shirttexture)
5994                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5995                         else
5996                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5997                         CHECKCGERROR
5998                 }
5999                 if (r_cg_permutation->fp_FogPlane) cgGLSetParameter4f(r_cg_permutation->fp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
6000                 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
6001                 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
6002                 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
6003                 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
6004                 if (r_cg_permutation->fp_ScreenToDepth) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
6005                 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
6006
6007         //      if (r_cg_permutation->fp_Texture_First          ) CG_BindTexture(r_cg_permutation->fp_Texture_First          , r_texture_white                                     );CHECKCGERROR
6008         //      if (r_cg_permutation->fp_Texture_Second         ) CG_BindTexture(r_cg_permutation->fp_Texture_Second         , r_texture_white                                     );CHECKCGERROR
6009         //      if (r_cg_permutation->fp_Texture_GammaRamps     ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps     , r_texture_gammaramps                                );CHECKCGERROR
6010                 if (r_cg_permutation->fp_Texture_Normal         ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal         , rsurface.texture->nmaptexture                       );CHECKCGERROR
6011                 if (r_cg_permutation->fp_Texture_Color          ) CG_BindTexture(r_cg_permutation->fp_Texture_Color          , rsurface.texture->basetexture                       );CHECKCGERROR
6012                 if (r_cg_permutation->fp_Texture_Gloss          ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss          , rsurface.texture->glosstexture                      );CHECKCGERROR
6013                 if (r_cg_permutation->fp_Texture_Glow           ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow           , rsurface.texture->glowtexture                       );CHECKCGERROR
6014                 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture             );CHECKCGERROR
6015                 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture             );CHECKCGERROR
6016                 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture            );CHECKCGERROR
6017                 if (r_cg_permutation->fp_Texture_SecondaryGlow  ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow  , rsurface.texture->backgroundglowtexture             );CHECKCGERROR
6018                 if (r_cg_permutation->fp_Texture_Pants          ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants          , rsurface.texture->pantstexture                      );CHECKCGERROR
6019                 if (r_cg_permutation->fp_Texture_Shirt          ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt          , rsurface.texture->shirttexture                      );CHECKCGERROR
6020                 if (r_cg_permutation->fp_Texture_ReflectMask    ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask    , rsurface.texture->reflectmasktexture                );CHECKCGERROR
6021                 if (r_cg_permutation->fp_Texture_ReflectCube    ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectCube    , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);CHECKCGERROR
6022                 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture                         );CHECKCGERROR
6023                 if (r_cg_permutation->fp_Texture_FogMask        ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask        , r_texture_fogattenuation                            );CHECKCGERROR
6024                 if (r_cg_permutation->fp_Texture_Lightmap       ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap       , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);CHECKCGERROR
6025                 if (r_cg_permutation->fp_Texture_Deluxemap      ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap      , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);CHECKCGERROR
6026                 if (r_cg_permutation->fp_Texture_Attenuation    ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation    , r_shadow_attenuationgradienttexture                 );CHECKCGERROR
6027                 if (rsurfacepass == RSURFPASS_BACKGROUND)
6028                 {
6029                         if (r_cg_permutation->fp_Texture_Refraction     ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction     , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);CHECKCGERROR
6030                         else if (r_cg_permutation->fp_Texture_First     ) CG_BindTexture(r_cg_permutation->fp_Texture_First          , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);CHECKCGERROR
6031                         if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
6032                 }
6033                 else
6034                 {
6035                         if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
6036                 }
6037                 if (r_cg_permutation->fp_Texture_ScreenDepth    ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth    , r_shadow_prepassgeometrydepthtexture                );CHECKCGERROR
6038                 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture            );CHECKCGERROR
6039                 if (r_cg_permutation->fp_Texture_ScreenDiffuse  ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse  , r_shadow_prepasslightingdiffusetexture              );CHECKCGERROR
6040                 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture             );CHECKCGERROR
6041                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
6042                 {
6043                         if (r_cg_permutation->fp_Texture_ShadowMap2D    ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D    , r_shadow_shadowmap2dtexture                         );CHECKCGERROR
6044                         if (rsurface.rtlight)
6045                         {
6046                                 if (r_cg_permutation->fp_Texture_Cube           ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube           , rsurface.rtlight->currentcubemap                    );CHECKCGERROR
6047                                 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture                      );CHECKCGERROR
6048                         }
6049                 }
6050
6051                 CHECKGLERROR
6052 #endif
6053                 break;
6054         case RENDERPATH_GL13:
6055         case RENDERPATH_GL11:
6056                 break;
6057         }
6058 }
6059
6060 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
6061 {
6062         // select a permutation of the lighting shader appropriate to this
6063         // combination of texture, entity, light source, and fogging, only use the
6064         // minimum features necessary to avoid wasting rendering time in the
6065         // fragment shader on features that are not being used
6066         unsigned int permutation = 0;
6067         unsigned int mode = 0;
6068         const float *lightcolorbase = rtlight->currentcolor;
6069         float ambientscale = rtlight->ambientscale;
6070         float diffusescale = rtlight->diffusescale;
6071         float specularscale = rtlight->specularscale;
6072         // this is the location of the light in view space
6073         vec3_t viewlightorigin;
6074         // this transforms from view space (camera) to light space (cubemap)
6075         matrix4x4_t viewtolight;
6076         matrix4x4_t lighttoview;
6077         float viewtolight16f[16];
6078         float range = 1.0f / r_shadow_deferred_8bitrange.value;
6079         // light source
6080         mode = SHADERMODE_DEFERREDLIGHTSOURCE;
6081         if (rtlight->currentcubemap != r_texture_whitecube)
6082                 permutation |= SHADERPERMUTATION_CUBEFILTER;
6083         if (diffusescale > 0)
6084                 permutation |= SHADERPERMUTATION_DIFFUSE;
6085         if (specularscale > 0)
6086         {
6087                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
6088                 if (r_shadow_glossexact.integer)
6089                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
6090         }
6091         if (r_shadow_usingshadowmap2d)
6092         {
6093                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
6094                 if (r_shadow_shadowmapvsdct)
6095                         permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
6096
6097                 if (r_shadow_shadowmapsampler)
6098                         permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
6099                 if (r_shadow_shadowmappcf > 1)
6100                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
6101                 else if (r_shadow_shadowmappcf)
6102                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
6103         }
6104         Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
6105         Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
6106         Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
6107         Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
6108         switch(vid.renderpath)
6109         {
6110         case RENDERPATH_D3D9:
6111 #ifdef SUPPORTD3D
6112                 R_SetupShader_SetPermutationHLSL(mode, permutation);
6113                 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6114                 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
6115                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
6116                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
6117                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
6118                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
6119                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
6120                 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
6121                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
6122                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
6123
6124                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
6125                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthcolortexture           );
6126                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
6127                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
6128                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dcolortexture                    );
6129                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
6130 #endif
6131                 break;
6132         case RENDERPATH_D3D10:
6133                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6134                 break;
6135         case RENDERPATH_D3D11:
6136                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6137                 break;
6138         case RENDERPATH_GL20:
6139                 R_SetupShader_SetPermutationGLSL(mode, permutation);
6140                 if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3fARB(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6141                 if (r_glsl_permutation->loc_ViewToLight               >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight              , 1, false, viewtolight16f);
6142                 if (r_glsl_permutation->loc_DeferredColor_Ambient     >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
6143                 if (r_glsl_permutation->loc_DeferredColor_Diffuse     >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
6144                 if (r_glsl_permutation->loc_DeferredColor_Specular    >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
6145                 if (r_glsl_permutation->loc_ShadowMap_TextureScale    >= 0) qglUniform2fARB(       r_glsl_permutation->loc_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
6146                 if (r_glsl_permutation->loc_ShadowMap_Parameters      >= 0) qglUniform4fARB(       r_glsl_permutation->loc_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
6147                 if (r_glsl_permutation->loc_SpecularPower             >= 0) qglUniform1fARB(       r_glsl_permutation->loc_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
6148                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2fARB(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
6149                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
6150
6151                 if (r_glsl_permutation->loc_Texture_Attenuation       >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
6152                 if (r_glsl_permutation->loc_Texture_ScreenDepth       >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
6153                 if (r_glsl_permutation->loc_Texture_ScreenNormalMap   >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
6154                 if (r_glsl_permutation->loc_Texture_Cube              >= 0) R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
6155                 if (r_glsl_permutation->loc_Texture_ShadowMap2D       >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dtexture                         );
6156                 if (r_glsl_permutation->loc_Texture_CubeProjection    >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
6157                 break;
6158         case RENDERPATH_CGGL:
6159 #ifdef SUPPORTCG
6160                 R_SetupShader_SetPermutationCG(mode, permutation);
6161                 if (r_cg_permutation->fp_LightPosition            ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
6162                 if (r_cg_permutation->fp_ViewToLight              ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
6163                 if (r_cg_permutation->fp_DeferredColor_Ambient    ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);CHECKCGERROR
6164                 if (r_cg_permutation->fp_DeferredColor_Diffuse    ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);CHECKCGERROR
6165                 if (r_cg_permutation->fp_DeferredColor_Specular   ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);CHECKCGERROR
6166                 if (r_cg_permutation->fp_ShadowMap_TextureScale   ) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
6167                 if (r_cg_permutation->fp_ShadowMap_Parameters     ) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
6168                 if (r_cg_permutation->fp_SpecularPower            ) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
6169                 if (r_cg_permutation->fp_ScreenToDepth            ) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
6170                 if (r_cg_permutation->fp_PixelToScreenTexCoord    ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
6171
6172                 if (r_cg_permutation->fp_Texture_Attenuation      ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation    , r_shadow_attenuationgradienttexture                 );CHECKCGERROR
6173                 if (r_cg_permutation->fp_Texture_ScreenDepth      ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth    , r_shadow_prepassgeometrydepthtexture                );CHECKCGERROR
6174                 if (r_cg_permutation->fp_Texture_ScreenNormalMap  ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture            );CHECKCGERROR
6175                 if (r_cg_permutation->fp_Texture_Cube             ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube           , rsurface.rtlight->currentcubemap                    );CHECKCGERROR
6176                 if (r_cg_permutation->fp_Texture_ShadowMap2D      ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D    , r_shadow_shadowmap2dtexture                         );CHECKCGERROR
6177                 if (r_cg_permutation->fp_Texture_CubeProjection   ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture                      );CHECKCGERROR
6178 #endif
6179                 break;
6180         case RENDERPATH_GL13:
6181         case RENDERPATH_GL11:
6182                 break;
6183         }
6184 }
6185
6186 #define SKINFRAME_HASH 1024
6187
6188 typedef struct
6189 {
6190         int loadsequence; // incremented each level change
6191         memexpandablearray_t array;
6192         skinframe_t *hash[SKINFRAME_HASH];
6193 }
6194 r_skinframe_t;
6195 r_skinframe_t r_skinframe;
6196
6197 void R_SkinFrame_PrepareForPurge(void)
6198 {
6199         r_skinframe.loadsequence++;
6200         // wrap it without hitting zero
6201         if (r_skinframe.loadsequence >= 200)
6202                 r_skinframe.loadsequence = 1;
6203 }
6204
6205 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
6206 {
6207         if (!skinframe)
6208                 return;
6209         // mark the skinframe as used for the purging code
6210         skinframe->loadsequence = r_skinframe.loadsequence;
6211 }
6212
6213 void R_SkinFrame_Purge(void)
6214 {
6215         int i;
6216         skinframe_t *s;
6217         for (i = 0;i < SKINFRAME_HASH;i++)
6218         {
6219                 for (s = r_skinframe.hash[i];s;s = s->next)
6220                 {
6221                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
6222                         {
6223                                 if (s->merged == s->base)
6224                                         s->merged = NULL;
6225                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
6226                                 R_PurgeTexture(s->stain );s->stain  = NULL;
6227                                 R_PurgeTexture(s->merged);s->merged = NULL;
6228                                 R_PurgeTexture(s->base  );s->base   = NULL;
6229                                 R_PurgeTexture(s->pants );s->pants  = NULL;
6230                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
6231                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
6232                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
6233                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
6234                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
6235                                 R_PurgeTexture(s->reflect);s->reflect = NULL;
6236                                 s->loadsequence = 0;
6237                         }
6238                 }
6239         }
6240 }
6241
6242 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
6243         skinframe_t *item;
6244         char basename[MAX_QPATH];
6245
6246         Image_StripImageExtension(name, basename, sizeof(basename));
6247
6248         if( last == NULL ) {
6249                 int hashindex;
6250                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6251                 item = r_skinframe.hash[hashindex];
6252         } else {
6253                 item = last->next;
6254         }
6255
6256         // linearly search through the hash bucket
6257         for( ; item ; item = item->next ) {
6258                 if( !strcmp( item->basename, basename ) ) {
6259                         return item;
6260                 }
6261         }
6262         return NULL;
6263 }
6264
6265 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
6266 {
6267         skinframe_t *item;
6268         int hashindex;
6269         char basename[MAX_QPATH];
6270
6271         Image_StripImageExtension(name, basename, sizeof(basename));
6272
6273         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6274         for (item = r_skinframe.hash[hashindex];item;item = item->next)
6275                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
6276                         break;
6277
6278         if (!item) {
6279                 rtexture_t *dyntexture;
6280                 // check whether its a dynamic texture
6281                 dyntexture = CL_GetDynTexture( basename );
6282                 if (!add && !dyntexture)
6283                         return NULL;
6284                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
6285                 memset(item, 0, sizeof(*item));
6286                 strlcpy(item->basename, basename, sizeof(item->basename));
6287                 item->base = dyntexture; // either NULL or dyntexture handle
6288                 item->textureflags = textureflags;
6289                 item->comparewidth = comparewidth;
6290                 item->compareheight = compareheight;
6291                 item->comparecrc = comparecrc;
6292                 item->next = r_skinframe.hash[hashindex];
6293                 r_skinframe.hash[hashindex] = item;
6294         }
6295         else if( item->base == NULL )
6296         {
6297                 rtexture_t *dyntexture;
6298                 // check whether its a dynamic texture
6299                 // 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]
6300                 dyntexture = CL_GetDynTexture( basename );
6301                 item->base = dyntexture; // either NULL or dyntexture handle
6302         }
6303
6304         R_SkinFrame_MarkUsed(item);
6305         return item;
6306 }
6307
6308 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
6309         { \
6310                 unsigned long long avgcolor[5], wsum; \
6311                 int pix, comp, w; \
6312                 avgcolor[0] = 0; \
6313                 avgcolor[1] = 0; \
6314                 avgcolor[2] = 0; \
6315                 avgcolor[3] = 0; \
6316                 avgcolor[4] = 0; \
6317                 wsum = 0; \
6318                 for(pix = 0; pix < cnt; ++pix) \
6319                 { \
6320                         w = 0; \
6321                         for(comp = 0; comp < 3; ++comp) \
6322                                 w += getpixel; \
6323                         if(w) /* ignore perfectly black pixels because that is better for model skins */ \
6324                         { \
6325                                 ++wsum; \
6326                                 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6327                                 w = getpixel; \
6328                                 for(comp = 0; comp < 3; ++comp) \
6329                                         avgcolor[comp] += getpixel * w; \
6330                                 avgcolor[3] += w; \
6331                         } \
6332                         /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6333                         avgcolor[4] += getpixel; \
6334                 } \
6335                 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
6336                         avgcolor[3] = 1; \
6337                 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
6338                 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
6339                 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
6340                 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
6341         }
6342
6343 extern cvar_t gl_picmip;
6344 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
6345 {
6346         int j;
6347         unsigned char *pixels;
6348         unsigned char *bumppixels;
6349         unsigned char *basepixels = NULL;
6350         int basepixels_width = 0;
6351         int basepixels_height = 0;
6352         skinframe_t *skinframe;
6353         rtexture_t *ddsbase = NULL;
6354         qboolean ddshasalpha = false;
6355         float ddsavgcolor[4];
6356         char basename[MAX_QPATH];
6357         int miplevel = R_PicmipForFlags(textureflags);
6358         int savemiplevel = miplevel;
6359         int mymiplevel;
6360
6361         if (cls.state == ca_dedicated)
6362                 return NULL;
6363
6364         // return an existing skinframe if already loaded
6365         // if loading of the first image fails, don't make a new skinframe as it
6366         // would cause all future lookups of this to be missing
6367         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
6368         if (skinframe && skinframe->base)
6369                 return skinframe;
6370
6371         Image_StripImageExtension(name, basename, sizeof(basename));
6372
6373         // check for DDS texture file first
6374         if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
6375         {
6376                 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
6377                 if (basepixels == NULL)
6378                         return NULL;
6379         }
6380
6381         // FIXME handle miplevel
6382
6383         if (developer_loading.integer)
6384                 Con_Printf("loading skin \"%s\"\n", name);
6385
6386         // we've got some pixels to store, so really allocate this new texture now
6387         if (!skinframe)
6388                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
6389         skinframe->stain = NULL;
6390         skinframe->merged = NULL;
6391         skinframe->base = NULL;
6392         skinframe->pants = NULL;
6393         skinframe->shirt = NULL;
6394         skinframe->nmap = NULL;
6395         skinframe->gloss = NULL;
6396         skinframe->glow = NULL;
6397         skinframe->fog = NULL;
6398         skinframe->reflect = NULL;
6399         skinframe->hasalpha = false;
6400
6401         if (ddsbase)
6402         {
6403                 skinframe->base = ddsbase;
6404                 skinframe->hasalpha = ddshasalpha;
6405                 VectorCopy(ddsavgcolor, skinframe->avgcolor);
6406                 if (r_loadfog && skinframe->hasalpha)
6407                         skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
6408                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6409         }
6410         else
6411         {
6412                 basepixels_width = image_width;
6413                 basepixels_height = image_height;
6414                 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
6415                 if (textureflags & TEXF_ALPHA)
6416                 {
6417                         for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
6418                         {
6419                                 if (basepixels[j] < 255)
6420                                 {
6421                                         skinframe->hasalpha = true;
6422                                         break;
6423                                 }
6424                         }
6425                         if (r_loadfog && skinframe->hasalpha)
6426                         {
6427                                 // has transparent pixels
6428                                 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6429                                 for (j = 0;j < image_width * image_height * 4;j += 4)
6430                                 {
6431                                         pixels[j+0] = 255;
6432                                         pixels[j+1] = 255;
6433                                         pixels[j+2] = 255;
6434                                         pixels[j+3] = basepixels[j+3];
6435                                 }
6436                                 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
6437                                 Mem_Free(pixels);
6438                         }
6439                 }
6440                 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
6441                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6442                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
6443                         R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
6444                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
6445                         R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
6446         }
6447
6448         if (r_loaddds)
6449         {
6450                 mymiplevel = savemiplevel;
6451                 if (r_loadnormalmap)
6452                         skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
6453                 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6454                 if (r_loadgloss)
6455                         skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6456                 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6457                 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6458                 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6459         }
6460
6461         // _norm is the name used by tenebrae and has been adopted as standard
6462         if (r_loadnormalmap && skinframe->nmap == NULL)
6463         {
6464                 mymiplevel = savemiplevel;
6465                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6466                 {
6467                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6468                         Mem_Free(pixels);
6469                         pixels = NULL;
6470                 }
6471                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6472                 {
6473                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6474                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
6475                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6476                         Mem_Free(pixels);
6477                         Mem_Free(bumppixels);
6478                 }
6479                 else if (r_shadow_bumpscale_basetexture.value > 0)
6480                 {
6481                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
6482                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
6483                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6484                         Mem_Free(pixels);
6485                 }
6486                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
6487                         R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
6488         }
6489
6490         // _luma is supported only for tenebrae compatibility
6491         // _glow is the preferred name
6492         mymiplevel = savemiplevel;
6493         if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow",  skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
6494         {
6495                 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6496                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
6497                         R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
6498                 Mem_Free(pixels);pixels = NULL;
6499         }
6500
6501         mymiplevel = savemiplevel;
6502         if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6503         {
6504                 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6505                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
6506                         R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
6507                 Mem_Free(pixels);
6508                 pixels = NULL;
6509         }
6510
6511         mymiplevel = savemiplevel;
6512         if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6513         {
6514                 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6515                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
6516                         R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
6517                 Mem_Free(pixels);
6518                 pixels = NULL;
6519         }
6520
6521         mymiplevel = savemiplevel;
6522         if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6523         {
6524                 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6525                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
6526                         R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
6527                 Mem_Free(pixels);
6528                 pixels = NULL;
6529         }
6530
6531         mymiplevel = savemiplevel;
6532         if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6533         {
6534                 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6535                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
6536                         R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
6537                 Mem_Free(pixels);
6538                 pixels = NULL;
6539         }
6540
6541         if (basepixels)
6542                 Mem_Free(basepixels);
6543
6544         return skinframe;
6545 }
6546
6547 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
6548 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
6549 {
6550         int i;
6551         unsigned char *temp1, *temp2;
6552         skinframe_t *skinframe;
6553
6554         if (cls.state == ca_dedicated)
6555                 return NULL;
6556
6557         // if already loaded just return it, otherwise make a new skinframe
6558         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
6559         if (skinframe && skinframe->base)
6560                 return skinframe;
6561
6562         skinframe->stain = NULL;
6563         skinframe->merged = NULL;
6564         skinframe->base = NULL;
6565         skinframe->pants = NULL;
6566         skinframe->shirt = NULL;
6567         skinframe->nmap = NULL;
6568         skinframe->gloss = NULL;
6569         skinframe->glow = NULL;
6570         skinframe->fog = NULL;
6571         skinframe->reflect = NULL;
6572         skinframe->hasalpha = false;
6573
6574         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6575         if (!skindata)
6576                 return NULL;
6577
6578         if (developer_loading.integer)
6579                 Con_Printf("loading 32bit skin \"%s\"\n", name);
6580
6581         if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
6582         {
6583                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6584                 temp2 = temp1 + width * height * 4;
6585                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6586                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
6587                 Mem_Free(temp1);
6588         }
6589         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
6590         if (textureflags & TEXF_ALPHA)
6591         {
6592                 for (i = 3;i < width * height * 4;i += 4)
6593                 {
6594                         if (skindata[i] < 255)
6595                         {
6596                                 skinframe->hasalpha = true;
6597                                 break;
6598                         }
6599                 }
6600                 if (r_loadfog && skinframe->hasalpha)
6601                 {
6602                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6603                         memcpy(fogpixels, skindata, width * height * 4);
6604                         for (i = 0;i < width * height * 4;i += 4)
6605                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6606                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
6607                         Mem_Free(fogpixels);
6608                 }
6609         }
6610
6611         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6612         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6613
6614         return skinframe;
6615 }
6616
6617 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6618 {
6619         int i;
6620         int featuresmask;
6621         skinframe_t *skinframe;
6622
6623         if (cls.state == ca_dedicated)
6624                 return NULL;
6625
6626         // if already loaded just return it, otherwise make a new skinframe
6627         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6628         if (skinframe && skinframe->base)
6629                 return skinframe;
6630
6631         skinframe->stain = NULL;
6632         skinframe->merged = NULL;
6633         skinframe->base = NULL;
6634         skinframe->pants = NULL;
6635         skinframe->shirt = NULL;
6636         skinframe->nmap = NULL;
6637         skinframe->gloss = NULL;
6638         skinframe->glow = NULL;
6639         skinframe->fog = NULL;
6640         skinframe->reflect = NULL;
6641         skinframe->hasalpha = false;
6642
6643         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6644         if (!skindata)
6645                 return NULL;
6646
6647         if (developer_loading.integer)
6648                 Con_Printf("loading quake skin \"%s\"\n", name);
6649
6650         // we actually don't upload anything until the first use, because mdl skins frequently go unused, and are almost never used in both modes (colormapped and non-colormapped)
6651         skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height);
6652         memcpy(skinframe->qpixels, skindata, width*height);
6653         skinframe->qwidth = width;
6654         skinframe->qheight = height;
6655
6656         featuresmask = 0;
6657         for (i = 0;i < width * height;i++)
6658                 featuresmask |= palette_featureflags[skindata[i]];
6659
6660         skinframe->hasalpha = false;
6661         skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6662         skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6663         skinframe->qgeneratemerged = true;
6664         skinframe->qgeneratebase = skinframe->qhascolormapping;
6665         skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6666
6667         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6668         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6669
6670         return skinframe;
6671 }
6672
6673 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6674 {
6675         int width;
6676         int height;
6677         unsigned char *skindata;
6678
6679         if (!skinframe->qpixels)
6680                 return;
6681
6682         if (!skinframe->qhascolormapping)
6683                 colormapped = false;
6684
6685         if (colormapped)
6686         {
6687                 if (!skinframe->qgeneratebase)
6688                         return;
6689         }
6690         else
6691         {
6692                 if (!skinframe->qgeneratemerged)
6693                         return;
6694         }
6695
6696         width = skinframe->qwidth;
6697         height = skinframe->qheight;
6698         skindata = skinframe->qpixels;
6699
6700         if (skinframe->qgeneratenmap)
6701         {
6702                 unsigned char *temp1, *temp2;
6703                 skinframe->qgeneratenmap = false;
6704                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6705                 temp2 = temp1 + width * height * 4;
6706                 // use either a custom palette or the quake palette
6707                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6708                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6709                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
6710                 Mem_Free(temp1);
6711         }
6712
6713         if (skinframe->qgenerateglow)
6714         {
6715                 skinframe->qgenerateglow = false;
6716                 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6717         }
6718
6719         if (colormapped)
6720         {
6721                 skinframe->qgeneratebase = false;
6722                 skinframe->base  = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
6723                 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6724                 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6725         }
6726         else
6727         {
6728                 skinframe->qgeneratemerged = false;
6729                 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
6730         }
6731
6732         if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6733         {
6734                 Mem_Free(skinframe->qpixels);
6735                 skinframe->qpixels = NULL;
6736         }
6737 }
6738
6739 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
6740 {
6741         int i;
6742         skinframe_t *skinframe;
6743
6744         if (cls.state == ca_dedicated)
6745                 return NULL;
6746
6747         // if already loaded just return it, otherwise make a new skinframe
6748         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6749         if (skinframe && skinframe->base)
6750                 return skinframe;
6751
6752         skinframe->stain = NULL;
6753         skinframe->merged = NULL;
6754         skinframe->base = NULL;
6755         skinframe->pants = NULL;
6756         skinframe->shirt = NULL;
6757         skinframe->nmap = NULL;
6758         skinframe->gloss = NULL;
6759         skinframe->glow = NULL;
6760         skinframe->fog = NULL;
6761         skinframe->reflect = NULL;
6762         skinframe->hasalpha = false;
6763
6764         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6765         if (!skindata)
6766                 return NULL;
6767
6768         if (developer_loading.integer)
6769                 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6770
6771         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6772         if (textureflags & TEXF_ALPHA)
6773         {
6774                 for (i = 0;i < width * height;i++)
6775                 {
6776                         if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6777                         {
6778                                 skinframe->hasalpha = true;
6779                                 break;
6780                         }
6781                 }
6782                 if (r_loadfog && skinframe->hasalpha)
6783                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6784         }
6785
6786         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6787         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6788
6789         return skinframe;
6790 }
6791
6792 skinframe_t *R_SkinFrame_LoadMissing(void)
6793 {
6794         skinframe_t *skinframe;
6795
6796         if (cls.state == ca_dedicated)
6797                 return NULL;
6798
6799         skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6800         skinframe->stain = NULL;
6801         skinframe->merged = NULL;
6802         skinframe->base = NULL;
6803         skinframe->pants = NULL;
6804         skinframe->shirt = NULL;
6805         skinframe->nmap = NULL;
6806         skinframe->gloss = NULL;
6807         skinframe->glow = NULL;
6808         skinframe->fog = NULL;
6809         skinframe->reflect = NULL;
6810         skinframe->hasalpha = false;
6811
6812         skinframe->avgcolor[0] = rand() / RAND_MAX;
6813         skinframe->avgcolor[1] = rand() / RAND_MAX;
6814         skinframe->avgcolor[2] = rand() / RAND_MAX;
6815         skinframe->avgcolor[3] = 1;
6816
6817         return skinframe;
6818 }
6819
6820 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6821 typedef struct suffixinfo_s
6822 {
6823         const char *suffix;
6824         qboolean flipx, flipy, flipdiagonal;
6825 }
6826 suffixinfo_t;
6827 static suffixinfo_t suffix[3][6] =
6828 {
6829         {
6830                 {"px",   false, false, false},
6831                 {"nx",   false, false, false},
6832                 {"py",   false, false, false},
6833                 {"ny",   false, false, false},
6834                 {"pz",   false, false, false},
6835                 {"nz",   false, false, false}
6836         },
6837         {
6838                 {"posx", false, false, false},
6839                 {"negx", false, false, false},
6840                 {"posy", false, false, false},
6841                 {"negy", false, false, false},
6842                 {"posz", false, false, false},
6843                 {"negz", false, false, false}
6844         },
6845         {
6846                 {"rt",    true, false,  true},
6847                 {"lf",   false,  true,  true},
6848                 {"ft",    true,  true, false},
6849                 {"bk",   false, false, false},
6850                 {"up",    true, false,  true},
6851                 {"dn",    true, false,  true}
6852         }
6853 };
6854
6855 static int componentorder[4] = {0, 1, 2, 3};
6856
6857 rtexture_t *R_LoadCubemap(const char *basename)
6858 {
6859         int i, j, cubemapsize;
6860         unsigned char *cubemappixels, *image_buffer;
6861         rtexture_t *cubemaptexture;
6862         char name[256];
6863         // must start 0 so the first loadimagepixels has no requested width/height
6864         cubemapsize = 0;
6865         cubemappixels = NULL;
6866         cubemaptexture = NULL;
6867         // keep trying different suffix groups (posx, px, rt) until one loads
6868         for (j = 0;j < 3 && !cubemappixels;j++)
6869         {
6870                 // load the 6 images in the suffix group
6871                 for (i = 0;i < 6;i++)
6872                 {
6873                         // generate an image name based on the base and and suffix
6874                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6875                         // load it
6876                         if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6877                         {
6878                                 // an image loaded, make sure width and height are equal
6879                                 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6880                                 {
6881                                         // if this is the first image to load successfully, allocate the cubemap memory
6882                                         if (!cubemappixels && image_width >= 1)
6883                                         {
6884                                                 cubemapsize = image_width;
6885                                                 // note this clears to black, so unavailable sides are black
6886                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6887                                         }
6888                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6889                                         if (cubemappixels)
6890                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
6891                                 }
6892                                 else
6893                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6894                                 // free the image
6895                                 Mem_Free(image_buffer);
6896                         }
6897                 }
6898         }
6899         // if a cubemap loaded, upload it
6900         if (cubemappixels)
6901         {
6902                 if (developer_loading.integer)
6903                         Con_Printf("loading cubemap \"%s\"\n", basename);
6904
6905                 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6906                 Mem_Free(cubemappixels);
6907         }
6908         else
6909         {
6910                 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6911                 if (developer_loading.integer)
6912                 {
6913                         Con_Printf("(tried tried images ");
6914                         for (j = 0;j < 3;j++)
6915                                 for (i = 0;i < 6;i++)
6916                                         Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6917                         Con_Print(" and was unable to find any of them).\n");
6918                 }
6919         }
6920         return cubemaptexture;
6921 }
6922
6923 rtexture_t *R_GetCubemap(const char *basename)
6924 {
6925         int i;
6926         for (i = 0;i < r_texture_numcubemaps;i++)
6927                 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6928                         return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6929         if (i >= MAX_CUBEMAPS)
6930                 return r_texture_whitecube;
6931         r_texture_numcubemaps++;
6932         strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6933         r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6934         return r_texture_cubemaps[i].texture;
6935 }
6936
6937 void R_FreeCubemaps(void)
6938 {
6939         int i;
6940         for (i = 0;i < r_texture_numcubemaps;i++)
6941         {
6942                 if (developer_loading.integer)
6943                         Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6944                 if (r_texture_cubemaps[i].texture)
6945                         R_FreeTexture(r_texture_cubemaps[i].texture);
6946         }
6947         r_texture_numcubemaps = 0;
6948 }
6949
6950 void R_Main_FreeViewCache(void)
6951 {
6952         if (r_refdef.viewcache.entityvisible)
6953                 Mem_Free(r_refdef.viewcache.entityvisible);
6954         if (r_refdef.viewcache.world_pvsbits)
6955                 Mem_Free(r_refdef.viewcache.world_pvsbits);
6956         if (r_refdef.viewcache.world_leafvisible)
6957                 Mem_Free(r_refdef.viewcache.world_leafvisible);
6958         if (r_refdef.viewcache.world_surfacevisible)
6959                 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6960         memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6961 }
6962
6963 void R_Main_ResizeViewCache(void)
6964 {
6965         int numentities = r_refdef.scene.numentities;
6966         int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6967         int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6968         int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6969         int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6970         if (r_refdef.viewcache.maxentities < numentities)
6971         {
6972                 r_refdef.viewcache.maxentities = numentities;
6973                 if (r_refdef.viewcache.entityvisible)
6974                         Mem_Free(r_refdef.viewcache.entityvisible);
6975                 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6976         }
6977         if (r_refdef.viewcache.world_numclusters != numclusters)
6978         {
6979                 r_refdef.viewcache.world_numclusters = numclusters;
6980                 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6981                 if (r_refdef.viewcache.world_pvsbits)
6982                         Mem_Free(r_refdef.viewcache.world_pvsbits);
6983                 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6984         }
6985         if (r_refdef.viewcache.world_numleafs != numleafs)
6986         {
6987                 r_refdef.viewcache.world_numleafs = numleafs;
6988                 if (r_refdef.viewcache.world_leafvisible)
6989                         Mem_Free(r_refdef.viewcache.world_leafvisible);
6990                 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6991         }
6992         if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6993         {
6994                 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6995                 if (r_refdef.viewcache.world_surfacevisible)
6996                         Mem_Free(r_refdef.viewcache.world_surfacevisible);
6997                 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6998         }
6999 }
7000
7001 extern rtexture_t *loadingscreentexture;
7002 void gl_main_start(void)
7003 {
7004         loadingscreentexture = NULL;
7005         r_texture_blanknormalmap = NULL;
7006         r_texture_white = NULL;
7007         r_texture_grey128 = NULL;
7008         r_texture_black = NULL;
7009         r_texture_whitecube = NULL;
7010         r_texture_normalizationcube = NULL;
7011         r_texture_fogattenuation = NULL;
7012         r_texture_fogheighttexture = NULL;
7013         r_texture_gammaramps = NULL;
7014         r_texture_numcubemaps = 0;
7015
7016         r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
7017         r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
7018
7019         switch(vid.renderpath)
7020         {
7021         case RENDERPATH_GL20:
7022         case RENDERPATH_CGGL:
7023         case RENDERPATH_D3D9:
7024         case RENDERPATH_D3D10:
7025         case RENDERPATH_D3D11:
7026                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7027                 Cvar_SetValueQuick(&gl_combine, 1);
7028                 Cvar_SetValueQuick(&r_glsl, 1);
7029                 r_loadnormalmap = true;
7030                 r_loadgloss = true;
7031                 r_loadfog = false;
7032                 break;
7033         case RENDERPATH_GL13:
7034                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7035                 Cvar_SetValueQuick(&gl_combine, 1);
7036                 Cvar_SetValueQuick(&r_glsl, 0);
7037                 r_loadnormalmap = false;
7038                 r_loadgloss = false;
7039                 r_loadfog = true;
7040                 break;
7041         case RENDERPATH_GL11:
7042                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7043                 Cvar_SetValueQuick(&gl_combine, 0);
7044                 Cvar_SetValueQuick(&r_glsl, 0);
7045                 r_loadnormalmap = false;
7046                 r_loadgloss = false;
7047                 r_loadfog = true;
7048                 break;
7049         }
7050
7051         R_AnimCache_Free();
7052         R_FrameData_Reset();
7053
7054         r_numqueries = 0;
7055         r_maxqueries = 0;
7056         memset(r_queries, 0, sizeof(r_queries));
7057
7058         r_qwskincache = NULL;
7059         r_qwskincache_size = 0;
7060
7061         // set up r_skinframe loading system for textures
7062         memset(&r_skinframe, 0, sizeof(r_skinframe));
7063         r_skinframe.loadsequence = 1;
7064         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
7065
7066         r_main_texturepool = R_AllocTexturePool();
7067         R_BuildBlankTextures();
7068         R_BuildNoTexture();
7069         if (vid.support.arb_texture_cube_map)
7070         {
7071                 R_BuildWhiteCube();
7072                 R_BuildNormalizationCube();
7073         }
7074         r_texture_fogattenuation = NULL;
7075         r_texture_fogheighttexture = NULL;
7076         r_texture_gammaramps = NULL;
7077         //r_texture_fogintensity = NULL;
7078         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
7079         memset(&r_waterstate, 0, sizeof(r_waterstate));
7080         r_glsl_permutation = NULL;
7081         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
7082         Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
7083         glslshaderstring = NULL;
7084 #ifdef SUPPORTCG
7085         r_cg_permutation = NULL;
7086         memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
7087         Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
7088         cgshaderstring = NULL;
7089 #endif
7090 #ifdef SUPPORTD3D
7091         r_hlsl_permutation = NULL;
7092         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
7093         Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
7094         hlslshaderstring = NULL;
7095 #endif
7096         memset(&r_svbsp, 0, sizeof (r_svbsp));
7097
7098         r_refdef.fogmasktable_density = 0;
7099 }
7100
7101 void gl_main_shutdown(void)
7102 {
7103         R_AnimCache_Free();
7104         R_FrameData_Reset();
7105
7106         R_Main_FreeViewCache();
7107
7108         switch(vid.renderpath)
7109         {
7110         case RENDERPATH_GL11:
7111         case RENDERPATH_GL13:
7112         case RENDERPATH_GL20:
7113         case RENDERPATH_CGGL:
7114                 if (r_maxqueries)
7115                         qglDeleteQueriesARB(r_maxqueries, r_queries);
7116                 break;
7117         case RENDERPATH_D3D9:
7118                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7119                 break;
7120         case RENDERPATH_D3D10:
7121                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7122                 break;
7123         case RENDERPATH_D3D11:
7124                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7125                 break;
7126         }
7127
7128         r_numqueries = 0;
7129         r_maxqueries = 0;
7130         memset(r_queries, 0, sizeof(r_queries));
7131
7132         r_qwskincache = NULL;
7133         r_qwskincache_size = 0;
7134
7135         // clear out the r_skinframe state
7136         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
7137         memset(&r_skinframe, 0, sizeof(r_skinframe));
7138
7139         if (r_svbsp.nodes)
7140                 Mem_Free(r_svbsp.nodes);
7141         memset(&r_svbsp, 0, sizeof (r_svbsp));
7142         R_FreeTexturePool(&r_main_texturepool);
7143         loadingscreentexture = NULL;
7144         r_texture_blanknormalmap = NULL;
7145         r_texture_white = NULL;
7146         r_texture_grey128 = NULL;
7147         r_texture_black = NULL;
7148         r_texture_whitecube = NULL;
7149         r_texture_normalizationcube = NULL;
7150         r_texture_fogattenuation = NULL;
7151         r_texture_fogheighttexture = NULL;
7152         r_texture_gammaramps = NULL;
7153         r_texture_numcubemaps = 0;
7154         //r_texture_fogintensity = NULL;
7155         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
7156         memset(&r_waterstate, 0, sizeof(r_waterstate));
7157         R_GLSL_Restart_f();
7158 }
7159
7160 extern void CL_ParseEntityLump(char *entitystring);
7161 void gl_main_newmap(void)
7162 {
7163         // FIXME: move this code to client
7164         char *entities, entname[MAX_QPATH];
7165         if (r_qwskincache)
7166                 Mem_Free(r_qwskincache);
7167         r_qwskincache = NULL;
7168         r_qwskincache_size = 0;
7169         if (cl.worldmodel)
7170         {
7171                 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
7172                 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
7173                 {
7174                         CL_ParseEntityLump(entities);
7175                         Mem_Free(entities);
7176                         return;
7177                 }
7178                 if (cl.worldmodel->brush.entities)
7179                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
7180         }
7181         R_Main_FreeViewCache();
7182
7183         R_FrameData_Reset();
7184 }
7185
7186 void GL_Main_Init(void)
7187 {
7188         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
7189
7190         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
7191         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
7192         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
7193         if (gamemode == GAME_NEHAHRA)
7194         {
7195                 Cvar_RegisterVariable (&gl_fogenable);
7196                 Cvar_RegisterVariable (&gl_fogdensity);
7197                 Cvar_RegisterVariable (&gl_fogred);
7198                 Cvar_RegisterVariable (&gl_foggreen);
7199                 Cvar_RegisterVariable (&gl_fogblue);
7200                 Cvar_RegisterVariable (&gl_fogstart);
7201                 Cvar_RegisterVariable (&gl_fogend);
7202                 Cvar_RegisterVariable (&gl_skyclip);
7203         }
7204         Cvar_RegisterVariable(&r_motionblur);
7205         Cvar_RegisterVariable(&r_motionblur_maxblur);
7206         Cvar_RegisterVariable(&r_motionblur_bmin);
7207         Cvar_RegisterVariable(&r_motionblur_vmin);
7208         Cvar_RegisterVariable(&r_motionblur_vmax);
7209         Cvar_RegisterVariable(&r_motionblur_vcoeff);
7210         Cvar_RegisterVariable(&r_motionblur_randomize);
7211         Cvar_RegisterVariable(&r_damageblur);
7212         Cvar_RegisterVariable(&r_equalize_entities_fullbright);
7213         Cvar_RegisterVariable(&r_equalize_entities_minambient);
7214         Cvar_RegisterVariable(&r_equalize_entities_by);
7215         Cvar_RegisterVariable(&r_equalize_entities_to);
7216         Cvar_RegisterVariable(&r_depthfirst);
7217         Cvar_RegisterVariable(&r_useinfinitefarclip);
7218         Cvar_RegisterVariable(&r_farclip_base);
7219         Cvar_RegisterVariable(&r_farclip_world);
7220         Cvar_RegisterVariable(&r_nearclip);
7221         Cvar_RegisterVariable(&r_showbboxes);
7222         Cvar_RegisterVariable(&r_showsurfaces);
7223         Cvar_RegisterVariable(&r_showtris);
7224         Cvar_RegisterVariable(&r_shownormals);
7225         Cvar_RegisterVariable(&r_showlighting);
7226         Cvar_RegisterVariable(&r_showshadowvolumes);
7227         Cvar_RegisterVariable(&r_showcollisionbrushes);
7228         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
7229         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
7230         Cvar_RegisterVariable(&r_showdisabledepthtest);
7231         Cvar_RegisterVariable(&r_drawportals);
7232         Cvar_RegisterVariable(&r_drawentities);
7233         Cvar_RegisterVariable(&r_draw2d);
7234         Cvar_RegisterVariable(&r_drawworld);
7235         Cvar_RegisterVariable(&r_cullentities_trace);
7236         Cvar_RegisterVariable(&r_cullentities_trace_samples);
7237         Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
7238         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
7239         Cvar_RegisterVariable(&r_cullentities_trace_delay);
7240         Cvar_RegisterVariable(&r_drawviewmodel);
7241         Cvar_RegisterVariable(&r_drawexteriormodel);
7242         Cvar_RegisterVariable(&r_speeds);
7243         Cvar_RegisterVariable(&r_fullbrights);
7244         Cvar_RegisterVariable(&r_wateralpha);
7245         Cvar_RegisterVariable(&r_dynamic);
7246         Cvar_RegisterVariable(&r_fakelight);
7247         Cvar_RegisterVariable(&r_fakelight_intensity);
7248         Cvar_RegisterVariable(&r_fullbright);
7249         Cvar_RegisterVariable(&r_shadows);
7250         Cvar_RegisterVariable(&r_shadows_darken);
7251         Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
7252         Cvar_RegisterVariable(&r_shadows_castfrombmodels);
7253         Cvar_RegisterVariable(&r_shadows_throwdistance);
7254         Cvar_RegisterVariable(&r_shadows_throwdirection);
7255         Cvar_RegisterVariable(&r_shadows_focus);
7256         Cvar_RegisterVariable(&r_shadows_shadowmapscale);
7257         Cvar_RegisterVariable(&r_q1bsp_skymasking);
7258         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
7259         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
7260         Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
7261         Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
7262         Cvar_RegisterVariable(&r_fog_exp2);
7263         Cvar_RegisterVariable(&r_drawfog);
7264         Cvar_RegisterVariable(&r_transparentdepthmasking);
7265         Cvar_RegisterVariable(&r_texture_dds_load);
7266         Cvar_RegisterVariable(&r_texture_dds_save);
7267         Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
7268         Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
7269         Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
7270         Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
7271         Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
7272         Cvar_RegisterVariable(&r_textureunits);
7273         Cvar_RegisterVariable(&gl_combine);
7274         Cvar_RegisterVariable(&r_glsl);
7275         Cvar_RegisterVariable(&r_glsl_deluxemapping);
7276         Cvar_RegisterVariable(&r_glsl_offsetmapping);
7277         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
7278         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
7279         Cvar_RegisterVariable(&r_glsl_postprocess);
7280         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
7281         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
7282         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
7283         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
7284         Cvar_RegisterVariable(&r_water);
7285         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
7286         Cvar_RegisterVariable(&r_water_clippingplanebias);
7287         Cvar_RegisterVariable(&r_water_refractdistort);
7288         Cvar_RegisterVariable(&r_water_reflectdistort);
7289         Cvar_RegisterVariable(&r_water_scissormode);
7290         Cvar_RegisterVariable(&r_lerpsprites);
7291         Cvar_RegisterVariable(&r_lerpmodels);
7292         Cvar_RegisterVariable(&r_lerplightstyles);
7293         Cvar_RegisterVariable(&r_waterscroll);
7294         Cvar_RegisterVariable(&r_bloom);
7295         Cvar_RegisterVariable(&r_bloom_colorscale);
7296         Cvar_RegisterVariable(&r_bloom_brighten);
7297         Cvar_RegisterVariable(&r_bloom_blur);
7298         Cvar_RegisterVariable(&r_bloom_resolution);
7299         Cvar_RegisterVariable(&r_bloom_colorexponent);
7300         Cvar_RegisterVariable(&r_bloom_colorsubtract);
7301         Cvar_RegisterVariable(&r_hdr);
7302         Cvar_RegisterVariable(&r_hdr_scenebrightness);
7303         Cvar_RegisterVariable(&r_hdr_glowintensity);
7304         Cvar_RegisterVariable(&r_hdr_range);
7305         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
7306         Cvar_RegisterVariable(&developer_texturelogging);
7307         Cvar_RegisterVariable(&gl_lightmaps);
7308         Cvar_RegisterVariable(&r_test);
7309         Cvar_RegisterVariable(&r_glsl_saturation);
7310         Cvar_RegisterVariable(&r_framedatasize);
7311         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
7312                 Cvar_SetValue("r_fullbrights", 0);
7313         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
7314
7315         Cvar_RegisterVariable(&r_track_sprites);
7316         Cvar_RegisterVariable(&r_track_sprites_flags);
7317         Cvar_RegisterVariable(&r_track_sprites_scalew);
7318         Cvar_RegisterVariable(&r_track_sprites_scaleh);
7319         Cvar_RegisterVariable(&r_overheadsprites_perspective);
7320         Cvar_RegisterVariable(&r_overheadsprites_pushback);
7321 }
7322
7323 extern void R_Textures_Init(void);
7324 extern void GL_Draw_Init(void);
7325 extern void GL_Main_Init(void);
7326 extern void R_Shadow_Init(void);
7327 extern void R_Sky_Init(void);
7328 extern void GL_Surf_Init(void);
7329 extern void R_Particles_Init(void);
7330 extern void R_Explosion_Init(void);
7331 extern void gl_backend_init(void);
7332 extern void Sbar_Init(void);
7333 extern void R_LightningBeams_Init(void);
7334 extern void Mod_RenderInit(void);
7335 extern void Font_Init(void);
7336
7337 void Render_Init(void)
7338 {
7339         gl_backend_init();
7340         R_Textures_Init();
7341         GL_Main_Init();
7342         Font_Init();
7343         GL_Draw_Init();
7344         R_Shadow_Init();
7345         R_Sky_Init();
7346         GL_Surf_Init();
7347         Sbar_Init();
7348         R_Particles_Init();
7349         R_Explosion_Init();
7350         R_LightningBeams_Init();
7351         Mod_RenderInit();
7352 }
7353
7354 /*
7355 ===============
7356 GL_Init
7357 ===============
7358 */
7359 extern char *ENGINE_EXTENSIONS;
7360 void GL_Init (void)
7361 {
7362         gl_renderer = (const char *)qglGetString(GL_RENDERER);
7363         gl_vendor = (const char *)qglGetString(GL_VENDOR);
7364         gl_version = (const char *)qglGetString(GL_VERSION);
7365         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
7366
7367         if (!gl_extensions)
7368                 gl_extensions = "";
7369         if (!gl_platformextensions)
7370                 gl_platformextensions = "";
7371
7372         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
7373         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
7374         Con_Printf("GL_VERSION: %s\n", gl_version);
7375         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
7376         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
7377
7378         VID_CheckExtensions();
7379
7380         // LordHavoc: report supported extensions
7381         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
7382
7383         // clear to black (loading plaque will be seen over this)
7384         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
7385 }
7386
7387 int R_CullBox(const vec3_t mins, const vec3_t maxs)
7388 {
7389         int i;
7390         mplane_t *p;
7391         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7392         {
7393                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
7394                 if (i == 4)
7395                         continue;
7396                 p = r_refdef.view.frustum + i;
7397                 switch(p->signbits)
7398                 {
7399                 default:
7400                 case 0:
7401                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7402                                 return true;
7403                         break;
7404                 case 1:
7405                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7406                                 return true;
7407                         break;
7408                 case 2:
7409                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7410                                 return true;
7411                         break;
7412                 case 3:
7413                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7414                                 return true;
7415                         break;
7416                 case 4:
7417                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7418                                 return true;
7419                         break;
7420                 case 5:
7421                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7422                                 return true;
7423                         break;
7424                 case 6:
7425                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7426                                 return true;
7427                         break;
7428                 case 7:
7429                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7430                                 return true;
7431                         break;
7432                 }
7433         }
7434         return false;
7435 }
7436
7437 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
7438 {
7439         int i;
7440         const mplane_t *p;
7441         for (i = 0;i < numplanes;i++)
7442         {
7443                 p = planes + i;
7444                 switch(p->signbits)
7445                 {
7446                 default:
7447                 case 0:
7448                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7449                                 return true;
7450                         break;
7451                 case 1:
7452                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7453                                 return true;
7454                         break;
7455                 case 2:
7456                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7457                                 return true;
7458                         break;
7459                 case 3:
7460                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7461                                 return true;
7462                         break;
7463                 case 4:
7464                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7465                                 return true;
7466                         break;
7467                 case 5:
7468                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7469                                 return true;
7470                         break;
7471                 case 6:
7472                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7473                                 return true;
7474                         break;
7475                 case 7:
7476                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7477                                 return true;
7478                         break;
7479                 }
7480         }
7481         return false;
7482 }
7483
7484 //==================================================================================
7485
7486 // LordHavoc: this stores temporary data used within the same frame
7487
7488 qboolean r_framedata_failed;
7489 static size_t r_framedata_size;
7490 static size_t r_framedata_current;
7491 static void *r_framedata_base;
7492
7493 void R_FrameData_Reset(void)
7494 {
7495         if (r_framedata_base)
7496                 Mem_Free(r_framedata_base);
7497         r_framedata_base = NULL;
7498         r_framedata_size = 0;
7499         r_framedata_current = 0;
7500         r_framedata_failed = false;
7501 }
7502
7503 void R_FrameData_NewFrame(void)
7504 {
7505         size_t wantedsize;
7506         if (r_framedata_failed)
7507                 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
7508         wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
7509         wantedsize = bound(65536, wantedsize, 128*1024*1024);
7510         if (r_framedata_size != wantedsize)
7511         {
7512                 r_framedata_size = wantedsize;
7513                 if (r_framedata_base)
7514                         Mem_Free(r_framedata_base);
7515                 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
7516         }
7517         r_framedata_current = 0;
7518         r_framedata_failed = false;
7519 }
7520
7521 void *R_FrameData_Alloc(size_t size)
7522 {
7523         void *data;
7524
7525         // align to 16 byte boundary
7526         size = (size + 15) & ~15;
7527         data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
7528         r_framedata_current += size;
7529
7530         // check overflow
7531         if (r_framedata_current > r_framedata_size)
7532                 r_framedata_failed = true;
7533
7534         // return NULL on everything after a failure
7535         if (r_framedata_failed)
7536                 return NULL;
7537
7538         return data;
7539 }
7540
7541 void *R_FrameData_Store(size_t size, void *data)
7542 {
7543         void *d = R_FrameData_Alloc(size);
7544         if (d)
7545                 memcpy(d, data, size);
7546         return d;
7547 }
7548
7549 //==================================================================================
7550
7551 // LordHavoc: animcache originally written by Echon, rewritten since then
7552
7553 /**
7554  * Animation cache prevents re-generating mesh data for an animated model
7555  * multiple times in one frame for lighting, shadowing, reflections, etc.
7556  */
7557
7558 void R_AnimCache_Free(void)
7559 {
7560 }
7561
7562 void R_AnimCache_ClearCache(void)
7563 {
7564         int i;
7565         entity_render_t *ent;
7566
7567         for (i = 0;i < r_refdef.scene.numentities;i++)
7568         {
7569                 ent = r_refdef.scene.entities[i];
7570                 ent->animcache_vertex3f = NULL;
7571                 ent->animcache_normal3f = NULL;
7572                 ent->animcache_svector3f = NULL;
7573                 ent->animcache_tvector3f = NULL;
7574                 ent->animcache_vertexposition = NULL;
7575                 ent->animcache_vertexmesh = NULL;
7576                 ent->animcache_vertexpositionbuffer = NULL;
7577                 ent->animcache_vertexmeshbuffer = NULL;
7578         }
7579 }
7580
7581 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
7582 {
7583         int i;
7584
7585         // identical memory layout, so no need to allocate...
7586         // this also provides the vertexposition structure to everything, e.g.
7587         // depth masked rendering currently uses it even if having separate
7588         // arrays
7589         // NOTE: get rid of this optimization if changing it to e.g. 4f
7590         ent->animcache_vertexposition = (r_vertexposition_t *)ent->animcache_vertex3f;
7591
7592         // TODO:
7593         // get rid of following uses of VERTEXPOSITION, change to the array:
7594         // R_DrawTextureSurfaceList_Sky if skyrendermasked
7595         // R_DrawSurface_TransparentCallback if r_transparentdepthmasking.integer
7596         // R_DrawTextureSurfaceList_DepthOnly
7597         // R_Q1BSP_DrawShadowMap
7598
7599         switch(vid.renderpath)
7600         {
7601         case RENDERPATH_GL20:
7602         case RENDERPATH_CGGL:
7603                 // need the meshbuffers if !gl_mesh_separatearrays.integer
7604                 if (gl_mesh_separatearrays.integer)
7605                         return;
7606                 break;
7607         case RENDERPATH_D3D9:
7608         case RENDERPATH_D3D10:
7609         case RENDERPATH_D3D11:
7610                 // always need the meshbuffers
7611                 break;
7612         case RENDERPATH_GL13:
7613         case RENDERPATH_GL11:
7614                 // never need the meshbuffers
7615                 return;
7616         }
7617
7618         if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
7619                 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
7620         /*
7621         if (!ent->animcache_vertexposition)
7622                 ent->animcache_vertexposition = (r_vertexposition_t *)R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
7623         */
7624         if (ent->animcache_vertexposition)
7625         {
7626                 /*
7627                 for (i = 0;i < numvertices;i++)
7628                         memcpy(ent->animcache_vertexposition[i].vertex3f, ent->animcache_vertex3f + 3*i, sizeof(float[3]));
7629                 */
7630                 // TODO: upload vertex buffer?
7631         }
7632         if (ent->animcache_vertexmesh)
7633         {
7634                 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
7635                 for (i = 0;i < numvertices;i++)
7636                         memcpy(ent->animcache_vertexmesh[i].vertex3f, ent->animcache_vertex3f + 3*i, sizeof(float[3]));
7637                 if (ent->animcache_svector3f)
7638                         for (i = 0;i < numvertices;i++)
7639                                 memcpy(ent->animcache_vertexmesh[i].svector3f, ent->animcache_svector3f + 3*i, sizeof(float[3]));
7640                 if (ent->animcache_tvector3f)
7641                         for (i = 0;i < numvertices;i++)
7642                                 memcpy(ent->animcache_vertexmesh[i].tvector3f, ent->animcache_tvector3f + 3*i, sizeof(float[3]));
7643                 if (ent->animcache_normal3f)
7644                         for (i = 0;i < numvertices;i++)
7645                                 memcpy(ent->animcache_vertexmesh[i].normal3f, ent->animcache_normal3f + 3*i, sizeof(float[3]));
7646                 // TODO: upload vertex buffer?
7647         }
7648 }
7649
7650 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
7651 {
7652         dp_model_t *model = ent->model;
7653         int numvertices;
7654         // see if it's already cached this frame
7655         if (ent->animcache_vertex3f)
7656         {
7657                 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
7658                 if (wantnormals || wanttangents)
7659                 {
7660                         if (ent->animcache_normal3f)
7661                                 wantnormals = false;
7662                         if (ent->animcache_svector3f)
7663                                 wanttangents = false;
7664                         if (wantnormals || wanttangents)
7665                         {
7666                                 numvertices = model->surfmesh.num_vertices;
7667                                 if (wantnormals)
7668                                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7669                                 if (wanttangents)
7670                                 {
7671                                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7672                                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7673                                 }
7674                                 if (!r_framedata_failed)
7675                                 {
7676                                         model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
7677                                         R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7678                                 }
7679                         }
7680                 }
7681         }
7682         else
7683         {
7684                 // see if this ent is worth caching
7685                 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7686                         return false;
7687                 // get some memory for this entity and generate mesh data
7688                 numvertices = model->surfmesh.num_vertices;
7689                 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7690                 if (wantnormals)
7691                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7692                 if (wanttangents)
7693                 {
7694                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7695                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7696                 }
7697                 if (!r_framedata_failed)
7698                 {
7699                         model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7700                         R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7701                 }
7702         }
7703         return !r_framedata_failed;
7704 }
7705
7706 void R_AnimCache_CacheVisibleEntities(void)
7707 {
7708         int i;
7709         qboolean wantnormals = true;
7710         qboolean wanttangents = !r_showsurfaces.integer;
7711
7712         switch(vid.renderpath)
7713         {
7714         case RENDERPATH_GL20:
7715         case RENDERPATH_CGGL:
7716         case RENDERPATH_D3D9:
7717         case RENDERPATH_D3D10:
7718         case RENDERPATH_D3D11:
7719                 break;
7720         case RENDERPATH_GL13:
7721         case RENDERPATH_GL11:
7722                 wanttangents = false;
7723                 break;
7724         }
7725
7726         if (r_shownormals.integer)
7727                 wanttangents = wantnormals = true;
7728
7729         // TODO: thread this
7730         // NOTE: R_PrepareRTLights() also caches entities
7731
7732         for (i = 0;i < r_refdef.scene.numentities;i++)
7733                 if (r_refdef.viewcache.entityvisible[i])
7734                         R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7735 }
7736
7737 //==================================================================================
7738
7739 static void R_View_UpdateEntityLighting (void)
7740 {
7741         int i;
7742         entity_render_t *ent;
7743         vec3_t tempdiffusenormal, avg;
7744         vec_t f, fa, fd, fdd;
7745         qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7746
7747         for (i = 0;i < r_refdef.scene.numentities;i++)
7748         {
7749                 ent = r_refdef.scene.entities[i];
7750
7751                 // skip unseen models
7752                 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7753                         continue;
7754
7755                 // skip bsp models
7756                 if (ent->model && ent->model->brush.num_leafs)
7757                 {
7758                         // TODO: use modellight for r_ambient settings on world?
7759                         VectorSet(ent->modellight_ambient, 0, 0, 0);
7760                         VectorSet(ent->modellight_diffuse, 0, 0, 0);
7761                         VectorSet(ent->modellight_lightdir, 0, 0, 1);
7762                         continue;
7763                 }
7764
7765                 // fetch the lighting from the worldmodel data
7766                 VectorClear(ent->modellight_ambient);
7767                 VectorClear(ent->modellight_diffuse);
7768                 VectorClear(tempdiffusenormal);
7769                 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7770                 {
7771                         vec3_t org;
7772                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7773                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
7774                         if(ent->flags & RENDER_EQUALIZE)
7775                         {
7776                                 // first fix up ambient lighting...
7777                                 if(r_equalize_entities_minambient.value > 0)
7778                                 {
7779                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7780                                         if(fd > 0)
7781                                         {
7782                                                 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7783                                                 if(fa < r_equalize_entities_minambient.value * fd)
7784                                                 {
7785                                                         // solve:
7786                                                         //   fa'/fd' = minambient
7787                                                         //   fa'+0.25*fd' = fa+0.25*fd
7788                                                         //   ...
7789                                                         //   fa' = fd' * minambient
7790                                                         //   fd'*(0.25+minambient) = fa+0.25*fd
7791                                                         //   ...
7792                                                         //   fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7793                                                         //   fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7794                                                         //   ...
7795                                                         fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7796                                                         f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
7797                                                         VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7798                                                         VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7799                                                 }
7800                                         }
7801                                 }
7802
7803                                 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7804                                 {
7805                                         VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7806                                         f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7807                                         if(f > 0)
7808                                         {
7809                                                 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7810                                                 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7811                                                 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7812                                         }
7813                                 }
7814                         }
7815                 }
7816                 else // highly rare
7817                         VectorSet(ent->modellight_ambient, 1, 1, 1);
7818
7819                 // move the light direction into modelspace coordinates for lighting code
7820                 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7821                 if(VectorLength2(ent->modellight_lightdir) == 0)
7822                         VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7823                 VectorNormalize(ent->modellight_lightdir);
7824         }
7825 }
7826
7827 #define MAX_LINEOFSIGHTTRACES 64
7828
7829 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7830 {
7831         int i;
7832         vec3_t boxmins, boxmaxs;
7833         vec3_t start;
7834         vec3_t end;
7835         dp_model_t *model = r_refdef.scene.worldmodel;
7836
7837         if (!model || !model->brush.TraceLineOfSight)
7838                 return true;
7839
7840         // expand the box a little
7841         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7842         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7843         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7844         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7845         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7846         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7847
7848         // return true if eye is inside enlarged box
7849         if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7850                 return true;
7851
7852         // try center
7853         VectorCopy(eye, start);
7854         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7855         if (model->brush.TraceLineOfSight(model, start, end))
7856                 return true;
7857
7858         // try various random positions
7859         for (i = 0;i < numsamples;i++)
7860         {
7861                 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7862                 if (model->brush.TraceLineOfSight(model, start, end))
7863                         return true;
7864         }
7865
7866         return false;
7867 }
7868
7869
7870 static void R_View_UpdateEntityVisible (void)
7871 {
7872         int i;
7873         int renderimask;
7874         int samples;
7875         entity_render_t *ent;
7876
7877         renderimask = r_refdef.envmap                                    ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7878                 : r_waterstate.renderingrefraction                       ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7879                 : (chase_active.integer || r_waterstate.renderingscene)  ? RENDER_VIEWMODEL
7880                 :                                                          RENDER_EXTERIORMODEL;
7881         if (!r_drawviewmodel.integer)
7882                 renderimask |= RENDER_VIEWMODEL;
7883         if (!r_drawexteriormodel.integer)
7884                 renderimask |= RENDER_EXTERIORMODEL;
7885         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7886         {
7887                 // worldmodel can check visibility
7888                 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7889                 for (i = 0;i < r_refdef.scene.numentities;i++)
7890                 {
7891                         ent = r_refdef.scene.entities[i];
7892                         if (!(ent->flags & renderimask))
7893                         if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7894                         if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
7895                                 r_refdef.viewcache.entityvisible[i] = true;
7896                 }
7897                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7898                         // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7899                 {
7900                         for (i = 0;i < r_refdef.scene.numentities;i++)
7901                         {
7902                                 ent = r_refdef.scene.entities[i];
7903                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7904                                 {
7905                                         samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7906                                         if (samples < 0)
7907                                                 continue; // temp entities do pvs only
7908                                         if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7909                                                 ent->last_trace_visibility = realtime;
7910                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7911                                                 r_refdef.viewcache.entityvisible[i] = 0;
7912                                 }
7913                         }
7914                 }
7915         }
7916         else
7917         {
7918                 // no worldmodel or it can't check visibility
7919                 for (i = 0;i < r_refdef.scene.numentities;i++)
7920                 {
7921                         ent = r_refdef.scene.entities[i];
7922                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
7923                 }
7924         }
7925 }
7926
7927 /// only used if skyrendermasked, and normally returns false
7928 int R_DrawBrushModelsSky (void)
7929 {
7930         int i, sky;
7931         entity_render_t *ent;
7932
7933         sky = false;
7934         for (i = 0;i < r_refdef.scene.numentities;i++)
7935         {
7936                 if (!r_refdef.viewcache.entityvisible[i])
7937                         continue;
7938                 ent = r_refdef.scene.entities[i];
7939                 if (!ent->model || !ent->model->DrawSky)
7940                         continue;
7941                 ent->model->DrawSky(ent);
7942                 sky = true;
7943         }
7944         return sky;
7945 }
7946
7947 static void R_DrawNoModel(entity_render_t *ent);
7948 static void R_DrawModels(void)
7949 {
7950         int i;
7951         entity_render_t *ent;
7952
7953         for (i = 0;i < r_refdef.scene.numentities;i++)
7954         {
7955                 if (!r_refdef.viewcache.entityvisible[i])
7956                         continue;
7957                 ent = r_refdef.scene.entities[i];
7958                 r_refdef.stats.entities++;
7959                 if (ent->model && ent->model->Draw != NULL)
7960                         ent->model->Draw(ent);
7961                 else
7962                         R_DrawNoModel(ent);
7963         }
7964 }
7965
7966 static void R_DrawModelsDepth(void)
7967 {
7968         int i;
7969         entity_render_t *ent;
7970
7971         for (i = 0;i < r_refdef.scene.numentities;i++)
7972         {
7973                 if (!r_refdef.viewcache.entityvisible[i])
7974                         continue;
7975                 ent = r_refdef.scene.entities[i];
7976                 if (ent->model && ent->model->DrawDepth != NULL)
7977                         ent->model->DrawDepth(ent);
7978         }
7979 }
7980
7981 static void R_DrawModelsDebug(void)
7982 {
7983         int i;
7984         entity_render_t *ent;
7985
7986         for (i = 0;i < r_refdef.scene.numentities;i++)
7987         {
7988                 if (!r_refdef.viewcache.entityvisible[i])
7989                         continue;
7990                 ent = r_refdef.scene.entities[i];
7991                 if (ent->model && ent->model->DrawDebug != NULL)
7992                         ent->model->DrawDebug(ent);
7993         }
7994 }
7995
7996 static void R_DrawModelsAddWaterPlanes(void)
7997 {
7998         int i;
7999         entity_render_t *ent;
8000
8001         for (i = 0;i < r_refdef.scene.numentities;i++)
8002         {
8003                 if (!r_refdef.viewcache.entityvisible[i])
8004                         continue;
8005                 ent = r_refdef.scene.entities[i];
8006                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
8007                         ent->model->DrawAddWaterPlanes(ent);
8008         }
8009 }
8010
8011 static void R_View_SetFrustum(const int *scissor)
8012 {
8013         int i;
8014         double fpx, fnx, fpy, fny;
8015         vec3_t forward, left, up, origin;
8016
8017         if(scissor)
8018         {
8019                 // flipped x coordinates (because x points left here)
8020                 fpx =  1.0 - 2.0 * (scissor[0]              - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
8021                 fnx =  1.0 - 2.0 * (scissor[0] + scissor[2] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
8022
8023                 // non-flipped y coordinates
8024                 fny = -1.0 + 2.0 * (scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
8025                 fpy = -1.0 + 2.0 * (scissor[1] + scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
8026         }
8027         else
8028         {
8029                 fnx = fny = -1;
8030                 fpx = fpy = +1;
8031         }
8032
8033         // we can't trust r_refdef.view.forward and friends in reflected scenes
8034         Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
8035
8036 #if 0
8037         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
8038         r_refdef.view.frustum[0].normal[1] = 0 - 0;
8039         r_refdef.view.frustum[0].normal[2] = -1 - 0;
8040         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
8041         r_refdef.view.frustum[1].normal[1] = 0 + 0;
8042         r_refdef.view.frustum[1].normal[2] = -1 + 0;
8043         r_refdef.view.frustum[2].normal[0] = 0 - 0;
8044         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
8045         r_refdef.view.frustum[2].normal[2] = -1 - 0;
8046         r_refdef.view.frustum[3].normal[0] = 0 + 0;
8047         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
8048         r_refdef.view.frustum[3].normal[2] = -1 + 0;
8049 #endif
8050
8051 #if 0
8052         zNear = r_refdef.nearclip;
8053         nudge = 1.0 - 1.0 / (1<<23);
8054         r_refdef.view.frustum[4].normal[0] = 0 - 0;
8055         r_refdef.view.frustum[4].normal[1] = 0 - 0;
8056         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
8057         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
8058         r_refdef.view.frustum[5].normal[0] = 0 + 0;
8059         r_refdef.view.frustum[5].normal[1] = 0 + 0;
8060         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
8061         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
8062 #endif
8063
8064
8065
8066 #if 0
8067         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
8068         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
8069         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
8070         r_refdef.view.frustum[0].dist = m[15] - m[12];
8071
8072         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
8073         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
8074         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
8075         r_refdef.view.frustum[1].dist = m[15] + m[12];
8076
8077         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
8078         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
8079         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
8080         r_refdef.view.frustum[2].dist = m[15] - m[13];
8081
8082         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
8083         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
8084         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
8085         r_refdef.view.frustum[3].dist = m[15] + m[13];
8086
8087         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
8088         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
8089         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
8090         r_refdef.view.frustum[4].dist = m[15] - m[14];
8091
8092         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
8093         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
8094         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
8095         r_refdef.view.frustum[5].dist = m[15] + m[14];
8096 #endif
8097
8098         if (r_refdef.view.useperspective)
8099         {
8100                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
8101                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
8102                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
8103                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
8104                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
8105
8106                 // then the normals from the corners relative to origin
8107                 CrossProduct(r_refdef.view.frustumcorner[2], r_refdef.view.frustumcorner[0], r_refdef.view.frustum[0].normal);
8108                 CrossProduct(r_refdef.view.frustumcorner[1], r_refdef.view.frustumcorner[3], r_refdef.view.frustum[1].normal);
8109                 CrossProduct(r_refdef.view.frustumcorner[0], r_refdef.view.frustumcorner[1], r_refdef.view.frustum[2].normal);
8110                 CrossProduct(r_refdef.view.frustumcorner[3], r_refdef.view.frustumcorner[2], r_refdef.view.frustum[3].normal);
8111
8112                 // Leaving those out was a mistake, those were in the old code, and they
8113                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
8114                 // I couldn't reproduce it after adding those normalizations. --blub
8115                 VectorNormalize(r_refdef.view.frustum[0].normal);
8116                 VectorNormalize(r_refdef.view.frustum[1].normal);
8117                 VectorNormalize(r_refdef.view.frustum[2].normal);
8118                 VectorNormalize(r_refdef.view.frustum[3].normal);
8119
8120                 // make the corners absolute
8121                 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
8122                 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
8123                 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
8124                 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
8125
8126                 // one more normal
8127                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
8128
8129                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
8130                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
8131                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
8132                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
8133                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
8134         }
8135         else
8136         {
8137                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
8138                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
8139                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
8140                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
8141                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
8142                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
8143                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
8144                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
8145                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
8146                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
8147         }
8148         r_refdef.view.numfrustumplanes = 5;
8149
8150         if (r_refdef.view.useclipplane)
8151         {
8152                 r_refdef.view.numfrustumplanes = 6;
8153                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
8154         }
8155
8156         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
8157                 PlaneClassify(r_refdef.view.frustum + i);
8158
8159         // LordHavoc: note to all quake engine coders, Quake had a special case
8160         // for 90 degrees which assumed a square view (wrong), so I removed it,
8161         // Quake2 has it disabled as well.
8162
8163         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
8164         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
8165         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
8166         //PlaneClassify(&frustum[0]);
8167
8168         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
8169         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
8170         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
8171         //PlaneClassify(&frustum[1]);
8172
8173         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
8174         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
8175         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
8176         //PlaneClassify(&frustum[2]);
8177
8178         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
8179         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
8180         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
8181         //PlaneClassify(&frustum[3]);
8182
8183         // nearclip plane
8184         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
8185         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
8186         //PlaneClassify(&frustum[4]);
8187 }
8188
8189 void R_View_UpdateWithScissor(const int *myscissor)
8190 {
8191         R_Main_ResizeViewCache();
8192         R_View_SetFrustum(myscissor);
8193         R_View_WorldVisibility(r_refdef.view.useclipplane);
8194         R_View_UpdateEntityVisible();
8195         R_View_UpdateEntityLighting();
8196 }
8197
8198 void R_View_Update(void)
8199 {
8200         R_Main_ResizeViewCache();
8201         R_View_SetFrustum(NULL);
8202         R_View_WorldVisibility(r_refdef.view.useclipplane);
8203         R_View_UpdateEntityVisible();
8204         R_View_UpdateEntityLighting();
8205 }
8206
8207 void R_SetupView(qboolean allowwaterclippingplane)
8208 {
8209         const float *customclipplane = NULL;
8210         float plane[4];
8211         if (r_refdef.view.useclipplane && allowwaterclippingplane)
8212         {
8213                 // LordHavoc: couldn't figure out how to make this approach the
8214                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
8215                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
8216                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
8217                         dist = r_refdef.view.clipplane.dist;
8218                 plane[0] = r_refdef.view.clipplane.normal[0];
8219                 plane[1] = r_refdef.view.clipplane.normal[1];
8220                 plane[2] = r_refdef.view.clipplane.normal[2];
8221                 plane[3] = dist;
8222                 customclipplane = plane;
8223         }
8224
8225         if (!r_refdef.view.useperspective)
8226                 R_Viewport_InitOrtho(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, -r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip, customclipplane);
8227         else if (vid.stencil && r_useinfinitefarclip.integer)
8228                 R_Viewport_InitPerspectiveInfinite(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, customclipplane);
8229         else
8230                 R_Viewport_InitPerspective(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip, customclipplane);
8231         R_SetViewport(&r_refdef.view.viewport);
8232 }
8233
8234 void R_EntityMatrix(const matrix4x4_t *matrix)
8235 {
8236         if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
8237         {
8238                 gl_modelmatrixchanged = false;
8239                 gl_modelmatrix = *matrix;
8240                 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
8241                 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
8242                 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
8243                 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
8244                 CHECKGLERROR
8245                 switch(vid.renderpath)
8246                 {
8247                 case RENDERPATH_D3D9:
8248 #ifdef SUPPORTD3D
8249                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
8250                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
8251 #endif
8252                         break;
8253                 case RENDERPATH_D3D10:
8254                         Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
8255                         break;
8256                 case RENDERPATH_D3D11:
8257                         Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
8258                         break;
8259                 case RENDERPATH_GL20:
8260                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
8261                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
8262                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8263                         break;
8264                 case RENDERPATH_CGGL:
8265 #ifdef SUPPORTCG
8266                         CHECKCGERROR
8267                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
8268                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
8269                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8270 #endif
8271                         break;
8272                 case RENDERPATH_GL13:
8273                 case RENDERPATH_GL11:
8274                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8275                         break;
8276                 }
8277         }
8278 }
8279
8280 void R_ResetViewRendering2D(void)
8281 {
8282         r_viewport_t viewport;
8283         DrawQ_Finish();
8284
8285         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
8286         R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, 0, 0, 1, 1, -10, 100, NULL);
8287         R_SetViewport(&viewport);
8288         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
8289         GL_Color(1, 1, 1, 1);
8290         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8291         GL_BlendFunc(GL_ONE, GL_ZERO);
8292         GL_AlphaTest(false);
8293         GL_ScissorTest(false);
8294         GL_DepthMask(false);
8295         GL_DepthRange(0, 1);
8296         GL_DepthTest(false);
8297         GL_DepthFunc(GL_LEQUAL);
8298         R_EntityMatrix(&identitymatrix);
8299         R_Mesh_ResetTextureState();
8300         GL_PolygonOffset(0, 0);
8301         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8302         switch(vid.renderpath)
8303         {
8304         case RENDERPATH_GL11:
8305         case RENDERPATH_GL13:
8306         case RENDERPATH_GL20:
8307         case RENDERPATH_CGGL:
8308                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8309                 break;
8310         case RENDERPATH_D3D9:
8311         case RENDERPATH_D3D10:
8312         case RENDERPATH_D3D11:
8313                 break;
8314         }
8315         GL_CullFace(GL_NONE);
8316 }
8317
8318 void R_ResetViewRendering3D(void)
8319 {
8320         DrawQ_Finish();
8321
8322         R_SetupView(true);
8323         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8324         GL_Color(1, 1, 1, 1);
8325         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8326         GL_BlendFunc(GL_ONE, GL_ZERO);
8327         GL_AlphaTest(false);
8328         GL_ScissorTest(true);
8329         GL_DepthMask(true);
8330         GL_DepthRange(0, 1);
8331         GL_DepthTest(true);
8332         GL_DepthFunc(GL_LEQUAL);
8333         R_EntityMatrix(&identitymatrix);
8334         R_Mesh_ResetTextureState();
8335         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8336         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8337         switch(vid.renderpath)
8338         {
8339         case RENDERPATH_GL11:
8340         case RENDERPATH_GL13:
8341         case RENDERPATH_GL20:
8342         case RENDERPATH_CGGL:
8343                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8344                 break;
8345         case RENDERPATH_D3D9:
8346         case RENDERPATH_D3D10:
8347         case RENDERPATH_D3D11:
8348                 break;
8349         }
8350         GL_CullFace(r_refdef.view.cullface_back);
8351 }
8352
8353 /*
8354 ================
8355 R_RenderView_UpdateViewVectors
8356 ================
8357 */
8358 static void R_RenderView_UpdateViewVectors(void)
8359 {
8360         // break apart the view matrix into vectors for various purposes
8361         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
8362         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
8363         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
8364         VectorNegate(r_refdef.view.left, r_refdef.view.right);
8365         // make an inverted copy of the view matrix for tracking sprites
8366         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
8367 }
8368
8369 void R_RenderScene(void);
8370 void R_RenderWaterPlanes(void);
8371
8372 static void R_Water_StartFrame(void)
8373 {
8374         int i;
8375         int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
8376         r_waterstate_waterplane_t *p;
8377
8378         if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
8379                 return;
8380
8381         switch(vid.renderpath)
8382         {
8383         case RENDERPATH_GL20:
8384         case RENDERPATH_CGGL:
8385         case RENDERPATH_D3D9:
8386         case RENDERPATH_D3D10:
8387         case RENDERPATH_D3D11:
8388                 break;
8389         case RENDERPATH_GL13:
8390         case RENDERPATH_GL11:
8391                 return;
8392         }
8393
8394         // set waterwidth and waterheight to the water resolution that will be
8395         // used (often less than the screen resolution for faster rendering)
8396         waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
8397         waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
8398
8399         // calculate desired texture sizes
8400         // can't use water if the card does not support the texture size
8401         if (!r_water.integer || r_showsurfaces.integer)
8402                 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
8403         else if (vid.support.arb_texture_non_power_of_two)
8404         {
8405                 texturewidth = waterwidth;
8406                 textureheight = waterheight;
8407                 camerawidth = waterwidth;
8408                 cameraheight = waterheight;
8409         }
8410         else
8411         {
8412                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
8413                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
8414                 for (camerawidth    = 1;camerawidth   <= waterwidth; camerawidth    *= 2); camerawidth  /= 2;
8415                 for (cameraheight   = 1;cameraheight  <= waterheight;cameraheight   *= 2); cameraheight /= 2;
8416         }
8417
8418         // allocate textures as needed
8419         if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
8420         {
8421                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8422                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
8423                 {
8424                         if (p->texture_refraction)
8425                                 R_FreeTexture(p->texture_refraction);
8426                         p->texture_refraction = NULL;
8427                         if (p->texture_reflection)
8428                                 R_FreeTexture(p->texture_reflection);
8429                         p->texture_reflection = NULL;
8430                         if (p->texture_camera)
8431                                 R_FreeTexture(p->texture_camera);
8432                         p->texture_camera = NULL;
8433                 }
8434                 memset(&r_waterstate, 0, sizeof(r_waterstate));
8435                 r_waterstate.texturewidth = texturewidth;
8436                 r_waterstate.textureheight = textureheight;
8437                 r_waterstate.camerawidth = camerawidth;
8438                 r_waterstate.cameraheight = cameraheight;
8439         }
8440
8441         if (r_waterstate.texturewidth)
8442         {
8443                 r_waterstate.enabled = true;
8444
8445                 // when doing a reduced render (HDR) we want to use a smaller area
8446                 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
8447                 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
8448
8449                 // set up variables that will be used in shader setup
8450                 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8451                 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8452                 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8453                 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8454         }
8455
8456         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8457         r_waterstate.numwaterplanes = 0;
8458 }
8459
8460 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
8461 {
8462         int triangleindex, planeindex;
8463         const int *e;
8464         vec3_t vert[3];
8465         vec3_t normal;
8466         vec3_t center;
8467         mplane_t plane;
8468         r_waterstate_waterplane_t *p;
8469         texture_t *t = R_GetCurrentTexture(surface->texture);
8470
8471         // just use the first triangle with a valid normal for any decisions
8472         VectorClear(normal);
8473         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
8474         {
8475                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
8476                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
8477                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
8478                 TriangleNormal(vert[0], vert[1], vert[2], normal);
8479                 if (VectorLength2(normal) >= 0.001)
8480                         break;
8481         }
8482
8483         VectorCopy(normal, plane.normal);
8484         VectorNormalize(plane.normal);
8485         plane.dist = DotProduct(vert[0], plane.normal);
8486         PlaneClassify(&plane);
8487         if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
8488         {
8489                 // skip backfaces (except if nocullface is set)
8490                 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
8491                         return;
8492                 VectorNegate(plane.normal, plane.normal);
8493                 plane.dist *= -1;
8494                 PlaneClassify(&plane);
8495         }
8496
8497
8498         // find a matching plane if there is one
8499         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8500                 if(p->camera_entity == t->camera_entity)
8501                         if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
8502                                 break;
8503         if (planeindex >= r_waterstate.maxwaterplanes)
8504                 return; // nothing we can do, out of planes
8505
8506         // if this triangle does not fit any known plane rendered this frame, add one
8507         if (planeindex >= r_waterstate.numwaterplanes)
8508         {
8509                 // store the new plane
8510                 r_waterstate.numwaterplanes++;
8511                 p->plane = plane;
8512                 // clear materialflags and pvs
8513                 p->materialflags = 0;
8514                 p->pvsvalid = false;
8515                 p->camera_entity = t->camera_entity;
8516                 VectorCopy(surface->mins, p->mins);
8517                 VectorCopy(surface->maxs, p->maxs);
8518         }
8519         else
8520         {
8521                 // merge mins/maxs
8522                 p->mins[0] = min(p->mins[0], surface->mins[0]);
8523                 p->mins[1] = min(p->mins[1], surface->mins[1]);
8524                 p->mins[2] = min(p->mins[2], surface->mins[2]);
8525                 p->maxs[0] = min(p->maxs[0], surface->maxs[0]);
8526                 p->maxs[1] = min(p->maxs[1], surface->maxs[1]);
8527                 p->maxs[2] = min(p->maxs[2], surface->maxs[2]);
8528         }
8529         // merge this surface's materialflags into the waterplane
8530         p->materialflags |= t->currentmaterialflags;
8531         if(!(p->materialflags & MATERIALFLAG_CAMERA))
8532         {
8533                 // merge this surface's PVS into the waterplane
8534                 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
8535                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
8536                  && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
8537                 {
8538                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
8539                         p->pvsvalid = true;
8540                 }
8541         }
8542 }
8543
8544 static void R_Water_ProcessPlanes(void)
8545 {
8546         int myscissor[4];
8547         r_refdef_view_t originalview;
8548         r_refdef_view_t myview;
8549         int planeindex;
8550         r_waterstate_waterplane_t *p;
8551         vec3_t visorigin;
8552
8553         originalview = r_refdef.view;
8554
8555         // make sure enough textures are allocated
8556         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8557         {
8558                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8559                 {
8560                         if (!p->texture_refraction)
8561                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8562                         if (!p->texture_refraction)
8563                                 goto error;
8564                 }
8565                 else if (p->materialflags & MATERIALFLAG_CAMERA)
8566                 {
8567                         if (!p->texture_camera)
8568                                 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
8569                         if (!p->texture_camera)
8570                                 goto error;
8571                 }
8572
8573                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8574                 {
8575                         if (!p->texture_reflection)
8576                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8577                         if (!p->texture_reflection)
8578                                 goto error;
8579                 }
8580         }
8581
8582         // render views
8583         r_refdef.view = originalview;
8584         r_refdef.view.showdebug = false;
8585         r_refdef.view.width = r_waterstate.waterwidth;
8586         r_refdef.view.height = r_waterstate.waterheight;
8587         r_refdef.view.useclipplane = true;
8588         myview = r_refdef.view;
8589         r_waterstate.renderingscene = true;
8590         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8591         {
8592                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8593                 {
8594                         r_refdef.view = myview;
8595                         if(r_water_scissormode.integer)
8596                         {
8597                                 R_SetupView(true);
8598                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8599                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8600                         }
8601
8602                         // render reflected scene and copy into texture
8603                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
8604                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
8605                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
8606                         r_refdef.view.clipplane = p->plane;
8607
8608                         // reverse the cullface settings for this render
8609                         r_refdef.view.cullface_front = GL_FRONT;
8610                         r_refdef.view.cullface_back = GL_BACK;
8611                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
8612                         {
8613                                 r_refdef.view.usecustompvs = true;
8614                                 if (p->pvsvalid)
8615                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8616                                 else
8617                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8618                         }
8619
8620                         R_ResetViewRendering3D();
8621                         R_ClearScreen(r_refdef.fogenabled);
8622                         if(r_water_scissormode.integer >= 2)
8623                                 R_View_UpdateWithScissor(myscissor);
8624                         else
8625                                 R_View_Update();
8626                         if(r_water_scissormode.integer)
8627                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8628                         R_RenderScene();
8629
8630                         R_Mesh_CopyToTexture(p->texture_reflection, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8631                 }
8632
8633                 // render the normal view scene and copy into texture
8634                 // (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)
8635                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8636                 {
8637                         r_refdef.view = myview;
8638                         if(r_water_scissormode.integer)
8639                         {
8640                                 R_SetupView(true);
8641                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8642                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8643                         }
8644
8645                         r_waterstate.renderingrefraction = true;
8646
8647                         r_refdef.view.clipplane = p->plane;
8648                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8649                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8650
8651                         if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
8652                         {
8653                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8654                                 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
8655                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8656                                 R_RenderView_UpdateViewVectors();
8657                                 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8658                                 {
8659                                         r_refdef.view.usecustompvs = true;
8660                                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
8661                                 }
8662                         }
8663
8664                         PlaneClassify(&r_refdef.view.clipplane);
8665
8666                         R_ResetViewRendering3D();
8667                         R_ClearScreen(r_refdef.fogenabled);
8668                         if(r_water_scissormode.integer >= 2)
8669                                 R_View_UpdateWithScissor(myscissor);
8670                         else
8671                                 R_View_Update();
8672                         if(r_water_scissormode.integer)
8673                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8674                         R_RenderScene();
8675
8676                         R_Mesh_CopyToTexture(p->texture_refraction, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8677                         r_waterstate.renderingrefraction = false;
8678                 }
8679                 else if (p->materialflags & MATERIALFLAG_CAMERA)
8680                 {
8681                         r_refdef.view = myview;
8682
8683                         r_refdef.view.clipplane = p->plane;
8684                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8685                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8686
8687                         r_refdef.view.width = r_waterstate.camerawidth;
8688                         r_refdef.view.height = r_waterstate.cameraheight;
8689                         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
8690                         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
8691
8692                         if(p->camera_entity)
8693                         {
8694                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8695                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8696                         }
8697
8698                         // note: all of the view is used for displaying... so
8699                         // there is no use in scissoring
8700
8701                         // reverse the cullface settings for this render
8702                         r_refdef.view.cullface_front = GL_FRONT;
8703                         r_refdef.view.cullface_back = GL_BACK;
8704                         // also reverse the view matrix
8705                         Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
8706                         R_RenderView_UpdateViewVectors();
8707                         if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8708                         {
8709                                 r_refdef.view.usecustompvs = true;
8710                                 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
8711                         }
8712                         
8713                         // camera needs no clipplane
8714                         r_refdef.view.useclipplane = false;
8715
8716                         PlaneClassify(&r_refdef.view.clipplane);
8717
8718                         R_ResetViewRendering3D();
8719                         R_ClearScreen(r_refdef.fogenabled);
8720                         R_View_Update();
8721                         R_RenderScene();
8722
8723                         R_Mesh_CopyToTexture(p->texture_camera, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8724                         r_waterstate.renderingrefraction = false;
8725                 }
8726
8727         }
8728         r_waterstate.renderingscene = false;
8729         r_refdef.view = originalview;
8730         R_ResetViewRendering3D();
8731         R_ClearScreen(r_refdef.fogenabled);
8732         R_View_Update();
8733         return;
8734 error:
8735         r_refdef.view = originalview;
8736         r_waterstate.renderingscene = false;
8737         Cvar_SetValueQuick(&r_water, 0);
8738         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
8739         return;
8740 }
8741
8742 void R_Bloom_StartFrame(void)
8743 {
8744         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8745
8746         switch(vid.renderpath)
8747         {
8748         case RENDERPATH_GL20:
8749         case RENDERPATH_CGGL:
8750         case RENDERPATH_D3D9:
8751         case RENDERPATH_D3D10:
8752         case RENDERPATH_D3D11:
8753                 break;
8754         case RENDERPATH_GL13:
8755         case RENDERPATH_GL11:
8756                 return;
8757         }
8758
8759         // set bloomwidth and bloomheight to the bloom resolution that will be
8760         // used (often less than the screen resolution for faster rendering)
8761         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8762         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8763         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8764         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8765         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8766
8767         // calculate desired texture sizes
8768         if (vid.support.arb_texture_non_power_of_two)
8769         {
8770                 screentexturewidth = r_refdef.view.width;
8771                 screentextureheight = r_refdef.view.height;
8772                 bloomtexturewidth = r_bloomstate.bloomwidth;
8773                 bloomtextureheight = r_bloomstate.bloomheight;
8774         }
8775         else
8776         {
8777                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
8778                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
8779                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
8780                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
8781         }
8782
8783         if ((r_hdr.integer || r_bloom.integer || (!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))) && ((r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512) || r_refdef.view.width > (int)vid.maxtexturesize_2d || r_refdef.view.height > (int)vid.maxtexturesize_2d))
8784         {
8785                 Cvar_SetValueQuick(&r_hdr, 0);
8786                 Cvar_SetValueQuick(&r_bloom, 0);
8787                 Cvar_SetValueQuick(&r_motionblur, 0);
8788                 Cvar_SetValueQuick(&r_damageblur, 0);
8789         }
8790
8791         if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial)) && !r_bloom.integer && !r_hdr.integer && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0)))
8792                 screentexturewidth = screentextureheight = 0;
8793         if (!r_hdr.integer && !r_bloom.integer)
8794                 bloomtexturewidth = bloomtextureheight = 0;
8795
8796         // allocate textures as needed
8797         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8798         {
8799                 if (r_bloomstate.texture_screen)
8800                         R_FreeTexture(r_bloomstate.texture_screen);
8801                 r_bloomstate.texture_screen = NULL;
8802                 r_bloomstate.screentexturewidth = screentexturewidth;
8803                 r_bloomstate.screentextureheight = screentextureheight;
8804                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8805                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8806         }
8807         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8808         {
8809                 if (r_bloomstate.texture_bloom)
8810                         R_FreeTexture(r_bloomstate.texture_bloom);
8811                 r_bloomstate.texture_bloom = NULL;
8812                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8813                 r_bloomstate.bloomtextureheight = bloomtextureheight;
8814                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8815                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8816         }
8817
8818         // when doing a reduced render (HDR) we want to use a smaller area
8819         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8820         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8821         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8822         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8823         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8824
8825         // set up a texcoord array for the full resolution screen image
8826         // (we have to keep this around to copy back during final render)
8827         r_bloomstate.screentexcoord2f[0] = 0;
8828         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8829         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8830         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8831         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8832         r_bloomstate.screentexcoord2f[5] = 0;
8833         r_bloomstate.screentexcoord2f[6] = 0;
8834         r_bloomstate.screentexcoord2f[7] = 0;
8835
8836         // set up a texcoord array for the reduced resolution bloom image
8837         // (which will be additive blended over the screen image)
8838         r_bloomstate.bloomtexcoord2f[0] = 0;
8839         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8840         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8841         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8842         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8843         r_bloomstate.bloomtexcoord2f[5] = 0;
8844         r_bloomstate.bloomtexcoord2f[6] = 0;
8845         r_bloomstate.bloomtexcoord2f[7] = 0;
8846
8847         switch(vid.renderpath)
8848         {
8849         case RENDERPATH_GL11:
8850         case RENDERPATH_GL13:
8851         case RENDERPATH_GL20:
8852         case RENDERPATH_CGGL:
8853                 break;
8854         case RENDERPATH_D3D9:
8855         case RENDERPATH_D3D10:
8856         case RENDERPATH_D3D11:
8857                 {
8858                         int i;
8859                         for (i = 0;i < 4;i++)
8860                         {
8861                                 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
8862                                 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
8863                                 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
8864                                 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
8865                         }
8866                 }
8867                 break;
8868         }
8869
8870         if (r_hdr.integer || r_bloom.integer)
8871         {
8872                 r_bloomstate.enabled = true;
8873                 r_bloomstate.hdr = r_hdr.integer != 0;
8874         }
8875
8876         R_Viewport_InitOrtho(&r_bloomstate.viewport, &identitymatrix, r_refdef.view.x, vid.height - r_bloomstate.bloomheight - r_refdef.view.y, r_bloomstate.bloomwidth, r_bloomstate.bloomheight, 0, 0, 1, 1, -10, 100, NULL);
8877 }
8878
8879 void R_Bloom_CopyBloomTexture(float colorscale)
8880 {
8881         r_refdef.stats.bloom++;
8882
8883         // scale down screen texture to the bloom texture size
8884         CHECKGLERROR
8885         R_SetViewport(&r_bloomstate.viewport);
8886         GL_BlendFunc(GL_ONE, GL_ZERO);
8887         GL_Color(colorscale, colorscale, colorscale, 1);
8888         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8889         switch(vid.renderpath)
8890         {
8891         case RENDERPATH_GL11:
8892         case RENDERPATH_GL13:
8893         case RENDERPATH_GL20:
8894         case RENDERPATH_CGGL:
8895                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8896                 break;
8897         case RENDERPATH_D3D9:
8898         case RENDERPATH_D3D10:
8899         case RENDERPATH_D3D11:
8900                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8901                 break;
8902         }
8903         // TODO: do boxfilter scale-down in shader?
8904         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8905         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8906         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8907
8908         // we now have a bloom image in the framebuffer
8909         // copy it into the bloom image texture for later processing
8910         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8911         r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8912 }
8913
8914 void R_Bloom_CopyHDRTexture(void)
8915 {
8916         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8917         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8918 }
8919
8920 void R_Bloom_MakeTexture(void)
8921 {
8922         int x, range, dir;
8923         float xoffset, yoffset, r, brighten;
8924
8925         r_refdef.stats.bloom++;
8926
8927         R_ResetViewRendering2D();
8928
8929         // we have a bloom image in the framebuffer
8930         CHECKGLERROR
8931         R_SetViewport(&r_bloomstate.viewport);
8932
8933         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8934         {
8935                 x *= 2;
8936                 r = bound(0, r_bloom_colorexponent.value / x, 1);
8937                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8938                 GL_Color(r,r,r,1);
8939                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8940                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8941                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8942                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8943
8944                 // copy the vertically blurred bloom view to a texture
8945                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8946                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8947         }
8948
8949         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8950         brighten = r_bloom_brighten.value;
8951         if (r_hdr.integer)
8952                 brighten *= r_hdr_range.value;
8953         brighten = sqrt(brighten);
8954         if(range >= 1)
8955                 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8956         R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8957
8958         for (dir = 0;dir < 2;dir++)
8959         {
8960                 // blend on at multiple vertical offsets to achieve a vertical blur
8961                 // TODO: do offset blends using GLSL
8962                 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8963                 GL_BlendFunc(GL_ONE, GL_ZERO);
8964                 for (x = -range;x <= range;x++)
8965                 {
8966                         if (!dir){xoffset = 0;yoffset = x;}
8967                         else {xoffset = x;yoffset = 0;}
8968                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
8969                         yoffset /= (float)r_bloomstate.bloomtextureheight;
8970                         // compute a texcoord array with the specified x and y offset
8971                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8972                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8973                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8974                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8975                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8976                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8977                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8978                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8979                         // this r value looks like a 'dot' particle, fading sharply to
8980                         // black at the edges
8981                         // (probably not realistic but looks good enough)
8982                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8983                         //r = brighten/(range*2+1);
8984                         r = brighten / (range * 2 + 1);
8985                         if(range >= 1)
8986                                 r *= (1 - x*x/(float)(range*range));
8987                         GL_Color(r, r, r, 1);
8988                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8989                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8990                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8991                         GL_BlendFunc(GL_ONE, GL_ONE);
8992                 }
8993
8994                 // copy the vertically blurred bloom view to a texture
8995                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8996                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8997         }
8998 }
8999
9000 void R_HDR_RenderBloomTexture(void)
9001 {
9002         int oldwidth, oldheight;
9003         float oldcolorscale;
9004
9005         oldcolorscale = r_refdef.view.colorscale;
9006         oldwidth = r_refdef.view.width;
9007         oldheight = r_refdef.view.height;
9008         r_refdef.view.width = r_bloomstate.bloomwidth;
9009         r_refdef.view.height = r_bloomstate.bloomheight;
9010
9011         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
9012         // TODO: add exposure compensation features
9013         // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
9014
9015         r_refdef.view.showdebug = false;
9016         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
9017
9018         R_ResetViewRendering3D();
9019
9020         R_ClearScreen(r_refdef.fogenabled);
9021         if (r_timereport_active)
9022                 R_TimeReport("HDRclear");
9023
9024         R_View_Update();
9025         if (r_timereport_active)
9026                 R_TimeReport("visibility");
9027
9028         // only do secondary renders with HDR if r_hdr is 2 or higher
9029         r_waterstate.numwaterplanes = 0;
9030         if (r_waterstate.enabled && r_hdr.integer >= 2)
9031                 R_RenderWaterPlanes();
9032
9033         r_refdef.view.showdebug = true;
9034         R_RenderScene();
9035         r_waterstate.numwaterplanes = 0;
9036
9037         R_ResetViewRendering2D();
9038
9039         R_Bloom_CopyHDRTexture();
9040         R_Bloom_MakeTexture();
9041
9042         // restore the view settings
9043         r_refdef.view.width = oldwidth;
9044         r_refdef.view.height = oldheight;
9045         r_refdef.view.colorscale = oldcolorscale;
9046
9047         R_ResetViewRendering3D();
9048
9049         R_ClearScreen(r_refdef.fogenabled);
9050         if (r_timereport_active)
9051                 R_TimeReport("viewclear");
9052 }
9053
9054 static void R_BlendView(void)
9055 {
9056         unsigned int permutation;
9057         float uservecs[4][4];
9058
9059         switch (vid.renderpath)
9060         {
9061         case RENDERPATH_GL20:
9062         case RENDERPATH_CGGL:
9063         case RENDERPATH_D3D9:
9064         case RENDERPATH_D3D10:
9065         case RENDERPATH_D3D11:
9066                 permutation =
9067                           (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
9068                         | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
9069                         | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
9070                         | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
9071                         | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
9072
9073                 if (r_bloomstate.texture_screen)
9074                 {
9075                         // make sure the buffer is available
9076                         if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
9077
9078                         R_ResetViewRendering2D();
9079
9080                         if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
9081                         {
9082                                 // declare variables
9083                                 float speed;
9084                                 static float avgspeed;
9085
9086                                 speed = VectorLength(cl.movement_velocity);
9087
9088                                 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
9089                                 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
9090
9091                                 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
9092                                 speed = bound(0, speed, 1);
9093                                 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
9094
9095                                 // calculate values into a standard alpha
9096                                 cl.motionbluralpha = 1 - exp(-
9097                                                 (
9098                                                  (r_motionblur.value * speed / 80)
9099                                                  +
9100                                                  (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
9101                                                 )
9102                                                 /
9103                                                 max(0.0001, cl.time - cl.oldtime) // fps independent
9104                                            );
9105
9106                                 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
9107                                 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
9108                                 // apply the blur
9109                                 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
9110                                 {
9111                                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9112                                         GL_Color(1, 1, 1, cl.motionbluralpha);
9113                                         switch(vid.renderpath)
9114                                         {
9115                                         case RENDERPATH_GL11:
9116                                         case RENDERPATH_GL13:
9117                                         case RENDERPATH_GL20:
9118                                         case RENDERPATH_CGGL:
9119                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
9120                                                 break;
9121                                         case RENDERPATH_D3D9:
9122                                         case RENDERPATH_D3D10:
9123                                         case RENDERPATH_D3D11:
9124                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
9125                                                 break;
9126                                         }
9127                                         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
9128                                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9129                                         r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9130                                 }
9131                         }
9132
9133                         // copy view into the screen texture
9134                         R_Mesh_CopyToTexture(r_bloomstate.texture_screen, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
9135                         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9136                 }
9137                 else if (!r_bloomstate.texture_bloom)
9138                 {
9139                         // we may still have to do view tint...
9140                         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9141                         {
9142                                 // apply a color tint to the whole view
9143                                 R_ResetViewRendering2D();
9144                                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9145                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9146                                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9147                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9148                                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9149                         }
9150                         break; // no screen processing, no bloom, skip it
9151                 }
9152
9153                 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
9154                 {
9155                         // render simple bloom effect
9156                         // copy the screen and shrink it and darken it for the bloom process
9157                         R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
9158                         // make the bloom texture
9159                         R_Bloom_MakeTexture();
9160                 }
9161
9162 #if _MSC_VER >= 1400
9163 #define sscanf sscanf_s
9164 #endif
9165                 memset(uservecs, 0, sizeof(uservecs));
9166                 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
9167                 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
9168                 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
9169                 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
9170
9171                 R_ResetViewRendering2D();
9172                 GL_Color(1, 1, 1, 1);
9173                 GL_BlendFunc(GL_ONE, GL_ZERO);
9174
9175                 switch(vid.renderpath)
9176                 {
9177                 case RENDERPATH_GL20:
9178                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9179                         R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
9180                         if (r_glsl_permutation->loc_Texture_First      >= 0) R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
9181                         if (r_glsl_permutation->loc_Texture_Second     >= 0) R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
9182                         if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
9183                         if (r_glsl_permutation->loc_ViewTintColor      >= 0) qglUniform4fARB(r_glsl_permutation->loc_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9184                         if (r_glsl_permutation->loc_PixelSize          >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9185                         if (r_glsl_permutation->loc_UserVec1           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9186                         if (r_glsl_permutation->loc_UserVec2           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9187                         if (r_glsl_permutation->loc_UserVec3           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9188                         if (r_glsl_permutation->loc_UserVec4           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9189                         if (r_glsl_permutation->loc_Saturation         >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
9190                         if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
9191                         if (r_glsl_permutation->loc_BloomColorSubtract    >= 0) qglUniform4fARB(r_glsl_permutation->loc_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9192                         break;
9193                 case RENDERPATH_CGGL:
9194 #ifdef SUPPORTCG
9195                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9196                         R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
9197                         if (r_cg_permutation->fp_Texture_First     ) CG_BindTexture(r_cg_permutation->fp_Texture_First     , r_bloomstate.texture_screen);CHECKCGERROR
9198                         if (r_cg_permutation->fp_Texture_Second    ) CG_BindTexture(r_cg_permutation->fp_Texture_Second    , r_bloomstate.texture_bloom );CHECKCGERROR
9199                         if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps       );CHECKCGERROR
9200                         if (r_cg_permutation->fp_ViewTintColor     ) cgGLSetParameter4f(     r_cg_permutation->fp_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);CHECKCGERROR
9201                         if (r_cg_permutation->fp_PixelSize         ) cgGLSetParameter2f(     r_cg_permutation->fp_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
9202                         if (r_cg_permutation->fp_UserVec1          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);CHECKCGERROR
9203                         if (r_cg_permutation->fp_UserVec2          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);CHECKCGERROR
9204                         if (r_cg_permutation->fp_UserVec3          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);CHECKCGERROR
9205                         if (r_cg_permutation->fp_UserVec4          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);CHECKCGERROR
9206                         if (r_cg_permutation->fp_Saturation        ) cgGLSetParameter1f(     r_cg_permutation->fp_Saturation        , r_glsl_saturation.value);CHECKCGERROR
9207                         if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
9208                         if (r_cg_permutation->fp_BloomColorSubtract   ) cgGLSetParameter4f(r_cg_permutation->fp_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9209 #endif
9210                         break;
9211                 case RENDERPATH_D3D9:
9212 #ifdef SUPPORTD3D
9213                         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
9214                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9215                         R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
9216                         R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
9217                         R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
9218                         R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
9219                         hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor        , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9220                         hlslPSSetParameter2f(D3DPSREGISTER_PixelSize            , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9221                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec1             , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9222                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec2             , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9223                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec3             , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9224                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec4             , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9225                         hlslPSSetParameter1f(D3DPSREGISTER_Saturation           , r_glsl_saturation.value);
9226                         hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
9227                         hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9228 #endif
9229                         break;
9230                 case RENDERPATH_D3D10:
9231                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9232                         break;
9233                 case RENDERPATH_D3D11:
9234                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9235                         break;
9236                 default:
9237                         break;
9238                 }
9239                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9240                 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9241                 break;
9242         case RENDERPATH_GL13:
9243         case RENDERPATH_GL11:
9244                 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9245                 {
9246                         // apply a color tint to the whole view
9247                         R_ResetViewRendering2D();
9248                         GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9249                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9250                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9251                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9252                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9253                 }
9254                 break;
9255         }
9256 }
9257
9258 matrix4x4_t r_waterscrollmatrix;
9259
9260 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
9261 {
9262         if (r_refdef.fog_density)
9263         {
9264                 r_refdef.fogcolor[0] = r_refdef.fog_red;
9265                 r_refdef.fogcolor[1] = r_refdef.fog_green;
9266                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
9267
9268                 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
9269                 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
9270                 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
9271                 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
9272
9273                 {
9274                         vec3_t fogvec;
9275                         VectorCopy(r_refdef.fogcolor, fogvec);
9276                         //   color.rgb *= ContrastBoost * SceneBrightness;
9277                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
9278                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
9279                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
9280                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
9281                 }
9282         }
9283 }
9284
9285 void R_UpdateVariables(void)
9286 {
9287         R_Textures_Frame();
9288
9289         r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
9290
9291         r_refdef.farclip = r_farclip_base.value;
9292         if (r_refdef.scene.worldmodel)
9293                 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
9294         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
9295
9296         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
9297                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
9298         r_refdef.polygonfactor = 0;
9299         r_refdef.polygonoffset = 0;
9300         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9301         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9302
9303         r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
9304         r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
9305         r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
9306         r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
9307         r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
9308         if (FAKELIGHT_ENABLED)
9309         {
9310                 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
9311         }
9312         if (r_showsurfaces.integer)
9313         {
9314                 r_refdef.scene.rtworld = false;
9315                 r_refdef.scene.rtworldshadows = false;
9316                 r_refdef.scene.rtdlight = false;
9317                 r_refdef.scene.rtdlightshadows = false;
9318                 r_refdef.lightmapintensity = 0;
9319         }
9320
9321         if (gamemode == GAME_NEHAHRA)
9322         {
9323                 if (gl_fogenable.integer)
9324                 {
9325                         r_refdef.oldgl_fogenable = true;
9326                         r_refdef.fog_density = gl_fogdensity.value;
9327                         r_refdef.fog_red = gl_fogred.value;
9328                         r_refdef.fog_green = gl_foggreen.value;
9329                         r_refdef.fog_blue = gl_fogblue.value;
9330                         r_refdef.fog_alpha = 1;
9331                         r_refdef.fog_start = 0;
9332                         r_refdef.fog_end = gl_skyclip.value;
9333                         r_refdef.fog_height = 1<<30;
9334                         r_refdef.fog_fadedepth = 128;
9335                 }
9336                 else if (r_refdef.oldgl_fogenable)
9337                 {
9338                         r_refdef.oldgl_fogenable = false;
9339                         r_refdef.fog_density = 0;
9340                         r_refdef.fog_red = 0;
9341                         r_refdef.fog_green = 0;
9342                         r_refdef.fog_blue = 0;
9343                         r_refdef.fog_alpha = 0;
9344                         r_refdef.fog_start = 0;
9345                         r_refdef.fog_end = 0;
9346                         r_refdef.fog_height = 1<<30;
9347                         r_refdef.fog_fadedepth = 128;
9348                 }
9349         }
9350
9351         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
9352         r_refdef.fog_start = max(0, r_refdef.fog_start);
9353         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
9354
9355         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
9356
9357         if (r_refdef.fog_density && r_drawfog.integer)
9358         {
9359                 r_refdef.fogenabled = true;
9360                 // this is the point where the fog reaches 0.9986 alpha, which we
9361                 // consider a good enough cutoff point for the texture
9362                 // (0.9986 * 256 == 255.6)
9363                 if (r_fog_exp2.integer)
9364                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
9365                 else
9366                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
9367                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
9368                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
9369                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
9370                 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
9371                         R_BuildFogHeightTexture();
9372                 // fog color was already set
9373                 // update the fog texture
9374                 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
9375                         R_BuildFogTexture();
9376                 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
9377                 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
9378         }
9379         else
9380                 r_refdef.fogenabled = false;
9381
9382         switch(vid.renderpath)
9383         {
9384         case RENDERPATH_GL20:
9385         case RENDERPATH_CGGL:
9386         case RENDERPATH_D3D9:
9387         case RENDERPATH_D3D10:
9388         case RENDERPATH_D3D11:
9389                 if(v_glslgamma.integer && !vid_gammatables_trivial)
9390                 {
9391                         if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
9392                         {
9393                                 // build GLSL gamma texture
9394 #define RAMPWIDTH 256
9395                                 unsigned short ramp[RAMPWIDTH * 3];
9396                                 unsigned char rampbgr[RAMPWIDTH][4];
9397                                 int i;
9398
9399                                 r_texture_gammaramps_serial = vid_gammatables_serial;
9400
9401                                 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
9402                                 for(i = 0; i < RAMPWIDTH; ++i)
9403                                 {
9404                                         rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9405                                         rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9406                                         rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
9407                                         rampbgr[i][3] = 0;
9408                                 }
9409                                 if (r_texture_gammaramps)
9410                                 {
9411                                         R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
9412                                 }
9413                                 else
9414                                 {
9415                                         r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
9416                                 }
9417                         }
9418                 }
9419                 else
9420                 {
9421                         // remove GLSL gamma texture
9422                 }
9423                 break;
9424         case RENDERPATH_GL13:
9425         case RENDERPATH_GL11:
9426                 break;
9427         }
9428 }
9429
9430 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
9431 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
9432 /*
9433 ================
9434 R_SelectScene
9435 ================
9436 */
9437 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
9438         if( scenetype != r_currentscenetype ) {
9439                 // store the old scenetype
9440                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
9441                 r_currentscenetype = scenetype;
9442                 // move in the new scene
9443                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
9444         }
9445 }
9446
9447 /*
9448 ================
9449 R_GetScenePointer
9450 ================
9451 */
9452 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
9453 {
9454         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
9455         if( scenetype == r_currentscenetype ) {
9456                 return &r_refdef.scene;
9457         } else {
9458                 return &r_scenes_store[ scenetype ];
9459         }
9460 }
9461
9462 /*
9463 ================
9464 R_RenderView
9465 ================
9466 */
9467 void R_RenderView(void)
9468 {
9469         if (r_timereport_active)
9470                 R_TimeReport("start");
9471         r_textureframe++; // used only by R_GetCurrentTexture
9472         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
9473
9474         if (!r_drawentities.integer)
9475                 r_refdef.scene.numentities = 0;
9476
9477         R_AnimCache_ClearCache();
9478         R_FrameData_NewFrame();
9479
9480         if (r_refdef.view.isoverlay)
9481         {
9482                 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
9483                 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
9484                 R_TimeReport("depthclear");
9485
9486                 r_refdef.view.showdebug = false;
9487
9488                 r_waterstate.enabled = false;
9489                 r_waterstate.numwaterplanes = 0;
9490
9491                 R_RenderScene();
9492
9493                 CHECKGLERROR
9494                 return;
9495         }
9496
9497         if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
9498                 return; //Host_Error ("R_RenderView: NULL worldmodel");
9499
9500         r_refdef.view.colorscale = r_hdr_scenebrightness.value;
9501
9502         R_RenderView_UpdateViewVectors();
9503
9504         R_Shadow_UpdateWorldLightSelection();
9505
9506         R_Bloom_StartFrame();
9507         R_Water_StartFrame();
9508
9509         CHECKGLERROR
9510         if (r_timereport_active)
9511                 R_TimeReport("viewsetup");
9512
9513         R_ResetViewRendering3D();
9514
9515         if (r_refdef.view.clear || r_refdef.fogenabled)
9516         {
9517                 R_ClearScreen(r_refdef.fogenabled);
9518                 if (r_timereport_active)
9519                         R_TimeReport("viewclear");
9520         }
9521         r_refdef.view.clear = true;
9522
9523         // this produces a bloom texture to be used in R_BlendView() later
9524         if (r_hdr.integer && r_bloomstate.bloomwidth)
9525         {
9526                 R_HDR_RenderBloomTexture();
9527                 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
9528                 r_textureframe++; // used only by R_GetCurrentTexture
9529         }
9530
9531         r_refdef.view.showdebug = true;
9532
9533         R_View_Update();
9534         if (r_timereport_active)
9535                 R_TimeReport("visibility");
9536
9537         r_waterstate.numwaterplanes = 0;
9538         if (r_waterstate.enabled)
9539                 R_RenderWaterPlanes();
9540
9541         R_RenderScene();
9542         r_waterstate.numwaterplanes = 0;
9543
9544         R_BlendView();
9545         if (r_timereport_active)
9546                 R_TimeReport("blendview");
9547
9548         GL_Scissor(0, 0, vid.width, vid.height);
9549         GL_ScissorTest(false);
9550
9551         CHECKGLERROR
9552 }
9553
9554 void R_RenderWaterPlanes(void)
9555 {
9556         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
9557         {
9558                 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
9559                 if (r_timereport_active)
9560                         R_TimeReport("waterworld");
9561         }
9562
9563         // don't let sound skip if going slow
9564         if (r_refdef.scene.extraupdate)
9565                 S_ExtraUpdate ();
9566
9567         R_DrawModelsAddWaterPlanes();
9568         if (r_timereport_active)
9569                 R_TimeReport("watermodels");
9570
9571         if (r_waterstate.numwaterplanes)
9572         {
9573                 R_Water_ProcessPlanes();
9574                 if (r_timereport_active)
9575                         R_TimeReport("waterscenes");
9576         }
9577 }
9578
9579 extern void R_DrawLightningBeams (void);
9580 extern void VM_CL_AddPolygonsToMeshQueue (void);
9581 extern void R_DrawPortals (void);
9582 extern cvar_t cl_locs_show;
9583 static void R_DrawLocs(void);
9584 static void R_DrawEntityBBoxes(void);
9585 static void R_DrawModelDecals(void);
9586 extern void R_DrawModelShadows(void);
9587 extern void R_DrawModelShadowMaps(void);
9588 extern cvar_t cl_decals_newsystem;
9589 extern qboolean r_shadow_usingdeferredprepass;
9590 void R_RenderScene(void)
9591 {
9592         qboolean shadowmapping = false;
9593
9594         if (r_timereport_active)
9595                 R_TimeReport("beginscene");
9596
9597         r_refdef.stats.renders++;
9598
9599         R_UpdateFogColor();
9600
9601         // don't let sound skip if going slow
9602         if (r_refdef.scene.extraupdate)
9603                 S_ExtraUpdate ();
9604
9605         R_MeshQueue_BeginScene();
9606
9607         R_SkyStartFrame();
9608
9609         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
9610
9611         if (r_timereport_active)
9612                 R_TimeReport("skystartframe");
9613
9614         if (cl.csqc_vidvars.drawworld)
9615         {
9616                 // don't let sound skip if going slow
9617                 if (r_refdef.scene.extraupdate)
9618                         S_ExtraUpdate ();
9619
9620                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
9621                 {
9622                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
9623                         if (r_timereport_active)
9624                                 R_TimeReport("worldsky");
9625                 }
9626
9627                 if (R_DrawBrushModelsSky() && r_timereport_active)
9628                         R_TimeReport("bmodelsky");
9629
9630                 if (skyrendermasked && skyrenderlater)
9631                 {
9632                         // we have to force off the water clipping plane while rendering sky
9633                         R_SetupView(false);
9634                         R_Sky();
9635                         R_SetupView(true);
9636                         if (r_timereport_active)
9637                                 R_TimeReport("sky");
9638                 }
9639         }
9640
9641         R_AnimCache_CacheVisibleEntities();
9642         if (r_timereport_active)
9643                 R_TimeReport("animation");
9644
9645         R_Shadow_PrepareLights();
9646         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
9647                 R_Shadow_PrepareModelShadows();
9648         if (r_timereport_active)
9649                 R_TimeReport("preparelights");
9650
9651         if (R_Shadow_ShadowMappingEnabled())
9652                 shadowmapping = true;
9653
9654         if (r_shadow_usingdeferredprepass)
9655                 R_Shadow_DrawPrepass();
9656
9657         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
9658         {
9659                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
9660                 if (r_timereport_active)
9661                         R_TimeReport("worlddepth");
9662         }
9663         if (r_depthfirst.integer >= 2)
9664         {
9665                 R_DrawModelsDepth();
9666                 if (r_timereport_active)
9667                         R_TimeReport("modeldepth");
9668         }
9669
9670         if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
9671         {
9672                 R_DrawModelShadowMaps();
9673                 R_ResetViewRendering3D();
9674                 // don't let sound skip if going slow
9675                 if (r_refdef.scene.extraupdate)
9676                         S_ExtraUpdate ();
9677         }
9678
9679         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
9680         {
9681                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
9682                 if (r_timereport_active)
9683                         R_TimeReport("world");
9684         }
9685
9686         // don't let sound skip if going slow
9687         if (r_refdef.scene.extraupdate)
9688                 S_ExtraUpdate ();
9689
9690         R_DrawModels();
9691         if (r_timereport_active)
9692                 R_TimeReport("models");
9693
9694         // don't let sound skip if going slow
9695         if (r_refdef.scene.extraupdate)
9696                 S_ExtraUpdate ();
9697
9698         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9699         {
9700                 R_DrawModelShadows();
9701                 R_ResetViewRendering3D();
9702                 // don't let sound skip if going slow
9703                 if (r_refdef.scene.extraupdate)
9704                         S_ExtraUpdate ();
9705         }
9706
9707         if (!r_shadow_usingdeferredprepass)
9708         {
9709                 R_Shadow_DrawLights();
9710                 if (r_timereport_active)
9711                         R_TimeReport("rtlights");
9712         }
9713
9714         // don't let sound skip if going slow
9715         if (r_refdef.scene.extraupdate)
9716                 S_ExtraUpdate ();
9717
9718         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9719         {
9720                 R_DrawModelShadows();
9721                 R_ResetViewRendering3D();
9722                 // don't let sound skip if going slow
9723                 if (r_refdef.scene.extraupdate)
9724                         S_ExtraUpdate ();
9725         }
9726
9727         if (cl.csqc_vidvars.drawworld)
9728         {
9729                 if (cl_decals_newsystem.integer)
9730                 {
9731                         R_DrawModelDecals();
9732                         if (r_timereport_active)
9733                                 R_TimeReport("modeldecals");
9734                 }
9735                 else
9736                 {
9737                         R_DrawDecals();
9738                         if (r_timereport_active)
9739                                 R_TimeReport("decals");
9740                 }
9741
9742                 R_DrawParticles();
9743                 if (r_timereport_active)
9744                         R_TimeReport("particles");
9745
9746                 R_DrawExplosions();
9747                 if (r_timereport_active)
9748                         R_TimeReport("explosions");
9749
9750                 R_DrawLightningBeams();
9751                 if (r_timereport_active)
9752                         R_TimeReport("lightning");
9753         }
9754
9755         VM_CL_AddPolygonsToMeshQueue();
9756
9757         if (r_refdef.view.showdebug)
9758         {
9759                 if (cl_locs_show.integer)
9760                 {
9761                         R_DrawLocs();
9762                         if (r_timereport_active)
9763                                 R_TimeReport("showlocs");
9764                 }
9765
9766                 if (r_drawportals.integer)
9767                 {
9768                         R_DrawPortals();
9769                         if (r_timereport_active)
9770                                 R_TimeReport("portals");
9771                 }
9772
9773                 if (r_showbboxes.value > 0)
9774                 {
9775                         R_DrawEntityBBoxes();
9776                         if (r_timereport_active)
9777                                 R_TimeReport("bboxes");
9778                 }
9779         }
9780
9781         R_MeshQueue_RenderTransparent();
9782         if (r_timereport_active)
9783                 R_TimeReport("drawtrans");
9784
9785         if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value != 0 || r_showcollisionbrushes.value > 0))
9786         {
9787                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9788                 if (r_timereport_active)
9789                         R_TimeReport("worlddebug");
9790                 R_DrawModelsDebug();
9791                 if (r_timereport_active)
9792                         R_TimeReport("modeldebug");
9793         }
9794
9795         if (cl.csqc_vidvars.drawworld)
9796         {
9797                 R_Shadow_DrawCoronas();
9798                 if (r_timereport_active)
9799                         R_TimeReport("coronas");
9800         }
9801
9802 #if 0
9803         {
9804                 GL_DepthTest(false);
9805                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
9806                 GL_Color(1, 1, 1, 1);
9807                 qglBegin(GL_POLYGON);
9808                 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
9809                 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
9810                 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
9811                 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
9812                 qglEnd();
9813                 qglBegin(GL_POLYGON);
9814                 qglVertex3f(r_refdef.view.frustumcorner[0][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[0][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[0][2] + 1000 * r_refdef.view.forward[2]);
9815                 qglVertex3f(r_refdef.view.frustumcorner[1][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[1][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[1][2] + 1000 * r_refdef.view.forward[2]);
9816                 qglVertex3f(r_refdef.view.frustumcorner[3][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[3][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[3][2] + 1000 * r_refdef.view.forward[2]);
9817                 qglVertex3f(r_refdef.view.frustumcorner[2][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[2][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[2][2] + 1000 * r_refdef.view.forward[2]);
9818                 qglEnd();
9819                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
9820         }
9821 #endif
9822
9823         // don't let sound skip if going slow
9824         if (r_refdef.scene.extraupdate)
9825                 S_ExtraUpdate ();
9826
9827         R_ResetViewRendering2D();
9828 }
9829
9830 static const unsigned short bboxelements[36] =
9831 {
9832         5, 1, 3, 5, 3, 7,
9833         6, 2, 0, 6, 0, 4,
9834         7, 3, 2, 7, 2, 6,
9835         4, 0, 1, 4, 1, 5,
9836         4, 5, 7, 4, 7, 6,
9837         1, 0, 2, 1, 2, 3,
9838 };
9839
9840 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9841 {
9842         int i;
9843         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9844
9845         RSurf_ActiveWorldEntity();
9846
9847         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9848         GL_DepthMask(false);
9849         GL_DepthRange(0, 1);
9850         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9851         R_Mesh_ResetTextureState();
9852
9853         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9854         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9855         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9856         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9857         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9858         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9859         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9860         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9861         R_FillColors(color4f, 8, cr, cg, cb, ca);
9862         if (r_refdef.fogenabled)
9863         {
9864                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9865                 {
9866                         f1 = RSurf_FogVertex(v);
9867                         f2 = 1 - f1;
9868                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9869                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9870                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9871                 }
9872         }
9873         R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
9874         R_Mesh_ResetTextureState();
9875         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9876         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
9877 }
9878
9879 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9880 {
9881         int i;
9882         float color[4];
9883         prvm_edict_t *edict;
9884         prvm_prog_t *prog_save = prog;
9885
9886         // this function draws bounding boxes of server entities
9887         if (!sv.active)
9888                 return;
9889
9890         GL_CullFace(GL_NONE);
9891         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9892
9893         prog = 0;
9894         SV_VM_Begin();
9895         for (i = 0;i < numsurfaces;i++)
9896         {
9897                 edict = PRVM_EDICT_NUM(surfacelist[i]);
9898                 switch ((int)edict->fields.server->solid)
9899                 {
9900                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
9901                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
9902                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
9903                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9904                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
9905                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
9906                 }
9907                 color[3] *= r_showbboxes.value;
9908                 color[3] = bound(0, color[3], 1);
9909                 GL_DepthTest(!r_showdisabledepthtest.integer);
9910                 GL_CullFace(r_refdef.view.cullface_front);
9911                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9912         }
9913         SV_VM_End();
9914         prog = prog_save;
9915 }
9916
9917 static void R_DrawEntityBBoxes(void)
9918 {
9919         int i;
9920         prvm_edict_t *edict;
9921         vec3_t center;
9922         prvm_prog_t *prog_save = prog;
9923
9924         // this function draws bounding boxes of server entities
9925         if (!sv.active)
9926                 return;
9927
9928         prog = 0;
9929         SV_VM_Begin();
9930         for (i = 0;i < prog->num_edicts;i++)
9931         {
9932                 edict = PRVM_EDICT_NUM(i);
9933                 if (edict->priv.server->free)
9934                         continue;
9935                 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9936                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9937                         continue;
9938                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9939                         continue;
9940                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9941                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9942         }
9943         SV_VM_End();
9944         prog = prog_save;
9945 }
9946
9947 static const int nomodelelement3i[24] =
9948 {
9949         5, 2, 0,
9950         5, 1, 2,
9951         5, 0, 3,
9952         5, 3, 1,
9953         0, 2, 4,
9954         2, 1, 4,
9955         3, 0, 4,
9956         1, 3, 4
9957 };
9958
9959 static const unsigned short nomodelelement3s[24] =
9960 {
9961         5, 2, 0,
9962         5, 1, 2,
9963         5, 0, 3,
9964         5, 3, 1,
9965         0, 2, 4,
9966         2, 1, 4,
9967         3, 0, 4,
9968         1, 3, 4
9969 };
9970
9971 static const float nomodelvertex3f[6*3] =
9972 {
9973         -16,   0,   0,
9974          16,   0,   0,
9975           0, -16,   0,
9976           0,  16,   0,
9977           0,   0, -16,
9978           0,   0,  16
9979 };
9980
9981 static const float nomodelcolor4f[6*4] =
9982 {
9983         0.0f, 0.0f, 0.5f, 1.0f,
9984         0.0f, 0.0f, 0.5f, 1.0f,
9985         0.0f, 0.5f, 0.0f, 1.0f,
9986         0.0f, 0.5f, 0.0f, 1.0f,
9987         0.5f, 0.0f, 0.0f, 1.0f,
9988         0.5f, 0.0f, 0.0f, 1.0f
9989 };
9990
9991 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9992 {
9993         int i;
9994         float f1, f2, *c;
9995         float color4f[6*4];
9996
9997         RSurf_ActiveCustomEntity(&ent->matrix, &ent->inversematrix, ent->flags, ent->shadertime, ent->colormod[0], ent->colormod[1], ent->colormod[2], ent->alpha, 6, nomodelvertex3f, NULL, NULL, NULL, NULL, nomodelcolor4f, 8, nomodelelement3i, nomodelelement3s, false, false);
9998
9999         // this is only called once per entity so numsurfaces is always 1, and
10000         // surfacelist is always {0}, so this code does not handle batches
10001
10002         if (rsurface.ent_flags & RENDER_ADDITIVE)
10003         {
10004                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
10005                 GL_DepthMask(false);
10006         }
10007         else if (rsurface.colormod[3] < 1)
10008         {
10009                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
10010                 GL_DepthMask(false);
10011         }
10012         else
10013         {
10014                 GL_BlendFunc(GL_ONE, GL_ZERO);
10015                 GL_DepthMask(true);
10016         }
10017         GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
10018         GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
10019         GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
10020         GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
10021         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
10022         memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
10023         for (i = 0, c = color4f;i < 6;i++, c += 4)
10024         {
10025                 c[0] *= rsurface.colormod[0];
10026                 c[1] *= rsurface.colormod[1];
10027                 c[2] *= rsurface.colormod[2];
10028                 c[3] *= rsurface.colormod[3];
10029         }
10030         if (r_refdef.fogenabled)
10031         {
10032                 for (i = 0, c = color4f;i < 6;i++, c += 4)
10033                 {
10034                         f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
10035                         f2 = 1 - f1;
10036                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
10037                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
10038                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
10039                 }
10040         }
10041         R_Mesh_ResetTextureState();
10042         R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
10043         R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
10044 }
10045
10046 void R_DrawNoModel(entity_render_t *ent)
10047 {
10048         vec3_t org;
10049         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
10050         if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
10051                 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
10052         else
10053                 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
10054 }
10055
10056 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
10057 {
10058         vec3_t right1, right2, diff, normal;
10059
10060         VectorSubtract (org2, org1, normal);
10061
10062         // calculate 'right' vector for start
10063         VectorSubtract (r_refdef.view.origin, org1, diff);
10064         CrossProduct (normal, diff, right1);
10065         VectorNormalize (right1);
10066
10067         // calculate 'right' vector for end
10068         VectorSubtract (r_refdef.view.origin, org2, diff);
10069         CrossProduct (normal, diff, right2);
10070         VectorNormalize (right2);
10071
10072         vert[ 0] = org1[0] + width * right1[0];
10073         vert[ 1] = org1[1] + width * right1[1];
10074         vert[ 2] = org1[2] + width * right1[2];
10075         vert[ 3] = org1[0] - width * right1[0];
10076         vert[ 4] = org1[1] - width * right1[1];
10077         vert[ 5] = org1[2] - width * right1[2];
10078         vert[ 6] = org2[0] - width * right2[0];
10079         vert[ 7] = org2[1] - width * right2[1];
10080         vert[ 8] = org2[2] - width * right2[2];
10081         vert[ 9] = org2[0] + width * right2[0];
10082         vert[10] = org2[1] + width * right2[1];
10083         vert[11] = org2[2] + width * right2[2];
10084 }
10085
10086 void R_CalcSprite_Vertex3f(float *vertex3f, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2)
10087 {
10088         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
10089         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
10090         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
10091         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
10092         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
10093         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
10094         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
10095         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
10096         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
10097         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
10098         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
10099         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
10100 }
10101
10102 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
10103 {
10104         int i;
10105         float *vertex3f;
10106         float v[3];
10107         VectorSet(v, x, y, z);
10108         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
10109                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
10110                         break;
10111         if (i == mesh->numvertices)
10112         {
10113                 if (mesh->numvertices < mesh->maxvertices)
10114                 {
10115                         VectorCopy(v, vertex3f);
10116                         mesh->numvertices++;
10117                 }
10118                 return mesh->numvertices;
10119         }
10120         else
10121                 return i;
10122 }
10123
10124 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
10125 {
10126         int i;
10127         int *e, element[3];
10128         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
10129         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
10130         e = mesh->element3i + mesh->numtriangles * 3;
10131         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
10132         {
10133                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
10134                 if (mesh->numtriangles < mesh->maxtriangles)
10135                 {
10136                         *e++ = element[0];
10137                         *e++ = element[1];
10138                         *e++ = element[2];
10139                         mesh->numtriangles++;
10140                 }
10141                 element[1] = element[2];
10142         }
10143 }
10144
10145 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
10146 {
10147         int i;
10148         int *e, element[3];
10149         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
10150         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
10151         e = mesh->element3i + mesh->numtriangles * 3;
10152         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
10153         {
10154                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
10155                 if (mesh->numtriangles < mesh->maxtriangles)
10156                 {
10157                         *e++ = element[0];
10158                         *e++ = element[1];
10159                         *e++ = element[2];
10160                         mesh->numtriangles++;
10161                 }
10162                 element[1] = element[2];
10163         }
10164 }
10165
10166 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
10167 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
10168 {
10169         int planenum, planenum2;
10170         int w;
10171         int tempnumpoints;
10172         mplane_t *plane, *plane2;
10173         double maxdist;
10174         double temppoints[2][256*3];
10175         // figure out how large a bounding box we need to properly compute this brush
10176         maxdist = 0;
10177         for (w = 0;w < numplanes;w++)
10178                 maxdist = max(maxdist, fabs(planes[w].dist));
10179         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
10180         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
10181         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
10182         {
10183                 w = 0;
10184                 tempnumpoints = 4;
10185                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
10186                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
10187                 {
10188                         if (planenum2 == planenum)
10189                                 continue;
10190                         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);
10191                         w = !w;
10192                 }
10193                 if (tempnumpoints < 3)
10194                         continue;
10195                 // generate elements forming a triangle fan for this polygon
10196                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
10197         }
10198 }
10199
10200 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)
10201 {
10202         texturelayer_t *layer;
10203         layer = t->currentlayers + t->currentnumlayers++;
10204         layer->type = type;
10205         layer->depthmask = depthmask;
10206         layer->blendfunc1 = blendfunc1;
10207         layer->blendfunc2 = blendfunc2;
10208         layer->texture = texture;
10209         layer->texmatrix = *matrix;
10210         layer->color[0] = r;
10211         layer->color[1] = g;
10212         layer->color[2] = b;
10213         layer->color[3] = a;
10214 }
10215
10216 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
10217 {
10218         if(parms[0] == 0 && parms[1] == 0)
10219                 return false;
10220         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10221                 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
10222                         return false;
10223         return true;
10224 }
10225
10226 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
10227 {
10228         double index, f;
10229         index = parms[2] + r_refdef.scene.time * parms[3];
10230         index -= floor(index);
10231         switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
10232         {
10233         default:
10234         case Q3WAVEFUNC_NONE:
10235         case Q3WAVEFUNC_NOISE:
10236         case Q3WAVEFUNC_COUNT:
10237                 f = 0;
10238                 break;
10239         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
10240         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
10241         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
10242         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
10243         case Q3WAVEFUNC_TRIANGLE:
10244                 index *= 4;
10245                 f = index - floor(index);
10246                 if (index < 1)
10247                         f = f;
10248                 else if (index < 2)
10249                         f = 1 - f;
10250                 else if (index < 3)
10251                         f = -f;
10252                 else
10253                         f = -(1 - f);
10254                 break;
10255         }
10256         f = parms[0] + parms[1] * f;
10257         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10258                 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
10259         return (float) f;
10260 }
10261
10262 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
10263 {
10264         int w, h, idx;
10265         float f;
10266         float tcmat[12];
10267         matrix4x4_t matrix, temp;
10268         switch(tcmod->tcmod)
10269         {
10270                 case Q3TCMOD_COUNT:
10271                 case Q3TCMOD_NONE:
10272                         if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10273                                 matrix = r_waterscrollmatrix;
10274                         else
10275                                 matrix = identitymatrix;
10276                         break;
10277                 case Q3TCMOD_ENTITYTRANSLATE:
10278                         // this is used in Q3 to allow the gamecode to control texcoord
10279                         // scrolling on the entity, which is not supported in darkplaces yet.
10280                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
10281                         break;
10282                 case Q3TCMOD_ROTATE:
10283                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
10284                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
10285                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
10286                         break;
10287                 case Q3TCMOD_SCALE:
10288                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
10289                         break;
10290                 case Q3TCMOD_SCROLL:
10291                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
10292                         break;
10293                 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
10294                         w = (int) tcmod->parms[0];
10295                         h = (int) tcmod->parms[1];
10296                         f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
10297                         f = f - floor(f);
10298                         idx = (int) floor(f * w * h);
10299                         Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
10300                         break;
10301                 case Q3TCMOD_STRETCH:
10302                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
10303                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
10304                         break;
10305                 case Q3TCMOD_TRANSFORM:
10306                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
10307                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
10308                         VectorSet(tcmat +  6, 0                   , 0                , 1);
10309                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
10310                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
10311                         break;
10312                 case Q3TCMOD_TURBULENT:
10313                         // this is handled in the RSurf_PrepareVertices function
10314                         matrix = identitymatrix;
10315                         break;
10316         }
10317         temp = *texmatrix;
10318         Matrix4x4_Concat(texmatrix, &matrix, &temp);
10319 }
10320
10321 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
10322 {
10323         int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
10324         char name[MAX_QPATH];
10325         skinframe_t *skinframe;
10326         unsigned char pixels[296*194];
10327         strlcpy(cache->name, skinname, sizeof(cache->name));
10328         dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
10329         if (developer_loading.integer)
10330                 Con_Printf("loading %s\n", name);
10331         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
10332         if (!skinframe || !skinframe->base)
10333         {
10334                 unsigned char *f;
10335                 fs_offset_t filesize;
10336                 skinframe = NULL;
10337                 f = FS_LoadFile(name, tempmempool, true, &filesize);
10338                 if (f)
10339                 {
10340                         if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
10341                                 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
10342                         Mem_Free(f);
10343                 }
10344         }
10345         cache->skinframe = skinframe;
10346 }
10347
10348 texture_t *R_GetCurrentTexture(texture_t *t)
10349 {
10350         int i;
10351         const entity_render_t *ent = rsurface.entity;
10352         dp_model_t *model = ent->model;
10353         q3shaderinfo_layer_tcmod_t *tcmod;
10354
10355         if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
10356                 return t->currentframe;
10357         t->update_lastrenderframe = r_textureframe;
10358         t->update_lastrenderentity = (void *)ent;
10359
10360         if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
10361                 t->camera_entity = ent->entitynumber;
10362         else
10363                 t->camera_entity = 0;
10364
10365         // switch to an alternate material if this is a q1bsp animated material
10366         {
10367                 texture_t *texture = t;
10368                 int s = rsurface.ent_skinnum;
10369                 if ((unsigned int)s >= (unsigned int)model->numskins)
10370                         s = 0;
10371                 if (model->skinscenes)
10372                 {
10373                         if (model->skinscenes[s].framecount > 1)
10374                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
10375                         else
10376                                 s = model->skinscenes[s].firstframe;
10377                 }
10378                 if (s > 0)
10379                         t = t + s * model->num_surfaces;
10380                 if (t->animated)
10381                 {
10382                         // use an alternate animation if the entity's frame is not 0,
10383                         // and only if the texture has an alternate animation
10384                         if (rsurface.ent_alttextures && t->anim_total[1])
10385                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
10386                         else
10387                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
10388                 }
10389                 texture->currentframe = t;
10390         }
10391
10392         // update currentskinframe to be a qw skin or animation frame
10393         if (rsurface.ent_qwskin >= 0)
10394         {
10395                 i = rsurface.ent_qwskin;
10396                 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
10397                 {
10398                         r_qwskincache_size = cl.maxclients;
10399                         if (r_qwskincache)
10400                                 Mem_Free(r_qwskincache);
10401                         r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
10402                 }
10403                 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
10404                         R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
10405                 t->currentskinframe = r_qwskincache[i].skinframe;
10406                 if (t->currentskinframe == NULL)
10407                         t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10408         }
10409         else if (t->numskinframes >= 2)
10410                 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10411         if (t->backgroundnumskinframes >= 2)
10412                 t->backgroundcurrentskinframe = t->backgroundskinframes[(unsigned int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
10413
10414         t->currentmaterialflags = t->basematerialflags;
10415         t->currentalpha = rsurface.colormod[3];
10416         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
10417                 t->currentalpha *= r_wateralpha.value;
10418         if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
10419                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
10420         if(!r_waterstate.enabled || r_refdef.view.isoverlay)
10421                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
10422         if (!(rsurface.ent_flags & RENDER_LIGHT))
10423                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
10424         else if (FAKELIGHT_ENABLED)
10425         {
10426                         // no modellight if using fakelight for the map
10427         }
10428         else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
10429         {
10430                 // pick a model lighting mode
10431                 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
10432                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
10433                 else
10434                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
10435         }
10436         if (rsurface.ent_flags & RENDER_ADDITIVE)
10437                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10438         else if (t->currentalpha < 1)
10439                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10440         if (rsurface.ent_flags & RENDER_DOUBLESIDED)
10441                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
10442         if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
10443                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
10444         if (t->backgroundnumskinframes)
10445                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
10446         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
10447         {
10448                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
10449                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
10450         }
10451         else
10452                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
10453         if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
10454                 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
10455
10456         // there is no tcmod
10457         if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10458         {
10459                 t->currenttexmatrix = r_waterscrollmatrix;
10460                 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
10461         }
10462         else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
10463         {
10464                 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
10465                 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
10466         }
10467
10468         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10469                 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
10470         for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10471                 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
10472
10473         t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
10474         if (t->currentskinframe->qpixels)
10475                 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
10476         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
10477         if (!t->basetexture)
10478                 t->basetexture = r_texture_notexture;
10479         t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
10480         t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
10481         t->nmaptexture = t->currentskinframe->nmap;
10482         if (!t->nmaptexture)
10483                 t->nmaptexture = r_texture_blanknormalmap;
10484         t->glosstexture = r_texture_black;
10485         t->glowtexture = t->currentskinframe->glow;
10486         t->fogtexture = t->currentskinframe->fog;
10487         t->reflectmasktexture = t->currentskinframe->reflect;
10488         if (t->backgroundnumskinframes)
10489         {
10490                 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
10491                 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
10492                 t->backgroundglosstexture = r_texture_black;
10493                 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
10494                 if (!t->backgroundnmaptexture)
10495                         t->backgroundnmaptexture = r_texture_blanknormalmap;
10496         }
10497         else
10498         {
10499                 t->backgroundbasetexture = r_texture_white;
10500                 t->backgroundnmaptexture = r_texture_blanknormalmap;
10501                 t->backgroundglosstexture = r_texture_black;
10502                 t->backgroundglowtexture = NULL;
10503         }
10504         t->specularpower = r_shadow_glossexponent.value;
10505         // TODO: store reference values for these in the texture?
10506         t->specularscale = 0;
10507         if (r_shadow_gloss.integer > 0)
10508         {
10509                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
10510                 {
10511                         if (r_shadow_glossintensity.value > 0)
10512                         {
10513                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
10514                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
10515                                 t->specularscale = r_shadow_glossintensity.value;
10516                         }
10517                 }
10518                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
10519                 {
10520                         t->glosstexture = r_texture_white;
10521                         t->backgroundglosstexture = r_texture_white;
10522                         t->specularscale = r_shadow_gloss2intensity.value;
10523                         t->specularpower = r_shadow_gloss2exponent.value;
10524                 }
10525         }
10526         t->specularscale *= t->specularscalemod;
10527         t->specularpower *= t->specularpowermod;
10528
10529         // lightmaps mode looks bad with dlights using actual texturing, so turn
10530         // off the colormap and glossmap, but leave the normalmap on as it still
10531         // accurately represents the shading involved
10532         if (gl_lightmaps.integer)
10533         {
10534                 t->basetexture = r_texture_grey128;
10535                 t->pantstexture = r_texture_black;
10536                 t->shirttexture = r_texture_black;
10537                 t->nmaptexture = r_texture_blanknormalmap;
10538                 t->glosstexture = r_texture_black;
10539                 t->glowtexture = NULL;
10540                 t->fogtexture = NULL;
10541                 t->reflectmasktexture = NULL;
10542                 t->backgroundbasetexture = NULL;
10543                 t->backgroundnmaptexture = r_texture_blanknormalmap;
10544                 t->backgroundglosstexture = r_texture_black;
10545                 t->backgroundglowtexture = NULL;
10546                 t->specularscale = 0;
10547                 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
10548         }
10549
10550         Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
10551         VectorClear(t->dlightcolor);
10552         t->currentnumlayers = 0;
10553         if (t->currentmaterialflags & MATERIALFLAG_WALL)
10554         {
10555                 int blendfunc1, blendfunc2;
10556                 qboolean depthmask;
10557                 if (t->currentmaterialflags & MATERIALFLAG_ADD)
10558                 {
10559                         blendfunc1 = GL_SRC_ALPHA;
10560                         blendfunc2 = GL_ONE;
10561                 }
10562                 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
10563                 {
10564                         blendfunc1 = GL_SRC_ALPHA;
10565                         blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
10566                 }
10567                 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10568                 {
10569                         blendfunc1 = t->customblendfunc[0];
10570                         blendfunc2 = t->customblendfunc[1];
10571                 }
10572                 else
10573                 {
10574                         blendfunc1 = GL_ONE;
10575                         blendfunc2 = GL_ZERO;
10576                 }
10577                 // don't colormod evilblend textures
10578                 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
10579                         VectorSet(t->lightmapcolor, 1, 1, 1);
10580                 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
10581                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10582                 {
10583                         // fullbright is not affected by r_refdef.lightmapintensity
10584                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
10585                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10586                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10587                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10588                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10589                 }
10590                 else
10591                 {
10592                         vec3_t ambientcolor;
10593                         float colorscale;
10594                         // set the color tint used for lights affecting this surface
10595                         VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
10596                         colorscale = 2;
10597                         // q3bsp has no lightmap updates, so the lightstylevalue that
10598                         // would normally be baked into the lightmap must be
10599                         // applied to the color
10600                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
10601                         if (model->type == mod_brushq3)
10602                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
10603                         colorscale *= r_refdef.lightmapintensity;
10604                         VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
10605                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
10606                         // basic lit geometry
10607                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
10608                         // add pants/shirt if needed
10609                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10610                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2]  * t->lightmapcolor[2], t->lightmapcolor[3]);
10611                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10612                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10613                         // now add ambient passes if needed
10614                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
10615                         {
10616                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
10617                                 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10618                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * ambientcolor[0], rsurface.colormap_pantscolor[1] * ambientcolor[1], rsurface.colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
10619                                 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10620                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * ambientcolor[0], rsurface.colormap_shirtcolor[1] * ambientcolor[1], rsurface.colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
10621                         }
10622                 }
10623                 if (t->glowtexture != NULL && !gl_lightmaps.integer)
10624                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->glowtexture, &t->currenttexmatrix, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2], t->lightmapcolor[3]);
10625                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
10626                 {
10627                         // if this is opaque use alpha blend which will darken the earlier
10628                         // passes cheaply.
10629                         //
10630                         // if this is an alpha blended material, all the earlier passes
10631                         // were darkened by fog already, so we only need to add the fog
10632                         // color ontop through the fog mask texture
10633                         //
10634                         // if this is an additive blended material, all the earlier passes
10635                         // were darkened by fog already, and we should not add fog color
10636                         // (because the background was not darkened, there is no fog color
10637                         // that was lost behind it).
10638                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->fogtexture, &t->currenttexmatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->lightmapcolor[3]);
10639                 }
10640         }
10641
10642         return t->currentframe;
10643 }
10644
10645 rsurfacestate_t rsurface;
10646
10647 void R_Mesh_ResizeArrays(int newvertices)
10648 {
10649         unsigned char *base;
10650         size_t size;
10651         if (rsurface.array_size >= newvertices)
10652                 return;
10653         if (rsurface.array_base)
10654                 Mem_Free(rsurface.array_base);
10655         rsurface.array_size = (newvertices + 1023) & ~1023;
10656         size = 0;
10657         size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10658         size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10659         size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10660         size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10661         size += rsurface.array_size * sizeof(float[3]);
10662         size += rsurface.array_size * sizeof(float[3]);
10663         size += rsurface.array_size * sizeof(float[3]);
10664         size += rsurface.array_size * sizeof(float[3]);
10665         size += rsurface.array_size * sizeof(float[3]);
10666         size += rsurface.array_size * sizeof(float[3]);
10667         size += rsurface.array_size * sizeof(float[3]);
10668         size += rsurface.array_size * sizeof(float[3]);
10669         size += rsurface.array_size * sizeof(float[4]);
10670         size += rsurface.array_size * sizeof(float[2]);
10671         size += rsurface.array_size * sizeof(float[2]);
10672         size += rsurface.array_size * sizeof(float[4]);
10673         size += rsurface.array_size * sizeof(int[3]);
10674         size += rsurface.array_size * sizeof(unsigned short[3]);
10675         rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
10676         rsurface.array_modelvertexmesh         = (r_vertexmesh_t     *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10677         rsurface.array_batchvertexmesh         = (r_vertexmesh_t     *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10678         rsurface.array_modelvertexposition     = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10679         rsurface.array_batchvertexposition     = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10680         rsurface.array_modelvertex3f           = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10681         rsurface.array_modelsvector3f          = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10682         rsurface.array_modeltvector3f          = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10683         rsurface.array_modelnormal3f           = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10684         rsurface.array_batchvertex3f           = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10685         rsurface.array_batchsvector3f          = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10686         rsurface.array_batchtvector3f          = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10687         rsurface.array_batchnormal3f           = (float              *)base;base += rsurface.array_size * sizeof(float[3]);
10688         rsurface.array_batchlightmapcolor4f    = (float              *)base;base += rsurface.array_size * sizeof(float[4]);
10689         rsurface.array_batchtexcoordtexture2f  = (float              *)base;base += rsurface.array_size * sizeof(float[2]);
10690         rsurface.array_batchtexcoordlightmap2f = (float              *)base;base += rsurface.array_size * sizeof(float[2]);
10691         rsurface.array_passcolor4f             = (float              *)base;base += rsurface.array_size * sizeof(float[4]);
10692         rsurface.array_batchelement3i          = (int                *)base;base += rsurface.array_size * sizeof(int[3]);
10693         rsurface.array_batchelement3s          = (unsigned short     *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
10694 }
10695
10696 void RSurf_ActiveWorldEntity(void)
10697 {
10698         dp_model_t *model = r_refdef.scene.worldmodel;
10699         //if (rsurface.entity == r_refdef.scene.worldentity)
10700         //      return;
10701         rsurface.entity = r_refdef.scene.worldentity;
10702         rsurface.skeleton = NULL;
10703         memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
10704         rsurface.ent_skinnum = 0;
10705         rsurface.ent_qwskin = -1;
10706         rsurface.ent_shadertime = 0;
10707         rsurface.ent_flags = r_refdef.scene.worldentity->flags;
10708         if (rsurface.array_size < model->surfmesh.num_vertices)
10709                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10710         rsurface.matrix = identitymatrix;
10711         rsurface.inversematrix = identitymatrix;
10712         rsurface.matrixscale = 1;
10713         rsurface.inversematrixscale = 1;
10714         R_EntityMatrix(&identitymatrix);
10715         VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
10716         Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
10717         rsurface.fograngerecip = r_refdef.fograngerecip;
10718         rsurface.fogheightfade = r_refdef.fogheightfade;
10719         rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
10720         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10721         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10722         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10723         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10724         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10725         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10726         VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
10727         rsurface.colormod[3] = 1;
10728         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
10729         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10730         rsurface.frameblend[0].lerp = 1;
10731         rsurface.ent_alttextures = false;
10732         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10733         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10734         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10735         rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10736         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10737         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10738         rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10739         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10740         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10741         rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10742         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10743         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10744         rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10745         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10746         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10747         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10748         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10749         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10750         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10751         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10752         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10753         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10754         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10755         rsurface.modelelement3i = model->surfmesh.data_element3i;
10756         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10757         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10758         rsurface.modelelement3s = model->surfmesh.data_element3s;
10759         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10760         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10761         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10762         rsurface.modelnumvertices = model->surfmesh.num_vertices;
10763         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10764         rsurface.modelsurfaces = model->data_surfaces;
10765         rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10766         rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10767         rsurface.modelvertexposition = model->surfmesh.vertexposition;
10768         rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10769         rsurface.modelgeneratedvertex = false;
10770         rsurface.batchgeneratedvertex = false;
10771         rsurface.batchfirstvertex = 0;
10772         rsurface.batchnumvertices = 0;
10773         rsurface.batchfirsttriangle = 0;
10774         rsurface.batchnumtriangles = 0;
10775         rsurface.batchvertex3f  = NULL;
10776         rsurface.batchvertex3f_vertexbuffer = NULL;
10777         rsurface.batchvertex3f_bufferoffset = 0;
10778         rsurface.batchsvector3f = NULL;
10779         rsurface.batchsvector3f_vertexbuffer = NULL;
10780         rsurface.batchsvector3f_bufferoffset = 0;
10781         rsurface.batchtvector3f = NULL;
10782         rsurface.batchtvector3f_vertexbuffer = NULL;
10783         rsurface.batchtvector3f_bufferoffset = 0;
10784         rsurface.batchnormal3f  = NULL;
10785         rsurface.batchnormal3f_vertexbuffer = NULL;
10786         rsurface.batchnormal3f_bufferoffset = 0;
10787         rsurface.batchlightmapcolor4f = NULL;
10788         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10789         rsurface.batchlightmapcolor4f_bufferoffset = 0;
10790         rsurface.batchtexcoordtexture2f = NULL;
10791         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10792         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10793         rsurface.batchtexcoordlightmap2f = NULL;
10794         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10795         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10796         rsurface.batchvertexmesh = NULL;
10797         rsurface.batchvertexmeshbuffer = NULL;
10798         rsurface.batchvertexposition = NULL;
10799         rsurface.batchvertexpositionbuffer = NULL;
10800         rsurface.batchelement3i = NULL;
10801         rsurface.batchelement3i_indexbuffer = NULL;
10802         rsurface.batchelement3i_bufferoffset = 0;
10803         rsurface.batchelement3s = NULL;
10804         rsurface.batchelement3s_indexbuffer = NULL;
10805         rsurface.batchelement3s_bufferoffset = 0;
10806         rsurface.passcolor4f = NULL;
10807         rsurface.passcolor4f_vertexbuffer = NULL;
10808         rsurface.passcolor4f_bufferoffset = 0;
10809 }
10810
10811 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
10812 {
10813         dp_model_t *model = ent->model;
10814         //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
10815         //      return;
10816         rsurface.entity = (entity_render_t *)ent;
10817         rsurface.skeleton = ent->skeleton;
10818         memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
10819         rsurface.ent_skinnum = ent->skinnum;
10820         rsurface.ent_qwskin = (ent->entitynumber <= cl.maxclients && ent->entitynumber >= 1 && cls.protocol == PROTOCOL_QUAKEWORLD && cl.scores[ent->entitynumber - 1].qw_skin[0] && !strcmp(ent->model->name, "progs/player.mdl")) ? (ent->entitynumber - 1) : -1;
10821         rsurface.ent_shadertime = ent->shadertime;
10822         rsurface.ent_flags = ent->flags;
10823         if (rsurface.array_size < model->surfmesh.num_vertices)
10824                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10825         rsurface.matrix = ent->matrix;
10826         rsurface.inversematrix = ent->inversematrix;
10827         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10828         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10829         R_EntityMatrix(&rsurface.matrix);
10830         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10831         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10832         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10833         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10834         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10835         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10836         VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10837         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10838         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10839         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10840         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10841         VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10842         rsurface.colormod[3] = ent->alpha;
10843         VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10844         memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10845         rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10846         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10847         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10848         if (ent->model->brush.submodel && !prepass)
10849         {
10850                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10851                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10852         }
10853         if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10854         {
10855                 if (ent->animcache_vertex3f && !r_framedata_failed)
10856                 {
10857                         rsurface.modelvertex3f = ent->animcache_vertex3f;
10858                         rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10859                         rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10860                         rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10861                         rsurface.modelvertexmesh = ent->animcache_vertexmesh;
10862                         rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
10863                         rsurface.modelvertexposition = ent->animcache_vertexposition;
10864                         rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
10865                 }
10866                 else if (wanttangents)
10867                 {
10868                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10869                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10870                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10871                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10872                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
10873                         rsurface.modelvertexmesh = NULL;
10874                         rsurface.modelvertexmeshbuffer = NULL;
10875                         rsurface.modelvertexposition = NULL;
10876                         rsurface.modelvertexpositionbuffer = NULL;
10877                 }
10878                 else if (wantnormals)
10879                 {
10880                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10881                         rsurface.modelsvector3f = NULL;
10882                         rsurface.modeltvector3f = NULL;
10883                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10884                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
10885                         rsurface.modelvertexmesh = NULL;
10886                         rsurface.modelvertexmeshbuffer = NULL;
10887                         rsurface.modelvertexposition = NULL;
10888                         rsurface.modelvertexpositionbuffer = NULL;
10889                 }
10890                 else
10891                 {
10892                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10893                         rsurface.modelsvector3f = NULL;
10894                         rsurface.modeltvector3f = NULL;
10895                         rsurface.modelnormal3f = NULL;
10896                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
10897                         rsurface.modelvertexmesh = NULL;
10898                         rsurface.modelvertexmeshbuffer = NULL;
10899                         rsurface.modelvertexposition = NULL;
10900                         rsurface.modelvertexpositionbuffer = NULL;
10901                 }
10902                 rsurface.modelvertex3f_vertexbuffer = 0;
10903                 rsurface.modelvertex3f_bufferoffset = 0;
10904                 rsurface.modelsvector3f_vertexbuffer = 0;
10905                 rsurface.modelsvector3f_bufferoffset = 0;
10906                 rsurface.modeltvector3f_vertexbuffer = 0;
10907                 rsurface.modeltvector3f_bufferoffset = 0;
10908                 rsurface.modelnormal3f_vertexbuffer = 0;
10909                 rsurface.modelnormal3f_bufferoffset = 0;
10910                 rsurface.modelgeneratedvertex = true;
10911         }
10912         else
10913         {
10914                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10915                 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10916                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10917                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10918                 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10919                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10920                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10921                 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10922                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10923                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10924                 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10925                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10926                 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10927                 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10928                 rsurface.modelvertexposition = model->surfmesh.vertexposition;
10929                 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10930                 rsurface.modelgeneratedvertex = false;
10931         }
10932         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10933         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10934         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10935         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10936         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10937         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10938         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10939         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10940         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10941         rsurface.modelelement3i = model->surfmesh.data_element3i;
10942         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10943         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10944         rsurface.modelelement3s = model->surfmesh.data_element3s;
10945         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10946         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10947         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10948         rsurface.modelnumvertices = model->surfmesh.num_vertices;
10949         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10950         rsurface.modelsurfaces = model->data_surfaces;
10951         rsurface.batchgeneratedvertex = false;
10952         rsurface.batchfirstvertex = 0;
10953         rsurface.batchnumvertices = 0;
10954         rsurface.batchfirsttriangle = 0;
10955         rsurface.batchnumtriangles = 0;
10956         rsurface.batchvertex3f  = NULL;
10957         rsurface.batchvertex3f_vertexbuffer = NULL;
10958         rsurface.batchvertex3f_bufferoffset = 0;
10959         rsurface.batchsvector3f = NULL;
10960         rsurface.batchsvector3f_vertexbuffer = NULL;
10961         rsurface.batchsvector3f_bufferoffset = 0;
10962         rsurface.batchtvector3f = NULL;
10963         rsurface.batchtvector3f_vertexbuffer = NULL;
10964         rsurface.batchtvector3f_bufferoffset = 0;
10965         rsurface.batchnormal3f  = NULL;
10966         rsurface.batchnormal3f_vertexbuffer = NULL;
10967         rsurface.batchnormal3f_bufferoffset = 0;
10968         rsurface.batchlightmapcolor4f = NULL;
10969         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10970         rsurface.batchlightmapcolor4f_bufferoffset = 0;
10971         rsurface.batchtexcoordtexture2f = NULL;
10972         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10973         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10974         rsurface.batchtexcoordlightmap2f = NULL;
10975         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10976         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10977         rsurface.batchvertexmesh = NULL;
10978         rsurface.batchvertexmeshbuffer = NULL;
10979         rsurface.batchvertexposition = NULL;
10980         rsurface.batchvertexpositionbuffer = NULL;
10981         rsurface.batchelement3i = NULL;
10982         rsurface.batchelement3i_indexbuffer = NULL;
10983         rsurface.batchelement3i_bufferoffset = 0;
10984         rsurface.batchelement3s = NULL;
10985         rsurface.batchelement3s_indexbuffer = NULL;
10986         rsurface.batchelement3s_bufferoffset = 0;
10987         rsurface.passcolor4f = NULL;
10988         rsurface.passcolor4f_vertexbuffer = NULL;
10989         rsurface.passcolor4f_bufferoffset = 0;
10990 }
10991
10992 void RSurf_ActiveCustomEntity(const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, int entflags, double shadertime, float r, float g, float b, float a, int numvertices, const float *vertex3f, const float *texcoord2f, const float *normal3f, const float *svector3f, const float *tvector3f, const float *color4f, int numtriangles, const int *element3i, const unsigned short *element3s, qboolean wantnormals, qboolean wanttangents)
10993 {
10994         int i;
10995
10996         rsurface.entity = r_refdef.scene.worldentity;
10997         rsurface.skeleton = NULL;
10998         rsurface.ent_skinnum = 0;
10999         rsurface.ent_qwskin = -1;
11000         rsurface.ent_shadertime = shadertime;
11001         rsurface.ent_flags = entflags;
11002         rsurface.modelnumvertices = numvertices;
11003         rsurface.modelnumtriangles = numtriangles;
11004         if (rsurface.array_size < rsurface.modelnumvertices)
11005                 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
11006         rsurface.matrix = *matrix;
11007         rsurface.inversematrix = *inversematrix;
11008         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
11009         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
11010         R_EntityMatrix(&rsurface.matrix);
11011         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
11012         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
11013         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
11014         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
11015         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
11016         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
11017         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
11018         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
11019         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
11020         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
11021         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
11022         Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
11023         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
11024         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
11025         rsurface.frameblend[0].lerp = 1;
11026         rsurface.ent_alttextures = false;
11027         rsurface.basepolygonfactor = r_refdef.polygonfactor;
11028         rsurface.basepolygonoffset = r_refdef.polygonoffset;
11029         if (wanttangents)
11030         {
11031                 rsurface.modelvertex3f = vertex3f;
11032                 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
11033                 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
11034                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
11035         }
11036         else if (wantnormals)
11037         {
11038                 rsurface.modelvertex3f = vertex3f;
11039                 rsurface.modelsvector3f = NULL;
11040                 rsurface.modeltvector3f = NULL;
11041                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
11042         }
11043         else
11044         {
11045                 rsurface.modelvertex3f = vertex3f;
11046                 rsurface.modelsvector3f = NULL;
11047                 rsurface.modeltvector3f = NULL;
11048                 rsurface.modelnormal3f = NULL;
11049         }
11050         rsurface.modelvertexmesh = NULL;
11051         rsurface.modelvertexmeshbuffer = NULL;
11052         rsurface.modelvertexposition = NULL;
11053         rsurface.modelvertexpositionbuffer = NULL;
11054         rsurface.modelvertex3f_vertexbuffer = 0;
11055         rsurface.modelvertex3f_bufferoffset = 0;
11056         rsurface.modelsvector3f_vertexbuffer = 0;
11057         rsurface.modelsvector3f_bufferoffset = 0;
11058         rsurface.modeltvector3f_vertexbuffer = 0;
11059         rsurface.modeltvector3f_bufferoffset = 0;
11060         rsurface.modelnormal3f_vertexbuffer = 0;
11061         rsurface.modelnormal3f_bufferoffset = 0;
11062         rsurface.modelgeneratedvertex = true;
11063         rsurface.modellightmapcolor4f  = color4f;
11064         rsurface.modellightmapcolor4f_vertexbuffer = 0;
11065         rsurface.modellightmapcolor4f_bufferoffset = 0;
11066         rsurface.modeltexcoordtexture2f  = texcoord2f;
11067         rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
11068         rsurface.modeltexcoordtexture2f_bufferoffset = 0;
11069         rsurface.modeltexcoordlightmap2f  = NULL;
11070         rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
11071         rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
11072         rsurface.modelelement3i = element3i;
11073         rsurface.modelelement3i_indexbuffer = NULL;
11074         rsurface.modelelement3i_bufferoffset = 0;
11075         rsurface.modelelement3s = element3s;
11076         rsurface.modelelement3s_indexbuffer = NULL;
11077         rsurface.modelelement3s_bufferoffset = 0;
11078         rsurface.modellightmapoffsets = NULL;
11079         rsurface.modelsurfaces = NULL;
11080         rsurface.batchgeneratedvertex = false;
11081         rsurface.batchfirstvertex = 0;
11082         rsurface.batchnumvertices = 0;
11083         rsurface.batchfirsttriangle = 0;
11084         rsurface.batchnumtriangles = 0;
11085         rsurface.batchvertex3f  = NULL;
11086         rsurface.batchvertex3f_vertexbuffer = NULL;
11087         rsurface.batchvertex3f_bufferoffset = 0;
11088         rsurface.batchsvector3f = NULL;
11089         rsurface.batchsvector3f_vertexbuffer = NULL;
11090         rsurface.batchsvector3f_bufferoffset = 0;
11091         rsurface.batchtvector3f = NULL;
11092         rsurface.batchtvector3f_vertexbuffer = NULL;
11093         rsurface.batchtvector3f_bufferoffset = 0;
11094         rsurface.batchnormal3f  = NULL;
11095         rsurface.batchnormal3f_vertexbuffer = NULL;
11096         rsurface.batchnormal3f_bufferoffset = 0;
11097         rsurface.batchlightmapcolor4f = NULL;
11098         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11099         rsurface.batchlightmapcolor4f_bufferoffset = 0;
11100         rsurface.batchtexcoordtexture2f = NULL;
11101         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11102         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11103         rsurface.batchtexcoordlightmap2f = NULL;
11104         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11105         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11106         rsurface.batchvertexmesh = NULL;
11107         rsurface.batchvertexmeshbuffer = NULL;
11108         rsurface.batchvertexposition = NULL;
11109         rsurface.batchvertexpositionbuffer = NULL;
11110         rsurface.batchelement3i = NULL;
11111         rsurface.batchelement3i_indexbuffer = NULL;
11112         rsurface.batchelement3i_bufferoffset = 0;
11113         rsurface.batchelement3s = NULL;
11114         rsurface.batchelement3s_indexbuffer = NULL;
11115         rsurface.batchelement3s_bufferoffset = 0;
11116         rsurface.passcolor4f = NULL;
11117         rsurface.passcolor4f_vertexbuffer = NULL;
11118         rsurface.passcolor4f_bufferoffset = 0;
11119
11120         if (rsurface.modelnumvertices && rsurface.modelelement3i)
11121         {
11122                 if ((wantnormals || wanttangents) && !normal3f)
11123                 {
11124                         Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
11125                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
11126                 }
11127                 if (wanttangents && !svector3f)
11128                 {
11129                         Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
11130                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
11131                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
11132                 }
11133         }
11134
11135         // now convert arrays into vertexmesh structs
11136         for (i = 0;i < numvertices;i++)
11137         {
11138                 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
11139                 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
11140                 if (rsurface.modelsvector3f)
11141                         VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
11142                 if (rsurface.modeltvector3f)
11143                         VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
11144                 if (rsurface.modelnormal3f)
11145                         VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
11146                 if (rsurface.modellightmapcolor4f)
11147                         Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
11148                 if (rsurface.modeltexcoordtexture2f)
11149                         Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
11150                 if (rsurface.modeltexcoordlightmap2f)
11151                         Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
11152         }
11153 }
11154
11155 float RSurf_FogPoint(const float *v)
11156 {
11157         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
11158         float FogPlaneViewDist = r_refdef.fogplaneviewdist;
11159         float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
11160         float FogHeightFade = r_refdef.fogheightfade;
11161         float fogfrac;
11162         unsigned int fogmasktableindex;
11163         if (r_refdef.fogplaneviewabove)
11164                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
11165         else
11166                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
11167         fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
11168         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
11169 }
11170
11171 float RSurf_FogVertex(const float *v)
11172 {
11173         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
11174         float FogPlaneViewDist = rsurface.fogplaneviewdist;
11175         float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
11176         float FogHeightFade = rsurface.fogheightfade;
11177         float fogfrac;
11178         unsigned int fogmasktableindex;
11179         if (r_refdef.fogplaneviewabove)
11180                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
11181         else
11182                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
11183         fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
11184         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
11185 }
11186
11187 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
11188 {
11189         int i;
11190         for (i = 0;i < numelements;i++)
11191                 outelement3i[i] = inelement3i[i] + adjust;
11192 }
11193
11194 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
11195 extern cvar_t gl_vbo;
11196 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
11197 {
11198         int deformindex;
11199         int firsttriangle;
11200         int numtriangles;
11201         int firstvertex;
11202         int endvertex;
11203         int numvertices;
11204         int surfacefirsttriangle;
11205         int surfacenumtriangles;
11206         int surfacefirstvertex;
11207         int surfaceendvertex;
11208         int surfacenumvertices;
11209         int needsupdate;
11210         int i, j;
11211         qboolean gaps;
11212         qboolean dynamicvertex;
11213         float amplitude;
11214         float animpos;
11215         float scale;
11216         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
11217         float waveparms[4];
11218         q3shaderinfo_deform_t *deform;
11219         const msurface_t *surface, *firstsurface;
11220         r_vertexposition_t *vertexposition;
11221         r_vertexmesh_t *vertexmesh;
11222         if (!texturenumsurfaces)
11223                 return;
11224         // find vertex range of this surface batch
11225         gaps = false;
11226         firstsurface = texturesurfacelist[0];
11227         firsttriangle = firstsurface->num_firsttriangle;
11228         numtriangles = 0;
11229         firstvertex = endvertex = firstsurface->num_firstvertex;
11230         for (i = 0;i < texturenumsurfaces;i++)
11231         {
11232                 surface = texturesurfacelist[i];
11233                 if (surface != firstsurface + i)
11234                         gaps = true;
11235                 surfacefirstvertex = surface->num_firstvertex;
11236                 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
11237                 surfacenumtriangles = surface->num_triangles;
11238                 if (firstvertex > surfacefirstvertex)
11239                         firstvertex = surfacefirstvertex;
11240                 if (endvertex < surfaceendvertex)
11241                         endvertex = surfaceendvertex;
11242                 numtriangles += surfacenumtriangles;
11243         }
11244         if (!numtriangles)
11245                 return;
11246
11247         // we now know the vertex range used, and if there are any gaps in it
11248         rsurface.batchfirstvertex = firstvertex;
11249         rsurface.batchnumvertices = endvertex - firstvertex;
11250         rsurface.batchfirsttriangle = firsttriangle;
11251         rsurface.batchnumtriangles = numtriangles;
11252
11253         // this variable holds flags for which properties have been updated that
11254         // may require regenerating vertexmesh or vertexposition arrays...
11255         needsupdate = 0;
11256
11257         // check if any dynamic vertex processing must occur
11258         dynamicvertex = false;
11259
11260         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11261                 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
11262         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11263         {
11264                 switch (deform->deform)
11265                 {
11266                 default:
11267                 case Q3DEFORM_PROJECTIONSHADOW:
11268                 case Q3DEFORM_TEXT0:
11269                 case Q3DEFORM_TEXT1:
11270                 case Q3DEFORM_TEXT2:
11271                 case Q3DEFORM_TEXT3:
11272                 case Q3DEFORM_TEXT4:
11273                 case Q3DEFORM_TEXT5:
11274                 case Q3DEFORM_TEXT6:
11275                 case Q3DEFORM_TEXT7:
11276                 case Q3DEFORM_NONE:
11277                         break;
11278                 case Q3DEFORM_AUTOSPRITE:
11279                         dynamicvertex = true;
11280                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11281                         needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11282                         break;
11283                 case Q3DEFORM_AUTOSPRITE2:
11284                         dynamicvertex = true;
11285                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11286                         needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11287                         break;
11288                 case Q3DEFORM_NORMAL:
11289                         dynamicvertex = true;
11290                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11291                         needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11292                         break;
11293                 case Q3DEFORM_WAVE:
11294                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11295                                 break; // if wavefunc is a nop, ignore this transform
11296                         dynamicvertex = true;
11297                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11298                         needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11299                         break;
11300                 case Q3DEFORM_BULGE:
11301                         dynamicvertex = true;
11302                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11303                         needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11304                         break;
11305                 case Q3DEFORM_MOVE:
11306                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11307                                 break; // if wavefunc is a nop, ignore this transform
11308                         dynamicvertex = true;
11309                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11310                         needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
11311                         break;
11312                 }
11313         }
11314         switch(rsurface.texture->tcgen.tcgen)
11315         {
11316         default:
11317         case Q3TCGEN_TEXTURE:
11318                 break;
11319         case Q3TCGEN_LIGHTMAP:
11320                 dynamicvertex = true;
11321                 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
11322                 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
11323                 break;
11324         case Q3TCGEN_VECTOR:
11325                 dynamicvertex = true;
11326                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11327                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11328                 break;
11329         case Q3TCGEN_ENVIRONMENT:
11330                 dynamicvertex = true;
11331                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
11332                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11333                 break;
11334         }
11335         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11336         {
11337                 dynamicvertex = true;
11338                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11339                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11340         }
11341
11342         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11343         {
11344                 dynamicvertex = true;
11345                 batchneed |= BATCHNEED_NOGAPS;
11346                 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
11347         }
11348
11349         if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11350         {
11351                 dynamicvertex = true;
11352                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11353                 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
11354         }
11355
11356         if (dynamicvertex || gaps || rsurface.batchfirstvertex)
11357         {
11358                 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
11359                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)      batchneed |= BATCHNEED_ARRAY_VERTEX;
11360                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)      batchneed |= BATCHNEED_ARRAY_NORMAL;
11361                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)      batchneed |= BATCHNEED_ARRAY_VECTOR;
11362                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
11363                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)    batchneed |= BATCHNEED_ARRAY_TEXCOORD;
11364                 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP)    batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
11365         }
11366
11367         // when the model data has no vertex buffer (dynamic mesh), we need to
11368         // eliminate gaps
11369         if (!rsurface.modelvertexmeshbuffer)
11370                 batchneed |= BATCHNEED_NOGAPS;
11371
11372         // if needsupdate, we have to do a dynamic vertex batch for sure
11373         if (needsupdate & batchneed)
11374                 dynamicvertex = true;
11375
11376         // see if we need to build vertexmesh from arrays
11377         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11378                 dynamicvertex = true;
11379
11380         // see if we need to build vertexposition from arrays
11381         if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
11382                 dynamicvertex = true;
11383
11384         // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
11385         if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
11386                 dynamicvertex = true;
11387
11388         // if there is a chance of animated vertex colors, it's a dynamic batch
11389         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11390                 dynamicvertex = true;
11391
11392         rsurface.batchvertex3f = rsurface.modelvertex3f;
11393         rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
11394         rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
11395         rsurface.batchsvector3f = rsurface.modelsvector3f;
11396         rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
11397         rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
11398         rsurface.batchtvector3f = rsurface.modeltvector3f;
11399         rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
11400         rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
11401         rsurface.batchnormal3f = rsurface.modelnormal3f;
11402         rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
11403         rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
11404         rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
11405         rsurface.batchlightmapcolor4f_vertexbuffer  = rsurface.modellightmapcolor4f_vertexbuffer;
11406         rsurface.batchlightmapcolor4f_bufferoffset  = rsurface.modellightmapcolor4f_bufferoffset;
11407         rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
11408         rsurface.batchtexcoordtexture2f_vertexbuffer  = rsurface.modeltexcoordtexture2f_vertexbuffer;
11409         rsurface.batchtexcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
11410         rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
11411         rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
11412         rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
11413         rsurface.batchvertexposition = rsurface.modelvertexposition;
11414         rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
11415         rsurface.batchvertexmesh = rsurface.modelvertexmesh;
11416         rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
11417         rsurface.batchelement3i = rsurface.modelelement3i;
11418         rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
11419         rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
11420         rsurface.batchelement3s = rsurface.modelelement3s;
11421         rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
11422         rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
11423
11424         // if any dynamic vertex processing has to occur in software, we copy the
11425         // entire surface list together before processing to rebase the vertices
11426         // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
11427         //
11428         // if any gaps exist and we do not have a static vertex buffer, we have to
11429         // copy the surface list together to avoid wasting upload bandwidth on the
11430         // vertices in the gaps.
11431         //
11432         // if gaps exist and we have a static vertex buffer, we still have to
11433         // combine the index buffer ranges into one dynamic index buffer.
11434         //
11435         // in all cases we end up with data that can be drawn in one call.
11436
11437         if (!dynamicvertex)
11438         {
11439                 // static vertex data, just set pointers...
11440                 rsurface.batchgeneratedvertex = false;
11441                 // if there are gaps, we want to build a combined index buffer,
11442                 // otherwise use the original static buffer with an appropriate offset
11443                 if (gaps)
11444                 {
11445                         firsttriangle = 0;
11446                         numtriangles = 0;
11447                         for (i = 0;i < texturenumsurfaces;i++)
11448                         {
11449                                 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11450                                 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11451                                 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
11452                                 numtriangles += surfacenumtriangles;
11453                         }
11454                         rsurface.batchelement3i = rsurface.array_batchelement3i;
11455                         rsurface.batchelement3i_indexbuffer = NULL;
11456                         rsurface.batchelement3i_bufferoffset = 0;
11457                         rsurface.batchelement3s = NULL;
11458                         rsurface.batchelement3s_indexbuffer = NULL;
11459                         rsurface.batchelement3s_bufferoffset = 0;
11460                         if (endvertex <= 65536)
11461                         {
11462                                 rsurface.batchelement3s = rsurface.array_batchelement3s;
11463                                 for (i = 0;i < numtriangles*3;i++)
11464                                         rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11465                         }
11466                         rsurface.batchfirsttriangle = firsttriangle;
11467                         rsurface.batchnumtriangles = numtriangles;
11468                 }
11469                 return;
11470         }
11471
11472         // something needs software processing, do it for real...
11473         // we only directly handle interleaved array data in this case...
11474         rsurface.batchgeneratedvertex = true;
11475
11476         // now copy the vertex data into a combined array and make an index array
11477         // (this is what Quake3 does all the time)
11478         //if (gaps || rsurface.batchfirstvertex)
11479         {
11480                 rsurface.batchvertexposition = NULL;
11481                 rsurface.batchvertexpositionbuffer = NULL;
11482                 rsurface.batchvertexmesh = NULL;
11483                 rsurface.batchvertexmeshbuffer = NULL;
11484                 rsurface.batchvertex3f = NULL;
11485                 rsurface.batchvertex3f_vertexbuffer = NULL;
11486                 rsurface.batchvertex3f_bufferoffset = 0;
11487                 rsurface.batchsvector3f = NULL;
11488                 rsurface.batchsvector3f_vertexbuffer = NULL;
11489                 rsurface.batchsvector3f_bufferoffset = 0;
11490                 rsurface.batchtvector3f = NULL;
11491                 rsurface.batchtvector3f_vertexbuffer = NULL;
11492                 rsurface.batchtvector3f_bufferoffset = 0;
11493                 rsurface.batchnormal3f = NULL;
11494                 rsurface.batchnormal3f_vertexbuffer = NULL;
11495                 rsurface.batchnormal3f_bufferoffset = 0;
11496                 rsurface.batchlightmapcolor4f = NULL;
11497                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11498                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11499                 rsurface.batchtexcoordtexture2f = NULL;
11500                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11501                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11502                 rsurface.batchtexcoordlightmap2f = NULL;
11503                 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11504                 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11505                 rsurface.batchelement3i = rsurface.array_batchelement3i;
11506                 rsurface.batchelement3i_indexbuffer = NULL;
11507                 rsurface.batchelement3i_bufferoffset = 0;
11508                 rsurface.batchelement3s = NULL;
11509                 rsurface.batchelement3s_indexbuffer = NULL;
11510                 rsurface.batchelement3s_bufferoffset = 0;
11511                 // we'll only be setting up certain arrays as needed
11512                 if (batchneed & BATCHNEED_VERTEXPOSITION)
11513                         rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11514                 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11515                         rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11516                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11517                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11518                 if (batchneed & BATCHNEED_ARRAY_NORMAL)
11519                         rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11520                 if (batchneed & BATCHNEED_ARRAY_VECTOR)
11521                 {
11522                         rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11523                         rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11524                 }
11525                 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
11526                         rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11527                 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
11528                         rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11529                 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
11530                         rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
11531                 numvertices = 0;
11532                 numtriangles = 0;
11533                 for (i = 0;i < texturenumsurfaces;i++)
11534                 {
11535                         surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
11536                         surfacenumvertices = texturesurfacelist[i]->num_vertices;
11537                         surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11538                         surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11539                         // copy only the data requested
11540                         if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
11541                                 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
11542                         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
11543                                 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
11544                         if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
11545                         {
11546                                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11547                                         memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11548                                 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
11549                                         memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11550                                 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
11551                                 {
11552                                         memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11553                                         memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11554                                 }
11555                                 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
11556                                         memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
11557                                 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
11558                                         memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11559                                 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
11560                                         memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11561                         }
11562                         RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
11563                         numvertices += surfacenumvertices;
11564                         numtriangles += surfacenumtriangles;
11565                 }
11566
11567                 // generate a 16bit index array as well if possible
11568                 // (in general, dynamic batches fit)
11569                 if (numvertices <= 65536)
11570                 {
11571                         rsurface.batchelement3s = rsurface.array_batchelement3s;
11572                         for (i = 0;i < numtriangles*3;i++)
11573                                 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11574                 }
11575
11576                 // since we've copied everything, the batch now starts at 0
11577                 rsurface.batchfirstvertex = 0;
11578                 rsurface.batchnumvertices = numvertices;
11579                 rsurface.batchfirsttriangle = 0;
11580                 rsurface.batchnumtriangles = numtriangles;
11581         }
11582
11583         // q1bsp surfaces rendered in vertex color mode have to have colors
11584         // calculated based on lightstyles
11585         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11586         {
11587                 // generate color arrays for the surfaces in this list
11588                 int c[4];
11589                 int scale;
11590                 int size3;
11591                 const int *offsets;
11592                 const unsigned char *lm;
11593                 numvertices = 0;
11594                 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11595                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11596                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11597                 for (i = 0;i < texturenumsurfaces;i++)
11598                 {
11599                         surface = texturesurfacelist[i];
11600                         offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
11601                         surfacenumvertices = surface->num_vertices;
11602                         if (surface->lightmapinfo->samples)
11603                         {
11604                                 for (j = 0;j < surfacenumvertices;j++)
11605                                 {
11606                                         lm = surface->lightmapinfo->samples + offsets[j];
11607                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
11608                                         VectorScale(lm, scale, c);
11609                                         if (surface->lightmapinfo->styles[1] != 255)
11610                                         {
11611                                                 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11612                                                 lm += size3;
11613                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
11614                                                 VectorMA(c, scale, lm, c);
11615                                                 if (surface->lightmapinfo->styles[2] != 255)
11616                                                 {
11617                                                         lm += size3;
11618                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
11619                                                         VectorMA(c, scale, lm, c);
11620                                                         if (surface->lightmapinfo->styles[3] != 255)
11621                                                         {
11622                                                                 lm += size3;
11623                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
11624                                                                 VectorMA(c, scale, lm, c);
11625                                                         }
11626                                                 }
11627                                         }
11628                                         c[0] >>= 15;
11629                                         c[1] >>= 15;
11630                                         c[2] >>= 15;
11631                                         Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, min(c[0], 255) * (1.0f / 255.0f), min(c[1], 255) * (1.0f / 255.0f), min(c[2], 255) * (1.0f / 255.0f), 1);
11632                                         numvertices++;
11633                                 }
11634                         }
11635                         else
11636                         {
11637                                 for (j = 0;j < surfacenumvertices;j++)
11638                                 {
11639                                         Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
11640                                         numvertices++;
11641                                 }
11642                         }
11643                 }
11644         }
11645
11646         // if vertices are deformed (sprite flares and things in maps, possibly
11647         // water waves, bulges and other deformations), modify the copied vertices
11648         // in place
11649         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11650         {
11651                 switch (deform->deform)
11652                 {
11653                 default:
11654                 case Q3DEFORM_PROJECTIONSHADOW:
11655                 case Q3DEFORM_TEXT0:
11656                 case Q3DEFORM_TEXT1:
11657                 case Q3DEFORM_TEXT2:
11658                 case Q3DEFORM_TEXT3:
11659                 case Q3DEFORM_TEXT4:
11660                 case Q3DEFORM_TEXT5:
11661                 case Q3DEFORM_TEXT6:
11662                 case Q3DEFORM_TEXT7:
11663                 case Q3DEFORM_NONE:
11664                         break;
11665                 case Q3DEFORM_AUTOSPRITE:
11666                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11667                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11668                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11669                         VectorNormalize(newforward);
11670                         VectorNormalize(newright);
11671                         VectorNormalize(newup);
11672                         // a single autosprite surface can contain multiple sprites...
11673                         for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11674                         {
11675                                 VectorClear(center);
11676                                 for (i = 0;i < 4;i++)
11677                                         VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11678                                 VectorScale(center, 0.25f, center);
11679                                 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
11680                                 VectorCopy(rsurface.batchsvector3f + 3*j, right);
11681                                 VectorCopy(rsurface.batchtvector3f + 3*j, up);
11682                                 for (i = 0;i < 4;i++)
11683                                 {
11684                                         VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
11685                                         VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
11686                                 }
11687                         }
11688                         // if we get here, BATCHNEED_ARRAY_NORMAL and BATCHNEED_ARRAY_VECTOR are in batchneed, so no need to check
11689                         Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11690                         Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
11691                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11692                         rsurface.batchvertex3f_vertexbuffer = NULL;
11693                         rsurface.batchvertex3f_bufferoffset = 0;
11694                         rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11695                         rsurface.batchsvector3f_vertexbuffer = NULL;
11696                         rsurface.batchsvector3f_bufferoffset = 0;
11697                         rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11698                         rsurface.batchtvector3f_vertexbuffer = NULL;
11699                         rsurface.batchtvector3f_bufferoffset = 0;
11700                         rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11701                         rsurface.batchnormal3f_vertexbuffer = NULL;
11702                         rsurface.batchnormal3f_bufferoffset = 0;
11703                         break;
11704                 case Q3DEFORM_AUTOSPRITE2:
11705                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11706                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11707                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11708                         VectorNormalize(newforward);
11709                         VectorNormalize(newright);
11710                         VectorNormalize(newup);
11711                         {
11712                                 const float *v1, *v2;
11713                                 vec3_t start, end;
11714                                 float f, l;
11715                                 struct
11716                                 {
11717                                         float length2;
11718                                         const float *v1;
11719                                         const float *v2;
11720                                 }
11721                                 shortest[2];
11722                                 memset(shortest, 0, sizeof(shortest));
11723                                 // a single autosprite surface can contain multiple sprites...
11724                                 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11725                                 {
11726                                         VectorClear(center);
11727                                         for (i = 0;i < 4;i++)
11728                                                 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11729                                         VectorScale(center, 0.25f, center);
11730                                         // find the two shortest edges, then use them to define the
11731                                         // axis vectors for rotating around the central axis
11732                                         for (i = 0;i < 6;i++)
11733                                         {
11734                                                 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
11735                                                 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
11736                                                 l = VectorDistance2(v1, v2);
11737                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
11738                                                 if (v1[2] != v2[2])
11739                                                         l += (1.0f / 1024.0f);
11740                                                 if (shortest[0].length2 > l || i == 0)
11741                                                 {
11742                                                         shortest[1] = shortest[0];
11743                                                         shortest[0].length2 = l;
11744                                                         shortest[0].v1 = v1;
11745                                                         shortest[0].v2 = v2;
11746                                                 }
11747                                                 else if (shortest[1].length2 > l || i == 1)
11748                                                 {
11749                                                         shortest[1].length2 = l;
11750                                                         shortest[1].v1 = v1;
11751                                                         shortest[1].v2 = v2;
11752                                                 }
11753                                         }
11754                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
11755                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
11756                                         // this calculates the right vector from the shortest edge
11757                                         // and the up vector from the edge midpoints
11758                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
11759                                         VectorNormalize(right);
11760                                         VectorSubtract(end, start, up);
11761                                         VectorNormalize(up);
11762                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
11763                                         VectorSubtract(rsurface.localvieworigin, center, forward);
11764                                         //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
11765                                         VectorNegate(forward, forward);
11766                                         VectorReflect(forward, 0, up, forward);
11767                                         VectorNormalize(forward);
11768                                         CrossProduct(up, forward, newright);
11769                                         VectorNormalize(newright);
11770                                         // rotate the quad around the up axis vector, this is made
11771                                         // especially easy by the fact we know the quad is flat,
11772                                         // so we only have to subtract the center position and
11773                                         // measure distance along the right vector, and then
11774                                         // multiply that by the newright vector and add back the
11775                                         // center position
11776                                         // we also need to subtract the old position to undo the
11777                                         // displacement from the center, which we do with a
11778                                         // DotProduct, the subtraction/addition of center is also
11779                                         // optimized into DotProducts here
11780                                         l = DotProduct(right, center);
11781                                         for (i = 0;i < 4;i++)
11782                                         {
11783                                                 v1 = rsurface.batchvertex3f + 3*(j+i);
11784                                                 f = DotProduct(right, v1) - l;
11785                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
11786                                         }
11787                                 }
11788                         }
11789                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11790                         rsurface.batchvertex3f_vertexbuffer = NULL;
11791                         rsurface.batchvertex3f_bufferoffset = 0;
11792                         if(batchneed & (BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR)) // otherwise these can stay NULL
11793                         {
11794                                 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11795                                 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11796                                 rsurface.batchnormal3f_vertexbuffer = NULL;
11797                                 rsurface.batchnormal3f_bufferoffset = 0;
11798                         }
11799                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11800                         {
11801                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
11802                                 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11803                                 rsurface.batchsvector3f_vertexbuffer = NULL;
11804                                 rsurface.batchsvector3f_bufferoffset = 0;
11805                                 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11806                                 rsurface.batchtvector3f_vertexbuffer = NULL;
11807                                 rsurface.batchtvector3f_bufferoffset = 0;
11808                         }
11809                         break;
11810                 case Q3DEFORM_NORMAL:
11811                         // deform the normals to make reflections wavey
11812                         for (j = 0;j < rsurface.batchnumvertices;j++)
11813                         {
11814                                 float vertex[3];
11815                                 float *normal = rsurface.array_batchnormal3f + 3*j;
11816                                 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
11817                                 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11818                                 normal[1] = rsurface.batchnormal3f[j*3+1] + deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11819                                 normal[2] = rsurface.batchnormal3f[j*3+2] + deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11820                                 VectorNormalize(normal);
11821                         }
11822                         rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11823                         rsurface.batchnormal3f_vertexbuffer = NULL;
11824                         rsurface.batchnormal3f_bufferoffset = 0;
11825                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11826                         {
11827                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
11828                                 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11829                                 rsurface.batchsvector3f_vertexbuffer = NULL;
11830                                 rsurface.batchsvector3f_bufferoffset = 0;
11831                                 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11832                                 rsurface.batchtvector3f_vertexbuffer = NULL;
11833                                 rsurface.batchtvector3f_bufferoffset = 0;
11834                         }
11835                         break;
11836                 case Q3DEFORM_WAVE:
11837                         // deform vertex array to make wavey water and flags and such
11838                         waveparms[0] = deform->waveparms[0];
11839                         waveparms[1] = deform->waveparms[1];
11840                         waveparms[2] = deform->waveparms[2];
11841                         waveparms[3] = deform->waveparms[3];
11842                         if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
11843                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
11844                         // this is how a divisor of vertex influence on deformation
11845                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
11846                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11847                         for (j = 0;j < rsurface.batchnumvertices;j++)
11848                         {
11849                                 // if the wavefunc depends on time, evaluate it per-vertex
11850                                 if (waveparms[3])
11851                                 {
11852                                         waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
11853                                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11854                                 }
11855                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11856                         }
11857                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11858                         Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11859                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11860                         rsurface.batchvertex3f_vertexbuffer = NULL;
11861                         rsurface.batchvertex3f_bufferoffset = 0;
11862                         rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11863                         rsurface.batchnormal3f_vertexbuffer = NULL;
11864                         rsurface.batchnormal3f_bufferoffset = 0;
11865                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11866                         {
11867                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
11868                                 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11869                                 rsurface.batchsvector3f_vertexbuffer = NULL;
11870                                 rsurface.batchsvector3f_bufferoffset = 0;
11871                                 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11872                                 rsurface.batchtvector3f_vertexbuffer = NULL;
11873                                 rsurface.batchtvector3f_bufferoffset = 0;
11874                         }
11875                         break;
11876                 case Q3DEFORM_BULGE:
11877                         // deform vertex array to make the surface have moving bulges
11878                         for (j = 0;j < rsurface.batchnumvertices;j++)
11879                         {
11880                                 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
11881                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11882                         }
11883                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11884                         Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11885                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11886                         rsurface.batchvertex3f_vertexbuffer = NULL;
11887                         rsurface.batchvertex3f_bufferoffset = 0;
11888                         rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11889                         rsurface.batchnormal3f_vertexbuffer = NULL;
11890                         rsurface.batchnormal3f_bufferoffset = 0;
11891                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11892                         {
11893                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
11894                                 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11895                                 rsurface.batchsvector3f_vertexbuffer = NULL;
11896                                 rsurface.batchsvector3f_bufferoffset = 0;
11897                                 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11898                                 rsurface.batchtvector3f_vertexbuffer = NULL;
11899                                 rsurface.batchtvector3f_bufferoffset = 0;
11900                         }
11901                         break;
11902                 case Q3DEFORM_MOVE:
11903                         // deform vertex array
11904                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11905                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
11906                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
11907                         VectorScale(deform->parms, scale, waveparms);
11908                         for (j = 0;j < rsurface.batchnumvertices;j++)
11909                                 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
11910                         rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11911                         rsurface.batchvertex3f_vertexbuffer = NULL;
11912                         rsurface.batchvertex3f_bufferoffset = 0;
11913                         break;
11914                 }
11915         }
11916
11917         // generate texcoords based on the chosen texcoord source
11918         switch(rsurface.texture->tcgen.tcgen)
11919         {
11920         default:
11921         case Q3TCGEN_TEXTURE:
11922                 break;
11923         case Q3TCGEN_LIGHTMAP:
11924                 if (rsurface.batchtexcoordlightmap2f)
11925                         memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
11926                 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11927                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11928                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11929                 break;
11930         case Q3TCGEN_VECTOR:
11931                 for (j = 0;j < rsurface.batchnumvertices;j++)
11932                 {
11933                         rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
11934                         rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
11935                 }
11936                 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11937                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11938                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11939                 break;
11940         case Q3TCGEN_ENVIRONMENT:
11941                 // make environment reflections using a spheremap
11942                 for (j = 0;j < rsurface.batchnumvertices;j++)
11943                 {
11944                         // identical to Q3A's method, but executed in worldspace so
11945                         // carried models can be shiny too
11946
11947                         float viewer[3], d, reflected[3], worldreflected[3];
11948
11949                         VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
11950                         // VectorNormalize(viewer);
11951
11952                         d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
11953
11954                         reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
11955                         reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
11956                         reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
11957                         // note: this is proportinal to viewer, so we can normalize later
11958
11959                         Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
11960                         VectorNormalize(worldreflected);
11961
11962                         // note: this sphere map only uses world x and z!
11963                         // so positive and negative y will LOOK THE SAME.
11964                         rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
11965                         rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
11966                 }
11967                 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11968                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11969                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11970                 break;
11971         }
11972         // the only tcmod that needs software vertex processing is turbulent, so
11973         // check for it here and apply the changes if needed
11974         // and we only support that as the first one
11975         // (handling a mixture of turbulent and other tcmods would be problematic
11976         //  without punting it entirely to a software path)
11977         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11978         {
11979                 amplitude = rsurface.texture->tcmods[0].parms[1];
11980                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
11981                 for (j = 0;j < rsurface.batchnumvertices;j++)
11982                 {
11983                         rsurface.array_batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11984                         rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1]                                ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11985                 }
11986                 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11987                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11988                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11989         }
11990
11991         if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11992         {
11993                 // convert the modified arrays to vertex structs
11994                 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11995                 rsurface.batchvertexmeshbuffer = NULL;
11996                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11997                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11998                                 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11999                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
12000                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
12001                                 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
12002                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
12003                 {
12004                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
12005                         {
12006                                 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
12007                                 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
12008                         }
12009                 }
12010                 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
12011                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
12012                                 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
12013                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
12014                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
12015                                 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
12016                 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
12017                         for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
12018                                 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
12019         }
12020
12021         if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
12022         {
12023                 // convert the modified arrays to vertex structs
12024                 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
12025                 rsurface.batchvertexpositionbuffer = NULL;
12026                 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
12027                         memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
12028                 else
12029                         for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
12030                                 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
12031         }
12032 }
12033
12034 void RSurf_DrawBatch(void)
12035 {
12036         R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
12037 }
12038
12039 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
12040 {
12041         // pick the closest matching water plane
12042         int planeindex, vertexindex, bestplaneindex = -1;
12043         float d, bestd;
12044         vec3_t vert;
12045         const float *v;
12046         r_waterstate_waterplane_t *p;
12047         bestd = 0;
12048         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
12049         {
12050                 if(p->camera_entity != rsurface.texture->camera_entity)
12051                         continue;
12052                 d = 0;
12053                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
12054                 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
12055                 {
12056                         Matrix4x4_Transform(&rsurface.matrix, v, vert);
12057                         d += fabs(PlaneDiff(vert, &p->plane));
12058                 }
12059                 if (bestd > d || bestplaneindex < 0)
12060                 {
12061                         bestd = d;
12062                         bestplaneindex = planeindex;
12063                 }
12064         }
12065         return bestplaneindex;
12066 }
12067
12068 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
12069 {
12070         int i;
12071         for (i = 0;i < rsurface.batchnumvertices;i++)
12072                 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
12073         rsurface.passcolor4f = rsurface.array_passcolor4f;
12074         rsurface.passcolor4f_vertexbuffer = 0;
12075         rsurface.passcolor4f_bufferoffset = 0;
12076 }
12077
12078 static void RSurf_DrawBatch_GL11_ApplyFog(void)
12079 {
12080         int i;
12081         float f;
12082         const float *v;
12083         const float *c;
12084         float *c2;
12085         if (rsurface.passcolor4f)
12086         {
12087                 // generate color arrays
12088                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
12089                 {
12090                         f = RSurf_FogVertex(v);
12091                         c2[0] = c[0] * f;
12092                         c2[1] = c[1] * f;
12093                         c2[2] = c[2] * f;
12094                         c2[3] = c[3];
12095                 }
12096         }
12097         else
12098         {
12099                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
12100                 {
12101                         f = RSurf_FogVertex(v);
12102                         c2[0] = f;
12103                         c2[1] = f;
12104                         c2[2] = f;
12105                         c2[3] = 1;
12106                 }
12107         }
12108         rsurface.passcolor4f = rsurface.array_passcolor4f;
12109         rsurface.passcolor4f_vertexbuffer = 0;
12110         rsurface.passcolor4f_bufferoffset = 0;
12111 }
12112
12113 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
12114 {
12115         int i;
12116         float f;
12117         const float *v;
12118         const float *c;
12119         float *c2;
12120         if (!rsurface.passcolor4f)
12121                 return;
12122         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
12123         {
12124                 f = RSurf_FogVertex(v);
12125                 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
12126                 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
12127                 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
12128                 c2[3] = c[3];
12129         }
12130         rsurface.passcolor4f = rsurface.array_passcolor4f;
12131         rsurface.passcolor4f_vertexbuffer = 0;
12132         rsurface.passcolor4f_bufferoffset = 0;
12133 }
12134
12135 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
12136 {
12137         int i;
12138         const float *c;
12139         float *c2;
12140         if (!rsurface.passcolor4f)
12141                 return;
12142         for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
12143         {
12144                 c2[0] = c[0] * r;
12145                 c2[1] = c[1] * g;
12146                 c2[2] = c[2] * b;
12147                 c2[3] = c[3] * a;
12148         }
12149         rsurface.passcolor4f = rsurface.array_passcolor4f;
12150         rsurface.passcolor4f_vertexbuffer = 0;
12151         rsurface.passcolor4f_bufferoffset = 0;
12152 }
12153
12154 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
12155 {
12156         int i;
12157         const float *c;
12158         float *c2;
12159         if (!rsurface.passcolor4f)
12160                 return;
12161         for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
12162         {
12163                 c2[0] = c[0] + r_refdef.scene.ambient;
12164                 c2[1] = c[1] + r_refdef.scene.ambient;
12165                 c2[2] = c[2] + r_refdef.scene.ambient;
12166                 c2[3] = c[3];
12167         }
12168         rsurface.passcolor4f = rsurface.array_passcolor4f;
12169         rsurface.passcolor4f_vertexbuffer = 0;
12170         rsurface.passcolor4f_bufferoffset = 0;
12171 }
12172
12173 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12174 {
12175         // TODO: optimize
12176         rsurface.passcolor4f = NULL;
12177         rsurface.passcolor4f_vertexbuffer = 0;
12178         rsurface.passcolor4f_bufferoffset = 0;
12179         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12180         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12181         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12182         GL_Color(r, g, b, a);
12183         R_Mesh_TexBind(0, rsurface.lightmaptexture);
12184         RSurf_DrawBatch();
12185 }
12186
12187 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12188 {
12189         // TODO: optimize applyfog && applycolor case
12190         // just apply fog if necessary, and tint the fog color array if necessary
12191         rsurface.passcolor4f = NULL;
12192         rsurface.passcolor4f_vertexbuffer = 0;
12193         rsurface.passcolor4f_bufferoffset = 0;
12194         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12195         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12196         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12197         GL_Color(r, g, b, a);
12198         RSurf_DrawBatch();
12199 }
12200
12201 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12202 {
12203         // TODO: optimize
12204         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12205         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12206         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12207         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12208         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12209         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12210         GL_Color(r, g, b, a);
12211         RSurf_DrawBatch();
12212 }
12213
12214 static void RSurf_DrawBatch_GL11_ClampColor(void)
12215 {
12216         int i;
12217         const float *c1;
12218         float *c2;
12219         if (!rsurface.passcolor4f)
12220                 return;
12221         for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
12222         {
12223                 c2[0] = bound(0.0f, c1[0], 1.0f);
12224                 c2[1] = bound(0.0f, c1[1], 1.0f);
12225                 c2[2] = bound(0.0f, c1[2], 1.0f);
12226                 c2[3] = bound(0.0f, c1[3], 1.0f);
12227         }
12228 }
12229
12230 static void RSurf_DrawBatch_GL11_ApplyFakeLight(void)
12231 {
12232         int i;
12233         float f;
12234         const float *v;
12235         const float *n;
12236         float *c;
12237         //vec3_t eyedir;
12238
12239         // fake shading
12240         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
12241         {
12242                 f = -DotProduct(r_refdef.view.forward, n);
12243                 f = max(0, f);
12244                 f = f * 0.85 + 0.15; // work around so stuff won't get black
12245                 f *= r_refdef.lightmapintensity;
12246                 Vector4Set(c, f, f, f, 1);
12247         }
12248
12249         rsurface.passcolor4f = rsurface.array_passcolor4f;
12250         rsurface.passcolor4f_vertexbuffer = 0;
12251         rsurface.passcolor4f_bufferoffset = 0;
12252 }
12253
12254 static void RSurf_DrawBatch_GL11_FakeLight(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12255 {
12256         RSurf_DrawBatch_GL11_ApplyFakeLight();
12257         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12258         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12259         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12260         GL_Color(r, g, b, a);
12261         RSurf_DrawBatch();
12262 }
12263
12264 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
12265 {
12266         int i;
12267         float f;
12268         float alpha;
12269         const float *v;
12270         const float *n;
12271         float *c;
12272         vec3_t ambientcolor;
12273         vec3_t diffusecolor;
12274         vec3_t lightdir;
12275         // TODO: optimize
12276         // model lighting
12277         VectorCopy(rsurface.modellight_lightdir, lightdir);
12278         f = 0.5f * r_refdef.lightmapintensity;
12279         ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
12280         ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
12281         ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
12282         diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
12283         diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
12284         diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
12285         alpha = *a;
12286         if (VectorLength2(diffusecolor) > 0)
12287         {
12288                 // q3-style directional shading
12289                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
12290                 {
12291                         if ((f = DotProduct(n, lightdir)) > 0)
12292                                 VectorMA(ambientcolor, f, diffusecolor, c);
12293                         else
12294                                 VectorCopy(ambientcolor, c);
12295                         c[3] = alpha;
12296                 }
12297                 *r = 1;
12298                 *g = 1;
12299                 *b = 1;
12300                 *a = 1;
12301                 rsurface.passcolor4f = rsurface.array_passcolor4f;
12302                 rsurface.passcolor4f_vertexbuffer = 0;
12303                 rsurface.passcolor4f_bufferoffset = 0;
12304                 *applycolor = false;
12305         }
12306         else
12307         {
12308                 *r = ambientcolor[0];
12309                 *g = ambientcolor[1];
12310                 *b = ambientcolor[2];
12311                 rsurface.passcolor4f = NULL;
12312                 rsurface.passcolor4f_vertexbuffer = 0;
12313                 rsurface.passcolor4f_bufferoffset = 0;
12314         }
12315 }
12316
12317 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12318 {
12319         RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
12320         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12321         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12322         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12323         GL_Color(r, g, b, a);
12324         RSurf_DrawBatch();
12325 }
12326
12327 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
12328 {
12329         int i;
12330         float f;
12331         const float *v;
12332         float *c;
12333         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
12334         {
12335                 f = 1 - RSurf_FogVertex(v);
12336                 c[0] = r;
12337                 c[1] = g;
12338                 c[2] = b;
12339                 c[3] = f * a;
12340         }
12341 }
12342
12343 void RSurf_SetupDepthAndCulling(void)
12344 {
12345         // submodels are biased to avoid z-fighting with world surfaces that they
12346         // may be exactly overlapping (avoids z-fighting artifacts on certain
12347         // doors and things in Quake maps)
12348         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
12349         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
12350         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
12351         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
12352 }
12353
12354 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12355 {
12356         // transparent sky would be ridiculous
12357         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12358                 return;
12359         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12360         skyrenderlater = true;
12361         RSurf_SetupDepthAndCulling();
12362         GL_DepthMask(true);
12363         // LordHavoc: HalfLife maps have freaky skypolys so don't use
12364         // skymasking on them, and Quake3 never did sky masking (unlike
12365         // software Quake and software Quake2), so disable the sky masking
12366         // in Quake3 maps as it causes problems with q3map2 sky tricks,
12367         // and skymasking also looks very bad when noclipping outside the
12368         // level, so don't use it then either.
12369         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
12370         {
12371                 R_Mesh_ResetTextureState();
12372                 if (skyrendermasked)
12373                 {
12374                         R_SetupShader_DepthOrShadow();
12375                         // depth-only (masking)
12376                         GL_ColorMask(0,0,0,0);
12377                         // just to make sure that braindead drivers don't draw
12378                         // anything despite that colormask...
12379                         GL_BlendFunc(GL_ZERO, GL_ONE);
12380                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12381                         R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12382                 }
12383                 else
12384                 {
12385                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12386                         // fog sky
12387                         GL_BlendFunc(GL_ONE, GL_ZERO);
12388                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12389                         GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
12390                         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12391                 }
12392                 RSurf_DrawBatch();
12393                 if (skyrendermasked)
12394                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12395         }
12396         R_Mesh_ResetTextureState();
12397         GL_Color(1, 1, 1, 1);
12398 }
12399
12400 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
12401 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
12402 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12403 {
12404         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
12405                 return;
12406         if (prepass)
12407         {
12408                 // render screenspace normalmap to texture
12409                 GL_DepthMask(true);
12410                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
12411                 RSurf_DrawBatch();
12412                 return;
12413         }
12414
12415         // bind lightmap texture
12416
12417         // water/refraction/reflection/camera surfaces have to be handled specially
12418         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
12419         {
12420                 int start, end, startplaneindex;
12421                 for (start = 0;start < texturenumsurfaces;start = end)
12422                 {
12423                         startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
12424                         for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
12425                                 ;
12426                         // now that we have a batch using the same planeindex, render it
12427                         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
12428                         {
12429                                 // render water or distortion background
12430                                 GL_DepthMask(true);
12431                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12432                                 RSurf_DrawBatch();
12433                                 // blend surface on top
12434                                 GL_DepthMask(false);
12435                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
12436                                 RSurf_DrawBatch();
12437                         }
12438                         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
12439                         {
12440                                 // render surface with reflection texture as input
12441                                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12442                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12443                                 RSurf_DrawBatch();
12444                         }
12445                 }
12446                 return;
12447         }
12448
12449         // render surface batch normally
12450         GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12451         R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
12452         RSurf_DrawBatch();
12453 }
12454
12455 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12456 {
12457         // OpenGL 1.3 path - anything not completely ancient
12458         qboolean applycolor;
12459         qboolean applyfog;
12460         int layerindex;
12461         const texturelayer_t *layer;
12462         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12463         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12464
12465         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12466         {
12467                 vec4_t layercolor;
12468                 int layertexrgbscale;
12469                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12470                 {
12471                         if (layerindex == 0)
12472                                 GL_AlphaTest(true);
12473                         else
12474                         {
12475                                 GL_AlphaTest(false);
12476                                 GL_DepthFunc(GL_EQUAL);
12477                         }
12478                 }
12479                 GL_DepthMask(layer->depthmask && writedepth);
12480                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12481                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
12482                 {
12483                         layertexrgbscale = 4;
12484                         VectorScale(layer->color, 0.25f, layercolor);
12485                 }
12486                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
12487                 {
12488                         layertexrgbscale = 2;
12489                         VectorScale(layer->color, 0.5f, layercolor);
12490                 }
12491                 else
12492                 {
12493                         layertexrgbscale = 1;
12494                         VectorScale(layer->color, 1.0f, layercolor);
12495                 }
12496                 layercolor[3] = layer->color[3];
12497                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
12498                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12499                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12500                 switch (layer->type)
12501                 {
12502                 case TEXTURELAYERTYPE_LITTEXTURE:
12503                         // single-pass lightmapped texture with 2x rgbscale
12504                         R_Mesh_TexBind(0, r_texture_white);
12505                         R_Mesh_TexMatrix(0, NULL);
12506                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12507                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12508                         R_Mesh_TexBind(1, layer->texture);
12509                         R_Mesh_TexMatrix(1, &layer->texmatrix);
12510                         R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12511                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12512                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12513                                 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12514                         else if (FAKELIGHT_ENABLED)
12515                                 RSurf_DrawBatch_GL11_FakeLight(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12516                         else if (rsurface.uselightmaptexture)
12517                                 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12518                         else
12519                                 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12520                         break;
12521                 case TEXTURELAYERTYPE_TEXTURE:
12522                         // singletexture unlit texture with transparency support
12523                         R_Mesh_TexBind(0, layer->texture);
12524                         R_Mesh_TexMatrix(0, &layer->texmatrix);
12525                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12526                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12527                         R_Mesh_TexBind(1, 0);
12528                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12529                         RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12530                         break;
12531                 case TEXTURELAYERTYPE_FOG:
12532                         // singletexture fogging
12533                         if (layer->texture)
12534                         {
12535                                 R_Mesh_TexBind(0, layer->texture);
12536                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12537                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12538                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12539                         }
12540                         else
12541                         {
12542                                 R_Mesh_TexBind(0, 0);
12543                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12544                         }
12545                         R_Mesh_TexBind(1, 0);
12546                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12547                         // generate a color array for the fog pass
12548                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12549                         RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
12550                         RSurf_DrawBatch();
12551                         break;
12552                 default:
12553                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12554                 }
12555         }
12556         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12557         {
12558                 GL_DepthFunc(GL_LEQUAL);
12559                 GL_AlphaTest(false);
12560         }
12561 }
12562
12563 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12564 {
12565         // OpenGL 1.1 - crusty old voodoo path
12566         qboolean applyfog;
12567         int layerindex;
12568         const texturelayer_t *layer;
12569         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12570         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12571
12572         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12573         {
12574                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12575                 {
12576                         if (layerindex == 0)
12577                                 GL_AlphaTest(true);
12578                         else
12579                         {
12580                                 GL_AlphaTest(false);
12581                                 GL_DepthFunc(GL_EQUAL);
12582                         }
12583                 }
12584                 GL_DepthMask(layer->depthmask && writedepth);
12585                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12586                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12587                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12588                 switch (layer->type)
12589                 {
12590                 case TEXTURELAYERTYPE_LITTEXTURE:
12591                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
12592                         {
12593                                 // two-pass lit texture with 2x rgbscale
12594                                 // first the lightmap pass
12595                                 R_Mesh_TexBind(0, r_texture_white);
12596                                 R_Mesh_TexMatrix(0, NULL);
12597                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12598                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12599                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12600                                         RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
12601                                 else if (FAKELIGHT_ENABLED)
12602                                         RSurf_DrawBatch_GL11_FakeLight(1, 1, 1, 1, false, false);
12603                                 else if (rsurface.uselightmaptexture)
12604                                         RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
12605                                 else
12606                                         RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
12607                                 // then apply the texture to it
12608                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
12609                                 R_Mesh_TexBind(0, layer->texture);
12610                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12611                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12612                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12613                                 RSurf_DrawBatch_GL11_Unlit(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);
12614                         }
12615                         else
12616                         {
12617                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
12618                                 R_Mesh_TexBind(0, layer->texture);
12619                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12620                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12621                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12622                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12623                                         RSurf_DrawBatch_GL11_VertexShade(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);
12624                                 else
12625                                         RSurf_DrawBatch_GL11_VertexColor(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);
12626                         }
12627                         break;
12628                 case TEXTURELAYERTYPE_TEXTURE:
12629                         // singletexture unlit texture with transparency support
12630                         R_Mesh_TexBind(0, layer->texture);
12631                         R_Mesh_TexMatrix(0, &layer->texmatrix);
12632                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12633                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12634                         RSurf_DrawBatch_GL11_Unlit(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);
12635                         break;
12636                 case TEXTURELAYERTYPE_FOG:
12637                         // singletexture fogging
12638                         if (layer->texture)
12639                         {
12640                                 R_Mesh_TexBind(0, layer->texture);
12641                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12642                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12643                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12644                         }
12645                         else
12646                         {
12647                                 R_Mesh_TexBind(0, 0);
12648                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12649                         }
12650                         // generate a color array for the fog pass
12651                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12652                         RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
12653                         RSurf_DrawBatch();
12654                         break;
12655                 default:
12656                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12657                 }
12658         }
12659         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12660         {
12661                 GL_DepthFunc(GL_LEQUAL);
12662                 GL_AlphaTest(false);
12663         }
12664 }
12665
12666 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12667 {
12668         int vi;
12669         int j;
12670         r_vertexgeneric_t *batchvertex;
12671         float c[4];
12672
12673         GL_AlphaTest(false);
12674         R_Mesh_ResetTextureState();
12675         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12676
12677         if(rsurface.texture && rsurface.texture->currentskinframe)
12678         {
12679                 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
12680                 c[3] *= rsurface.texture->currentalpha;
12681         }
12682         else
12683         {
12684                 c[0] = 1;
12685                 c[1] = 0;
12686                 c[2] = 1;
12687                 c[3] = 1;
12688         }
12689
12690         if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
12691         {
12692                 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
12693                 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
12694                 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
12695         }
12696
12697         // brighten it up (as texture value 127 means "unlit")
12698         c[0] *= 2 * r_refdef.view.colorscale;
12699         c[1] *= 2 * r_refdef.view.colorscale;
12700         c[2] *= 2 * r_refdef.view.colorscale;
12701
12702         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
12703                 c[3] *= r_wateralpha.value;
12704
12705         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
12706         {
12707                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12708                 GL_DepthMask(false);
12709         }
12710         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
12711         {
12712                 GL_BlendFunc(GL_ONE, GL_ONE);
12713                 GL_DepthMask(false);
12714         }
12715         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12716         {
12717                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
12718                 GL_DepthMask(false);
12719         }
12720         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
12721         {
12722                 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
12723                 GL_DepthMask(false);
12724         }
12725         else
12726         {
12727                 GL_BlendFunc(GL_ONE, GL_ZERO);
12728                 GL_DepthMask(writedepth);
12729         }
12730
12731         if (r_showsurfaces.integer == 3)
12732         {
12733                 rsurface.passcolor4f = NULL;
12734
12735                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
12736                 {
12737                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12738
12739                         rsurface.passcolor4f = NULL;
12740                         rsurface.passcolor4f_vertexbuffer = 0;
12741                         rsurface.passcolor4f_bufferoffset = 0;
12742                 }
12743                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12744                 {
12745                         qboolean applycolor = true;
12746                         float one = 1.0;
12747
12748                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12749
12750                         r_refdef.lightmapintensity = 1;
12751                         RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
12752                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12753                 }
12754                 else if (FAKELIGHT_ENABLED)
12755                 {
12756                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12757
12758                         r_refdef.lightmapintensity = r_fakelight_intensity.value;
12759                         RSurf_DrawBatch_GL11_ApplyFakeLight();
12760                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12761                 }
12762                 else
12763                 {
12764                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12765
12766                         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12767                         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12768                         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12769                 }
12770
12771                 if(!rsurface.passcolor4f)
12772                         RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
12773
12774                 RSurf_DrawBatch_GL11_ApplyAmbient();
12775                 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
12776                 if(r_refdef.fogenabled)
12777                         RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
12778                 RSurf_DrawBatch_GL11_ClampColor();
12779
12780                 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
12781                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12782                 RSurf_DrawBatch();
12783         }
12784         else if (!r_refdef.view.showdebug)
12785         {
12786                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12787                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12788                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12789                 {
12790                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12791                         Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
12792                 }
12793                 R_Mesh_PrepareVertices_Generic_Unlock();
12794                 RSurf_DrawBatch();
12795         }
12796         else if (r_showsurfaces.integer == 4)
12797         {
12798                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12799                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12800                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12801                 {
12802                         unsigned char c = vi << 3;
12803                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12804                         Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
12805                 }
12806                 R_Mesh_PrepareVertices_Generic_Unlock();
12807                 RSurf_DrawBatch();
12808         }
12809         else if (r_showsurfaces.integer == 2)
12810         {
12811                 const int *e;
12812                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12813                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
12814                 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
12815                 {
12816                         unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
12817                         VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
12818                         VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
12819                         VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
12820                         Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
12821                         Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
12822                         Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
12823                 }
12824                 R_Mesh_PrepareVertices_Generic_Unlock();
12825                 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
12826         }
12827         else
12828         {
12829                 int texturesurfaceindex;
12830                 int k;
12831                 const msurface_t *surface;
12832                 unsigned char surfacecolor4ub[4];
12833                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12834                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
12835                 vi = 0;
12836                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
12837                 {
12838                         surface = texturesurfacelist[texturesurfaceindex];
12839                         k = (int)(((size_t)surface) / sizeof(msurface_t));
12840                         Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
12841                         for (j = 0;j < surface->num_vertices;j++)
12842                         {
12843                                 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12844                                 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
12845                                 vi++;
12846                         }
12847                 }
12848                 R_Mesh_PrepareVertices_Generic_Unlock();
12849                 RSurf_DrawBatch();
12850         }
12851 }
12852
12853 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12854 {
12855         CHECKGLERROR
12856         RSurf_SetupDepthAndCulling();
12857         if (r_showsurfaces.integer)
12858         {
12859                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12860                 return;
12861         }
12862         switch (vid.renderpath)
12863         {
12864         case RENDERPATH_GL20:
12865         case RENDERPATH_CGGL:
12866         case RENDERPATH_D3D9:
12867         case RENDERPATH_D3D10:
12868         case RENDERPATH_D3D11:
12869                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12870                 break;
12871         case RENDERPATH_GL13:
12872                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12873                 break;
12874         case RENDERPATH_GL11:
12875                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12876                 break;
12877         }
12878         CHECKGLERROR
12879 }
12880
12881 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12882 {
12883         CHECKGLERROR
12884         RSurf_SetupDepthAndCulling();
12885         if (r_showsurfaces.integer)
12886         {
12887                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12888                 return;
12889         }
12890         switch (vid.renderpath)
12891         {
12892         case RENDERPATH_GL20:
12893         case RENDERPATH_CGGL:
12894         case RENDERPATH_D3D9:
12895         case RENDERPATH_D3D10:
12896         case RENDERPATH_D3D11:
12897                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12898                 break;
12899         case RENDERPATH_GL13:
12900                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12901                 break;
12902         case RENDERPATH_GL11:
12903                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12904                 break;
12905         }
12906         CHECKGLERROR
12907 }
12908
12909 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12910 {
12911         int i, j;
12912         int texturenumsurfaces, endsurface;
12913         texture_t *texture;
12914         const msurface_t *surface;
12915 #define MAXBATCH_TRANSPARENTSURFACES 256
12916         const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
12917
12918         // if the model is static it doesn't matter what value we give for
12919         // wantnormals and wanttangents, so this logic uses only rules applicable
12920         // to a model, knowing that they are meaningless otherwise
12921         if (ent == r_refdef.scene.worldentity)
12922                 RSurf_ActiveWorldEntity();
12923         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12924                 RSurf_ActiveModelEntity(ent, false, false, false);
12925         else
12926         {
12927                 switch (vid.renderpath)
12928                 {
12929                 case RENDERPATH_GL20:
12930                 case RENDERPATH_CGGL:
12931                 case RENDERPATH_D3D9:
12932                 case RENDERPATH_D3D10:
12933                 case RENDERPATH_D3D11:
12934                         RSurf_ActiveModelEntity(ent, true, true, false);
12935                         break;
12936                 case RENDERPATH_GL13:
12937                 case RENDERPATH_GL11:
12938                         RSurf_ActiveModelEntity(ent, true, false, false);
12939                         break;
12940                 }
12941         }
12942
12943         if (r_transparentdepthmasking.integer)
12944         {
12945                 qboolean setup = false;
12946                 for (i = 0;i < numsurfaces;i = j)
12947                 {
12948                         j = i + 1;
12949                         surface = rsurface.modelsurfaces + surfacelist[i];
12950                         texture = surface->texture;
12951                         rsurface.texture = R_GetCurrentTexture(texture);
12952                         rsurface.lightmaptexture = NULL;
12953                         rsurface.deluxemaptexture = NULL;
12954                         rsurface.uselightmaptexture = false;
12955                         // scan ahead until we find a different texture
12956                         endsurface = min(i + 1024, numsurfaces);
12957                         texturenumsurfaces = 0;
12958                         texturesurfacelist[texturenumsurfaces++] = surface;
12959                         for (;j < endsurface;j++)
12960                         {
12961                                 surface = rsurface.modelsurfaces + surfacelist[j];
12962                                 if (texture != surface->texture)
12963                                         break;
12964                                 texturesurfacelist[texturenumsurfaces++] = surface;
12965                         }
12966                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
12967                                 continue;
12968                         // render the range of surfaces as depth
12969                         if (!setup)
12970                         {
12971                                 setup = true;
12972                                 GL_ColorMask(0,0,0,0);
12973                                 GL_Color(1,1,1,1);
12974                                 GL_DepthTest(true);
12975                                 GL_BlendFunc(GL_ONE, GL_ZERO);
12976                                 GL_DepthMask(true);
12977                                 GL_AlphaTest(false);
12978                                 R_Mesh_ResetTextureState();
12979                                 R_SetupShader_DepthOrShadow();
12980                         }
12981                         RSurf_SetupDepthAndCulling();
12982                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12983                         R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12984                         RSurf_DrawBatch();
12985                 }
12986                 if (setup)
12987                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12988         }
12989
12990         for (i = 0;i < numsurfaces;i = j)
12991         {
12992                 j = i + 1;
12993                 surface = rsurface.modelsurfaces + surfacelist[i];
12994                 texture = surface->texture;
12995                 rsurface.texture = R_GetCurrentTexture(texture);
12996                 // scan ahead until we find a different texture
12997                 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12998                 texturenumsurfaces = 0;
12999                 texturesurfacelist[texturenumsurfaces++] = surface;
13000                 if(FAKELIGHT_ENABLED)
13001                 {
13002                         rsurface.lightmaptexture = NULL;
13003                         rsurface.deluxemaptexture = NULL;
13004                         rsurface.uselightmaptexture = false;
13005                         for (;j < endsurface;j++)
13006                         {
13007                                 surface = rsurface.modelsurfaces + surfacelist[j];
13008                                 if (texture != surface->texture)
13009                                         break;
13010                                 texturesurfacelist[texturenumsurfaces++] = surface;
13011                         }
13012                 }
13013                 else
13014                 {
13015                         rsurface.lightmaptexture = surface->lightmaptexture;
13016                         rsurface.deluxemaptexture = surface->deluxemaptexture;
13017                         rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
13018                         for (;j < endsurface;j++)
13019                         {
13020                                 surface = rsurface.modelsurfaces + surfacelist[j];
13021                                 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
13022                                         break;
13023                                 texturesurfacelist[texturenumsurfaces++] = surface;
13024                         }
13025                 }
13026                 // render the range of surfaces
13027                 if (ent == r_refdef.scene.worldentity)
13028                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
13029                 else
13030                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
13031         }
13032         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13033         GL_AlphaTest(false);
13034 }
13035
13036 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
13037 {
13038         // transparent surfaces get pushed off into the transparent queue
13039         int surfacelistindex;
13040         const msurface_t *surface;
13041         vec3_t tempcenter, center;
13042         for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
13043         {
13044                 surface = texturesurfacelist[surfacelistindex];
13045                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
13046                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
13047                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
13048                 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
13049                 if (queueentity->transparent_offset) // transparent offset
13050                 {
13051                         center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
13052                         center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
13053                         center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
13054                 }
13055                 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
13056         }
13057 }
13058
13059 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
13060 {
13061         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
13062                 return;
13063         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
13064                 return;
13065         RSurf_SetupDepthAndCulling();
13066         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
13067         R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
13068         RSurf_DrawBatch();
13069 }
13070
13071 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
13072 {
13073         const entity_render_t *queueentity = r_refdef.scene.worldentity;
13074         CHECKGLERROR
13075         if (depthonly)
13076                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
13077         else if (prepass)
13078         {
13079                 if (!rsurface.texture->currentnumlayers)
13080                         return;
13081                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
13082                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
13083                 else
13084                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
13085         }
13086         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
13087                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
13088         else if (!rsurface.texture->currentnumlayers)
13089                 return;
13090         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
13091         {
13092                 // in the deferred case, transparent surfaces were queued during prepass
13093                 if (!r_shadow_usingdeferredprepass)
13094                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
13095         }
13096         else
13097         {
13098                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
13099                 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
13100         }
13101         CHECKGLERROR
13102 }
13103
13104 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
13105 {
13106         int i, j;
13107         texture_t *texture;
13108         // break the surface list down into batches by texture and use of lightmapping
13109         for (i = 0;i < numsurfaces;i = j)
13110         {
13111                 j = i + 1;
13112                 // texture is the base texture pointer, rsurface.texture is the
13113                 // current frame/skin the texture is directing us to use (for example
13114                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
13115                 // use skin 1 instead)
13116                 texture = surfacelist[i]->texture;
13117                 rsurface.texture = R_GetCurrentTexture(texture);
13118                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
13119                 {
13120                         // if this texture is not the kind we want, skip ahead to the next one
13121                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
13122                                 ;
13123                         continue;
13124                 }
13125                 if(FAKELIGHT_ENABLED || depthonly || prepass)
13126                 {
13127                         rsurface.lightmaptexture = NULL;
13128                         rsurface.deluxemaptexture = NULL;
13129                         rsurface.uselightmaptexture = false;
13130                         // simply scan ahead until we find a different texture or lightmap state
13131                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
13132                                 ;
13133                 }
13134                 else
13135                 {
13136                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
13137                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
13138                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
13139                         // simply scan ahead until we find a different texture or lightmap state
13140                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
13141                                 ;
13142                 }
13143                 // render the range of surfaces
13144                 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
13145         }
13146 }
13147
13148 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
13149 {
13150         CHECKGLERROR
13151         if (depthonly)
13152                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
13153         else if (prepass)
13154         {
13155                 if (!rsurface.texture->currentnumlayers)
13156                         return;
13157                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
13158                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
13159                 else
13160                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
13161         }
13162         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
13163                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
13164         else if (!rsurface.texture->currentnumlayers)
13165                 return;
13166         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
13167         {
13168                 // in the deferred case, transparent surfaces were queued during prepass
13169                 if (!r_shadow_usingdeferredprepass)
13170                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
13171         }
13172         else
13173         {
13174                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
13175                 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
13176         }
13177         CHECKGLERROR
13178 }
13179
13180 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
13181 {
13182         int i, j;
13183         texture_t *texture;
13184         // break the surface list down into batches by texture and use of lightmapping
13185         for (i = 0;i < numsurfaces;i = j)
13186         {
13187                 j = i + 1;
13188                 // texture is the base texture pointer, rsurface.texture is the
13189                 // current frame/skin the texture is directing us to use (for example
13190                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
13191                 // use skin 1 instead)
13192                 texture = surfacelist[i]->texture;
13193                 rsurface.texture = R_GetCurrentTexture(texture);
13194                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
13195                 {
13196                         // if this texture is not the kind we want, skip ahead to the next one
13197                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
13198                                 ;
13199                         continue;
13200                 }
13201                 if(FAKELIGHT_ENABLED || depthonly || prepass)
13202                 {
13203                         rsurface.lightmaptexture = NULL;
13204                         rsurface.deluxemaptexture = NULL;
13205                         rsurface.uselightmaptexture = false;
13206                         // simply scan ahead until we find a different texture or lightmap state
13207                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
13208                                 ;
13209                 }
13210                 else
13211                 {
13212                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
13213                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
13214                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
13215                         // simply scan ahead until we find a different texture or lightmap state
13216                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
13217                                 ;
13218                 }
13219                 // render the range of surfaces
13220                 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
13221         }
13222 }
13223
13224 float locboxvertex3f[6*4*3] =
13225 {
13226         1,0,1, 1,0,0, 1,1,0, 1,1,1,
13227         0,1,1, 0,1,0, 0,0,0, 0,0,1,
13228         1,1,1, 1,1,0, 0,1,0, 0,1,1,
13229         0,0,1, 0,0,0, 1,0,0, 1,0,1,
13230         0,0,1, 1,0,1, 1,1,1, 0,1,1,
13231         1,0,0, 0,0,0, 0,1,0, 1,1,0
13232 };
13233
13234 unsigned short locboxelements[6*2*3] =
13235 {
13236          0, 1, 2, 0, 2, 3,
13237          4, 5, 6, 4, 6, 7,
13238          8, 9,10, 8,10,11,
13239         12,13,14, 12,14,15,
13240         16,17,18, 16,18,19,
13241         20,21,22, 20,22,23
13242 };
13243
13244 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
13245 {
13246         int i, j;
13247         cl_locnode_t *loc = (cl_locnode_t *)ent;
13248         vec3_t mins, size;
13249         float vertex3f[6*4*3];
13250         CHECKGLERROR
13251         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13252         GL_DepthMask(false);
13253         GL_DepthRange(0, 1);
13254         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13255         GL_DepthTest(true);
13256         GL_CullFace(GL_NONE);
13257         R_EntityMatrix(&identitymatrix);
13258
13259         R_Mesh_ResetTextureState();
13260
13261         i = surfacelist[0];
13262         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13263                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13264                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13265                         surfacelist[0] < 0 ? 0.5f : 0.125f);
13266
13267         if (VectorCompare(loc->mins, loc->maxs))
13268         {
13269                 VectorSet(size, 2, 2, 2);
13270                 VectorMA(loc->mins, -0.5f, size, mins);
13271         }
13272         else
13273         {
13274                 VectorCopy(loc->mins, mins);
13275                 VectorSubtract(loc->maxs, loc->mins, size);
13276         }
13277
13278         for (i = 0;i < 6*4*3;)
13279                 for (j = 0;j < 3;j++, i++)
13280                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
13281
13282         R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
13283         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13284         R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
13285 }
13286
13287 void R_DrawLocs(void)
13288 {
13289         int index;
13290         cl_locnode_t *loc, *nearestloc;
13291         vec3_t center;
13292         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
13293         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
13294         {
13295                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
13296                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
13297         }
13298 }
13299
13300 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
13301 {
13302         if (decalsystem->decals)
13303                 Mem_Free(decalsystem->decals);
13304         memset(decalsystem, 0, sizeof(*decalsystem));
13305 }
13306
13307 static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
13308 {
13309         tridecal_t *decal;
13310         tridecal_t *decals;
13311         int i;
13312
13313         // expand or initialize the system
13314         if (decalsystem->maxdecals <= decalsystem->numdecals)
13315         {
13316                 decalsystem_t old = *decalsystem;
13317                 qboolean useshortelements;
13318                 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
13319                 useshortelements = decalsystem->maxdecals * 3 <= 65536;
13320                 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
13321                 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
13322                 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
13323                 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
13324                 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
13325                 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
13326                 if (decalsystem->numdecals)
13327                         memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
13328                 if (old.decals)
13329                         Mem_Free(old.decals);
13330                 for (i = 0;i < decalsystem->maxdecals*3;i++)
13331                         decalsystem->element3i[i] = i;
13332                 if (useshortelements)
13333                         for (i = 0;i < decalsystem->maxdecals*3;i++)
13334                                 decalsystem->element3s[i] = i;
13335         }
13336
13337         // grab a decal and search for another free slot for the next one
13338         decals = decalsystem->decals;
13339         decal = decalsystem->decals + (i = decalsystem->freedecal++);
13340         for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
13341                 ;
13342         decalsystem->freedecal = i;
13343         if (decalsystem->numdecals <= i)
13344                 decalsystem->numdecals = i + 1;
13345
13346         // initialize the decal
13347         decal->lived = 0;
13348         decal->triangleindex = triangleindex;
13349         decal->surfaceindex = surfaceindex;
13350         decal->decalsequence = decalsequence;
13351         decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
13352         decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
13353         decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
13354         decal->color4ub[0][3] = 255;
13355         decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
13356         decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
13357         decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
13358         decal->color4ub[1][3] = 255;
13359         decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
13360         decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
13361         decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
13362         decal->color4ub[2][3] = 255;
13363         decal->vertex3f[0][0] = v0[0];
13364         decal->vertex3f[0][1] = v0[1];
13365         decal->vertex3f[0][2] = v0[2];
13366         decal->vertex3f[1][0] = v1[0];
13367         decal->vertex3f[1][1] = v1[1];
13368         decal->vertex3f[1][2] = v1[2];
13369         decal->vertex3f[2][0] = v2[0];
13370         decal->vertex3f[2][1] = v2[1];
13371         decal->vertex3f[2][2] = v2[2];
13372         decal->texcoord2f[0][0] = t0[0];
13373         decal->texcoord2f[0][1] = t0[1];
13374         decal->texcoord2f[1][0] = t1[0];
13375         decal->texcoord2f[1][1] = t1[1];
13376         decal->texcoord2f[2][0] = t2[0];
13377         decal->texcoord2f[2][1] = t2[1];
13378 }
13379
13380 extern cvar_t cl_decals_bias;
13381 extern cvar_t cl_decals_models;
13382 extern cvar_t cl_decals_newsystem_intensitymultiplier;
13383 // baseparms, parms, temps
13384 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
13385 {
13386         int cornerindex;
13387         int index;
13388         float v[9][3];
13389         const float *vertex3f;
13390         int numpoints;
13391         float points[2][9][3];
13392         float temp[3];
13393         float tc[9][2];
13394         float f;
13395         float c[9][4];
13396         const int *e;
13397
13398         e = rsurface.modelelement3i + 3*triangleindex;
13399
13400         vertex3f = rsurface.modelvertex3f;
13401
13402         for (cornerindex = 0;cornerindex < 3;cornerindex++)
13403         {
13404                 index = 3*e[cornerindex];
13405                 VectorCopy(vertex3f + index, v[cornerindex]);
13406         }
13407         // cull backfaces
13408         //TriangleNormal(v[0], v[1], v[2], normal);
13409         //if (DotProduct(normal, localnormal) < 0.0f)
13410         //      continue;
13411         // clip by each of the box planes formed from the projection matrix
13412         // if anything survives, we emit the decal
13413         numpoints = PolygonF_Clip(3        , v[0]        , planes[0][0], planes[0][1], planes[0][2], planes[0][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13414         if (numpoints < 3)
13415                 return;
13416         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[1][0], planes[1][1], planes[1][2], planes[1][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
13417         if (numpoints < 3)
13418                 return;
13419         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[2][0], planes[2][1], planes[2][2], planes[2][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13420         if (numpoints < 3)
13421                 return;
13422         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[3][0], planes[3][1], planes[3][2], planes[3][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
13423         if (numpoints < 3)
13424                 return;
13425         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[4][0], planes[4][1], planes[4][2], planes[4][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13426         if (numpoints < 3)
13427                 return;
13428         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[5][0], planes[5][1], planes[5][2], planes[5][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), v[0]);
13429         if (numpoints < 3)
13430                 return;
13431         // some part of the triangle survived, so we have to accept it...
13432         if (dynamic)
13433         {
13434                 // dynamic always uses the original triangle
13435                 numpoints = 3;
13436                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13437                 {
13438                         index = 3*e[cornerindex];
13439                         VectorCopy(vertex3f + index, v[cornerindex]);
13440                 }
13441         }
13442         for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
13443         {
13444                 // convert vertex positions to texcoords
13445                 Matrix4x4_Transform(projection, v[cornerindex], temp);
13446                 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
13447                 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
13448                 // calculate distance fade from the projection origin
13449                 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
13450                 f = bound(0.0f, f, 1.0f);
13451                 c[cornerindex][0] = r * f;
13452                 c[cornerindex][1] = g * f;
13453                 c[cornerindex][2] = b * f;
13454                 c[cornerindex][3] = 1.0f;
13455                 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
13456         }
13457         if (dynamic)
13458                 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
13459         else
13460                 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
13461                         R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
13462 }
13463 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
13464 {
13465         matrix4x4_t projection;
13466         decalsystem_t *decalsystem;
13467         qboolean dynamic;
13468         dp_model_t *model;
13469         const msurface_t *surface;
13470         const msurface_t *surfaces;
13471         const int *surfacelist;
13472         const texture_t *texture;
13473         int numtriangles;
13474         int numsurfacelist;
13475         int surfacelistindex;
13476         int surfaceindex;
13477         int triangleindex;
13478         float localorigin[3];
13479         float localnormal[3];
13480         float localmins[3];
13481         float localmaxs[3];
13482         float localsize;
13483         //float normal[3];
13484         float planes[6][4];
13485         float angles[3];
13486         bih_t *bih;
13487         int bih_triangles_count;
13488         int bih_triangles[256];
13489         int bih_surfaces[256];
13490
13491         decalsystem = &ent->decalsystem;
13492         model = ent->model;
13493         if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
13494         {
13495                 R_DecalSystem_Reset(&ent->decalsystem);
13496                 return;
13497         }
13498
13499         if (!model->brush.data_leafs && !cl_decals_models.integer)
13500         {
13501                 if (decalsystem->model)
13502                         R_DecalSystem_Reset(decalsystem);
13503                 return;
13504         }
13505
13506         if (decalsystem->model != model)
13507                 R_DecalSystem_Reset(decalsystem);
13508         decalsystem->model = model;
13509
13510         RSurf_ActiveModelEntity(ent, false, false, false);
13511
13512         Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
13513         Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
13514         VectorNormalize(localnormal);
13515         localsize = worldsize*rsurface.inversematrixscale;
13516         localmins[0] = localorigin[0] - localsize;
13517         localmins[1] = localorigin[1] - localsize;
13518         localmins[2] = localorigin[2] - localsize;
13519         localmaxs[0] = localorigin[0] + localsize;
13520         localmaxs[1] = localorigin[1] + localsize;
13521         localmaxs[2] = localorigin[2] + localsize;
13522
13523         //VectorCopy(localnormal, planes[4]);
13524         //VectorVectors(planes[4], planes[2], planes[0]);
13525         AnglesFromVectors(angles, localnormal, NULL, false);
13526         AngleVectors(angles, planes[0], planes[2], planes[4]);
13527         VectorNegate(planes[0], planes[1]);
13528         VectorNegate(planes[2], planes[3]);
13529         VectorNegate(planes[4], planes[5]);
13530         planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
13531         planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
13532         planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
13533         planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
13534         planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
13535         planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
13536
13537 #if 1
13538 // works
13539 {
13540         matrix4x4_t forwardprojection;
13541         Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
13542         Matrix4x4_Invert_Simple(&projection, &forwardprojection);
13543 }
13544 #else
13545 // broken
13546 {
13547         float projectionvector[4][3];
13548         VectorScale(planes[0], ilocalsize, projectionvector[0]);
13549         VectorScale(planes[2], ilocalsize, projectionvector[1]);
13550         VectorScale(planes[4], ilocalsize, projectionvector[2]);
13551         projectionvector[0][0] = planes[0][0] * ilocalsize;
13552         projectionvector[0][1] = planes[1][0] * ilocalsize;
13553         projectionvector[0][2] = planes[2][0] * ilocalsize;
13554         projectionvector[1][0] = planes[0][1] * ilocalsize;
13555         projectionvector[1][1] = planes[1][1] * ilocalsize;
13556         projectionvector[1][2] = planes[2][1] * ilocalsize;
13557         projectionvector[2][0] = planes[0][2] * ilocalsize;
13558         projectionvector[2][1] = planes[1][2] * ilocalsize;
13559         projectionvector[2][2] = planes[2][2] * ilocalsize;
13560         projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
13561         projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
13562         projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
13563         Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
13564 }
13565 #endif
13566
13567         dynamic = model->surfmesh.isanimated;
13568         numsurfacelist = model->nummodelsurfaces;
13569         surfacelist = model->sortedmodelsurfaces;
13570         surfaces = model->data_surfaces;
13571
13572         bih = NULL;
13573         bih_triangles_count = -1;
13574         if(!dynamic)
13575         {
13576                 if(model->render_bih.numleafs)
13577                         bih = &model->render_bih;
13578                 else if(model->collision_bih.numleafs)
13579                         bih = &model->collision_bih;
13580         }
13581         if(bih)
13582                 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
13583         if(bih_triangles_count == 0)
13584                 return;
13585         if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
13586                 return;
13587         if(bih_triangles_count > 0)
13588         {
13589                 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
13590                 {
13591                         surfaceindex = bih_surfaces[triangleindex];
13592                         surface = surfaces + surfaceindex;
13593                         texture = surface->texture;
13594                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13595                                 continue;
13596                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13597                                 continue;
13598                         R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
13599                 }
13600         }
13601         else
13602         {
13603                 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
13604                 {
13605                         surfaceindex = surfacelist[surfacelistindex];
13606                         surface = surfaces + surfaceindex;
13607                         // check cull box first because it rejects more than any other check
13608                         if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
13609                                 continue;
13610                         // skip transparent surfaces
13611                         texture = surface->texture;
13612                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13613                                 continue;
13614                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13615                                 continue;
13616                         numtriangles = surface->num_triangles;
13617                         for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
13618                                 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
13619                 }
13620         }
13621 }
13622
13623 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
13624 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
13625 {
13626         int renderentityindex;
13627         float worldmins[3];
13628         float worldmaxs[3];
13629         entity_render_t *ent;
13630
13631         if (!cl_decals_newsystem.integer)
13632                 return;
13633
13634         worldmins[0] = worldorigin[0] - worldsize;
13635         worldmins[1] = worldorigin[1] - worldsize;
13636         worldmins[2] = worldorigin[2] - worldsize;
13637         worldmaxs[0] = worldorigin[0] + worldsize;
13638         worldmaxs[1] = worldorigin[1] + worldsize;
13639         worldmaxs[2] = worldorigin[2] + worldsize;
13640
13641         R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13642
13643         for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
13644         {
13645                 ent = r_refdef.scene.entities[renderentityindex];
13646                 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
13647                         continue;
13648
13649                 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13650         }
13651 }
13652
13653 typedef struct r_decalsystem_splatqueue_s
13654 {
13655         vec3_t worldorigin;
13656         vec3_t worldnormal;
13657         float color[4];
13658         float tcrange[4];
13659         float worldsize;
13660         int decalsequence;
13661 }
13662 r_decalsystem_splatqueue_t;
13663
13664 int r_decalsystem_numqueued = 0;
13665 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
13666
13667 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
13668 {
13669         r_decalsystem_splatqueue_t *queue;
13670
13671         if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
13672                 return;
13673
13674         queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
13675         VectorCopy(worldorigin, queue->worldorigin);
13676         VectorCopy(worldnormal, queue->worldnormal);
13677         Vector4Set(queue->color, r, g, b, a);
13678         Vector4Set(queue->tcrange, s1, t1, s2, t2);
13679         queue->worldsize = worldsize;
13680         queue->decalsequence = cl.decalsequence++;
13681 }
13682
13683 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
13684 {
13685         int i;
13686         r_decalsystem_splatqueue_t *queue;
13687
13688         for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
13689                 R_DecalSystem_ApplySplatEntities(queue->worldorigin, queue->worldnormal, queue->color[0], queue->color[1], queue->color[2], queue->color[3], queue->tcrange[0], queue->tcrange[1], queue->tcrange[2], queue->tcrange[3], queue->worldsize, queue->decalsequence);
13690         r_decalsystem_numqueued = 0;
13691 }
13692
13693 extern cvar_t cl_decals_max;
13694 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
13695 {
13696         int i;
13697         decalsystem_t *decalsystem = &ent->decalsystem;
13698         int numdecals;
13699         int killsequence;
13700         tridecal_t *decal;
13701         float frametime;
13702         float lifetime;
13703
13704         if (!decalsystem->numdecals)
13705                 return;
13706
13707         if (r_showsurfaces.integer)
13708                 return;
13709
13710         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13711         {
13712                 R_DecalSystem_Reset(decalsystem);
13713                 return;
13714         }
13715
13716         killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
13717         lifetime = cl_decals_time.value + cl_decals_fadetime.value;
13718
13719         if (decalsystem->lastupdatetime)
13720                 frametime = (cl.time - decalsystem->lastupdatetime);
13721         else
13722                 frametime = 0;
13723         decalsystem->lastupdatetime = cl.time;
13724         decal = decalsystem->decals;
13725         numdecals = decalsystem->numdecals;
13726
13727         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13728         {
13729                 if (decal->color4ub[0][3])
13730                 {
13731                         decal->lived += frametime;
13732                         if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
13733                         {
13734                                 memset(decal, 0, sizeof(*decal));
13735                                 if (decalsystem->freedecal > i)
13736                                         decalsystem->freedecal = i;
13737                         }
13738                 }
13739         }
13740         decal = decalsystem->decals;
13741         while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
13742                 numdecals--;
13743
13744         // collapse the array by shuffling the tail decals into the gaps
13745         for (;;)
13746         {
13747                 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
13748                         decalsystem->freedecal++;
13749                 if (decalsystem->freedecal == numdecals)
13750                         break;
13751                 decal[decalsystem->freedecal] = decal[--numdecals];
13752         }
13753
13754         decalsystem->numdecals = numdecals;
13755
13756         if (numdecals <= 0)
13757         {
13758                 // if there are no decals left, reset decalsystem
13759                 R_DecalSystem_Reset(decalsystem);
13760         }
13761 }
13762
13763 extern skinframe_t *decalskinframe;
13764 static void R_DrawModelDecals_Entity(entity_render_t *ent)
13765 {
13766         int i;
13767         decalsystem_t *decalsystem = &ent->decalsystem;
13768         int numdecals;
13769         tridecal_t *decal;
13770         float faderate;
13771         float alpha;
13772         float *v3f;
13773         float *c4f;
13774         float *t2f;
13775         const int *e;
13776         const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
13777         int numtris = 0;
13778
13779         numdecals = decalsystem->numdecals;
13780         if (!numdecals)
13781                 return;
13782
13783         if (r_showsurfaces.integer)
13784                 return;
13785
13786         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13787         {
13788                 R_DecalSystem_Reset(decalsystem);
13789                 return;
13790         }
13791
13792         // if the model is static it doesn't matter what value we give for
13793         // wantnormals and wanttangents, so this logic uses only rules applicable
13794         // to a model, knowing that they are meaningless otherwise
13795         if (ent == r_refdef.scene.worldentity)
13796                 RSurf_ActiveWorldEntity();
13797         else
13798                 RSurf_ActiveModelEntity(ent, false, false, false);
13799
13800         decalsystem->lastupdatetime = cl.time;
13801         decal = decalsystem->decals;
13802
13803         faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
13804
13805         // update vertex positions for animated models
13806         v3f = decalsystem->vertex3f;
13807         c4f = decalsystem->color4f;
13808         t2f = decalsystem->texcoord2f;
13809         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13810         {
13811                 if (!decal->color4ub[0][3])
13812                         continue;
13813
13814                 if (surfacevisible && !surfacevisible[decal->surfaceindex])
13815                         continue;
13816
13817                 // update color values for fading decals
13818                 if (decal->lived >= cl_decals_time.value)
13819                 {
13820                         alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
13821                         alpha *= (1.0f/255.0f);
13822                 }
13823                 else
13824                         alpha = 1.0f/255.0f;
13825
13826                 c4f[ 0] = decal->color4ub[0][0] * alpha;
13827                 c4f[ 1] = decal->color4ub[0][1] * alpha;
13828                 c4f[ 2] = decal->color4ub[0][2] * alpha;
13829                 c4f[ 3] = 1;
13830                 c4f[ 4] = decal->color4ub[1][0] * alpha;
13831                 c4f[ 5] = decal->color4ub[1][1] * alpha;
13832                 c4f[ 6] = decal->color4ub[1][2] * alpha;
13833                 c4f[ 7] = 1;
13834                 c4f[ 8] = decal->color4ub[2][0] * alpha;
13835                 c4f[ 9] = decal->color4ub[2][1] * alpha;
13836                 c4f[10] = decal->color4ub[2][2] * alpha;
13837                 c4f[11] = 1;
13838
13839                 t2f[0] = decal->texcoord2f[0][0];
13840                 t2f[1] = decal->texcoord2f[0][1];
13841                 t2f[2] = decal->texcoord2f[1][0];
13842                 t2f[3] = decal->texcoord2f[1][1];
13843                 t2f[4] = decal->texcoord2f[2][0];
13844                 t2f[5] = decal->texcoord2f[2][1];
13845
13846                 // update vertex positions for animated models
13847                 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
13848                 {
13849                         e = rsurface.modelelement3i + 3*decal->triangleindex;
13850                         VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
13851                         VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
13852                         VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
13853                 }
13854                 else
13855                 {
13856                         VectorCopy(decal->vertex3f[0], v3f);
13857                         VectorCopy(decal->vertex3f[1], v3f + 3);
13858                         VectorCopy(decal->vertex3f[2], v3f + 6);
13859                 }
13860
13861                 if (r_refdef.fogenabled)
13862                 {
13863                         alpha = RSurf_FogVertex(v3f);
13864                         VectorScale(c4f, alpha, c4f);
13865                         alpha = RSurf_FogVertex(v3f + 3);
13866                         VectorScale(c4f + 4, alpha, c4f + 4);
13867                         alpha = RSurf_FogVertex(v3f + 6);
13868                         VectorScale(c4f + 8, alpha, c4f + 8);
13869                 }
13870
13871                 v3f += 9;
13872                 c4f += 12;
13873                 t2f += 6;
13874                 numtris++;
13875         }
13876
13877         if (numtris > 0)
13878         {
13879                 r_refdef.stats.drawndecals += numtris;
13880
13881                 // now render the decals all at once
13882                 // (this assumes they all use one particle font texture!)
13883                 RSurf_ActiveCustomEntity(&rsurface.matrix, &rsurface.inversematrix, rsurface.ent_flags, rsurface.ent_shadertime, 1, 1, 1, 1, numdecals*3, decalsystem->vertex3f, decalsystem->texcoord2f, NULL, NULL, NULL, decalsystem->color4f, numtris, decalsystem->element3i, decalsystem->element3s, false, false);
13884                 R_Mesh_ResetTextureState();
13885                 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
13886                 GL_DepthMask(false);
13887                 GL_DepthRange(0, 1);
13888                 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
13889                 GL_DepthTest(true);
13890                 GL_CullFace(GL_NONE);
13891                 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
13892                 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
13893                 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
13894         }
13895 }
13896
13897 static void R_DrawModelDecals(void)
13898 {
13899         int i, numdecals;
13900
13901         // fade faster when there are too many decals
13902         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13903         for (i = 0;i < r_refdef.scene.numentities;i++)
13904                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13905
13906         R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
13907         for (i = 0;i < r_refdef.scene.numentities;i++)
13908                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13909                         R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
13910
13911         R_DecalSystem_ApplySplatEntitiesQueue();
13912
13913         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13914         for (i = 0;i < r_refdef.scene.numentities;i++)
13915                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13916
13917         r_refdef.stats.totaldecals += numdecals;
13918
13919         if (r_showsurfaces.integer)
13920                 return;
13921
13922         R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
13923
13924         for (i = 0;i < r_refdef.scene.numentities;i++)
13925         {
13926                 if (!r_refdef.viewcache.entityvisible[i])
13927                         continue;
13928                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13929                         R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
13930         }
13931 }
13932
13933 extern cvar_t mod_collision_bih;
13934 void R_DrawDebugModel(void)
13935 {
13936         entity_render_t *ent = rsurface.entity;
13937         int i, j, k, l, flagsmask;
13938         const msurface_t *surface;
13939         dp_model_t *model = ent->model;
13940         vec3_t v;
13941
13942         switch(vid.renderpath)
13943         {
13944         case RENDERPATH_GL11:
13945         case RENDERPATH_GL13:
13946         case RENDERPATH_GL20:
13947         case RENDERPATH_CGGL:
13948                 break;
13949         case RENDERPATH_D3D9:
13950                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13951                 return;
13952         case RENDERPATH_D3D10:
13953                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13954                 return;
13955         case RENDERPATH_D3D11:
13956                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13957                 return;
13958         }
13959
13960         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
13961
13962         R_Mesh_ResetTextureState();
13963         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13964         GL_DepthRange(0, 1);
13965         GL_DepthTest(!r_showdisabledepthtest.integer);
13966         GL_DepthMask(false);
13967         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13968
13969         if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
13970         {
13971                 int triangleindex;
13972                 int bihleafindex;
13973                 qboolean cullbox = ent == r_refdef.scene.worldentity;
13974                 const q3mbrush_t *brush;
13975                 const bih_t *bih = &model->collision_bih;
13976                 const bih_leaf_t *bihleaf;
13977                 float vertex3f[3][3];
13978                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
13979                 cullbox = false;
13980                 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
13981                 {
13982                         if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
13983                                 continue;
13984                         switch (bihleaf->type)
13985                         {
13986                         case BIH_BRUSH:
13987                                 brush = model->brush.data_brushes + bihleaf->itemindex;
13988                                 if (brush->colbrushf && brush->colbrushf->numtriangles)
13989                                 {
13990                                         GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
13991                                         R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
13992                                         R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
13993                                 }
13994                                 break;
13995                         case BIH_COLLISIONTRIANGLE:
13996                                 triangleindex = bihleaf->itemindex;
13997                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
13998                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
13999                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
14000                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
14001                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
14002                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
14003                                 break;
14004                         case BIH_RENDERTRIANGLE:
14005                                 triangleindex = bihleaf->itemindex;
14006                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
14007                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
14008                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
14009                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
14010                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
14011                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
14012                                 break;
14013                         }
14014                 }
14015         }
14016
14017         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
14018
14019         if (r_showtris.integer || r_shownormals.integer)
14020         {
14021                 if (r_showdisabledepthtest.integer)
14022                 {
14023                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
14024                         GL_DepthMask(false);
14025                 }
14026                 else
14027                 {
14028                         GL_BlendFunc(GL_ONE, GL_ZERO);
14029                         GL_DepthMask(true);
14030                 }
14031                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
14032                 {
14033                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
14034                                 continue;
14035                         rsurface.texture = R_GetCurrentTexture(surface->texture);
14036                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
14037                         {
14038                                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
14039                                 if (r_showtris.value > 0)
14040                                 {
14041                                         if (!rsurface.texture->currentlayers->depthmask)
14042                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
14043                                         else if (ent == r_refdef.scene.worldentity)
14044                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
14045                                         else
14046                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
14047                                         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
14048                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
14049                                         RSurf_DrawBatch();
14050                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
14051                                         CHECKGLERROR
14052                                 }
14053                                 if (r_shownormals.value < 0)
14054                                 {
14055                                         qglBegin(GL_LINES);
14056                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
14057                                         {
14058                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
14059                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
14060                                                 qglVertex3f(v[0], v[1], v[2]);
14061                                                 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
14062                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
14063                                                 qglVertex3f(v[0], v[1], v[2]);
14064                                         }
14065                                         qglEnd();
14066                                         CHECKGLERROR
14067                                 }
14068                                 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
14069                                 {
14070                                         qglBegin(GL_LINES);
14071                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
14072                                         {
14073                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
14074                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
14075                                                 qglVertex3f(v[0], v[1], v[2]);
14076                                                 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
14077                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
14078                                                 qglVertex3f(v[0], v[1], v[2]);
14079                                         }
14080                                         qglEnd();
14081                                         CHECKGLERROR
14082                                         qglBegin(GL_LINES);
14083                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
14084                                         {
14085                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
14086                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
14087                                                 qglVertex3f(v[0], v[1], v[2]);
14088                                                 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
14089                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
14090                                                 qglVertex3f(v[0], v[1], v[2]);
14091                                         }
14092                                         qglEnd();
14093                                         CHECKGLERROR
14094                                         qglBegin(GL_LINES);
14095                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
14096                                         {
14097                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
14098                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
14099                                                 qglVertex3f(v[0], v[1], v[2]);
14100                                                 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
14101                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
14102                                                 qglVertex3f(v[0], v[1], v[2]);
14103                                         }
14104                                         qglEnd();
14105                                         CHECKGLERROR
14106                                 }
14107                         }
14108                 }
14109                 rsurface.texture = NULL;
14110         }
14111 }
14112
14113 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
14114 int r_maxsurfacelist = 0;
14115 const msurface_t **r_surfacelist = NULL;
14116 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
14117 {
14118         int i, j, endj, flagsmask;
14119         dp_model_t *model = r_refdef.scene.worldmodel;
14120         msurface_t *surfaces;
14121         unsigned char *update;
14122         int numsurfacelist = 0;
14123         if (model == NULL)
14124                 return;
14125
14126         if (r_maxsurfacelist < model->num_surfaces)
14127         {
14128                 r_maxsurfacelist = model->num_surfaces;
14129                 if (r_surfacelist)
14130                         Mem_Free((msurface_t**)r_surfacelist);
14131                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
14132         }
14133
14134         RSurf_ActiveWorldEntity();
14135
14136         surfaces = model->data_surfaces;
14137         update = model->brushq1.lightmapupdateflags;
14138
14139         // update light styles on this submodel
14140         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
14141         {
14142                 model_brush_lightstyleinfo_t *style;
14143                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
14144                 {
14145                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
14146                         {
14147                                 int *list = style->surfacelist;
14148                                 style->value = r_refdef.scene.lightstylevalue[style->style];
14149                                 for (j = 0;j < style->numsurfaces;j++)
14150                                         update[list[j]] = true;
14151                         }
14152                 }
14153         }
14154
14155         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
14156
14157         if (debug)
14158         {
14159                 R_DrawDebugModel();
14160                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14161                 return;
14162         }
14163
14164         rsurface.lightmaptexture = NULL;
14165         rsurface.deluxemaptexture = NULL;
14166         rsurface.uselightmaptexture = false;
14167         rsurface.texture = NULL;
14168         rsurface.rtlight = NULL;
14169         numsurfacelist = 0;
14170         // add visible surfaces to draw list
14171         for (i = 0;i < model->nummodelsurfaces;i++)
14172         {
14173                 j = model->sortedmodelsurfaces[i];
14174                 if (r_refdef.viewcache.world_surfacevisible[j])
14175                         r_surfacelist[numsurfacelist++] = surfaces + j;
14176         }
14177         // update lightmaps if needed
14178         if (model->brushq1.firstrender)
14179         {
14180                 model->brushq1.firstrender = false;
14181                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14182                         if (update[j])
14183                                 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
14184         }
14185         else if (update)
14186         {
14187                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14188                         if (r_refdef.viewcache.world_surfacevisible[j])
14189                                 if (update[j])
14190                                         R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
14191         }
14192         // don't do anything if there were no surfaces
14193         if (!numsurfacelist)
14194         {
14195                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14196                 return;
14197         }
14198         R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
14199         GL_AlphaTest(false);
14200
14201         // add to stats if desired
14202         if (r_speeds.integer && !skysurfaces && !depthonly)
14203         {
14204                 r_refdef.stats.world_surfaces += numsurfacelist;
14205                 for (j = 0;j < numsurfacelist;j++)
14206                         r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
14207         }
14208
14209         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14210 }
14211
14212 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
14213 {
14214         int i, j, endj, flagsmask;
14215         dp_model_t *model = ent->model;
14216         msurface_t *surfaces;
14217         unsigned char *update;
14218         int numsurfacelist = 0;
14219         if (model == NULL)
14220                 return;
14221
14222         if (r_maxsurfacelist < model->num_surfaces)
14223         {
14224                 r_maxsurfacelist = model->num_surfaces;
14225                 if (r_surfacelist)
14226                         Mem_Free((msurface_t **)r_surfacelist);
14227                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
14228         }
14229
14230         // if the model is static it doesn't matter what value we give for
14231         // wantnormals and wanttangents, so this logic uses only rules applicable
14232         // to a model, knowing that they are meaningless otherwise
14233         if (ent == r_refdef.scene.worldentity)
14234                 RSurf_ActiveWorldEntity();
14235         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
14236                 RSurf_ActiveModelEntity(ent, false, false, false);
14237         else if (prepass)
14238                 RSurf_ActiveModelEntity(ent, true, true, true);
14239         else if (depthonly)
14240         {
14241                 switch (vid.renderpath)
14242                 {
14243                 case RENDERPATH_GL20:
14244                 case RENDERPATH_CGGL:
14245                 case RENDERPATH_D3D9:
14246                 case RENDERPATH_D3D10:
14247                 case RENDERPATH_D3D11:
14248                         RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
14249                         break;
14250                 case RENDERPATH_GL13:
14251                 case RENDERPATH_GL11:
14252                         RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
14253                         break;
14254                 }
14255         }
14256         else
14257         {
14258                 switch (vid.renderpath)
14259                 {
14260                 case RENDERPATH_GL20:
14261                 case RENDERPATH_CGGL:
14262                 case RENDERPATH_D3D9:
14263                 case RENDERPATH_D3D10:
14264                 case RENDERPATH_D3D11:
14265                         RSurf_ActiveModelEntity(ent, true, true, false);
14266                         break;
14267                 case RENDERPATH_GL13:
14268                 case RENDERPATH_GL11:
14269                         RSurf_ActiveModelEntity(ent, true, false, false);
14270                         break;
14271                 }
14272         }
14273
14274         surfaces = model->data_surfaces;
14275         update = model->brushq1.lightmapupdateflags;
14276
14277         // update light styles
14278         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
14279         {
14280                 model_brush_lightstyleinfo_t *style;
14281                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
14282                 {
14283                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
14284                         {
14285                                 int *list = style->surfacelist;
14286                                 style->value = r_refdef.scene.lightstylevalue[style->style];
14287                                 for (j = 0;j < style->numsurfaces;j++)
14288                                         update[list[j]] = true;
14289                         }
14290                 }
14291         }
14292
14293         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
14294
14295         if (debug)
14296         {
14297                 R_DrawDebugModel();
14298                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14299                 return;
14300         }
14301
14302         rsurface.lightmaptexture = NULL;
14303         rsurface.deluxemaptexture = NULL;
14304         rsurface.uselightmaptexture = false;
14305         rsurface.texture = NULL;
14306         rsurface.rtlight = NULL;
14307         numsurfacelist = 0;
14308         // add visible surfaces to draw list
14309         for (i = 0;i < model->nummodelsurfaces;i++)
14310                 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
14311         // don't do anything if there were no surfaces
14312         if (!numsurfacelist)
14313         {
14314                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14315                 return;
14316         }
14317         // update lightmaps if needed
14318         if (update)
14319         {
14320                 int updated = 0;
14321                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14322                 {
14323                         if (update[j])
14324                         {
14325                                 updated++;
14326                                 R_BuildLightMap(ent, surfaces + j);
14327                         }
14328                 }
14329         }
14330         if (update)
14331                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14332                         if (update[j])
14333                                 R_BuildLightMap(ent, surfaces + j);
14334         R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
14335         GL_AlphaTest(false);
14336
14337         // add to stats if desired
14338         if (r_speeds.integer && !skysurfaces && !depthonly)
14339         {
14340                 r_refdef.stats.entities_surfaces += numsurfacelist;
14341                 for (j = 0;j < numsurfacelist;j++)
14342                         r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
14343         }
14344
14345         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14346 }
14347
14348 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14349 {
14350         static texture_t texture;
14351         static msurface_t surface;
14352         const msurface_t *surfacelist = &surface;
14353
14354         // fake enough texture and surface state to render this geometry
14355
14356         texture.update_lastrenderframe = -1; // regenerate this texture
14357         texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
14358         texture.currentskinframe = skinframe;
14359         texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
14360         texture.offsetmapping = OFFSETMAPPING_OFF;
14361         texture.offsetscale = 1;
14362         texture.specularscalemod = 1;
14363         texture.specularpowermod = 1;
14364
14365         surface.texture = &texture;
14366         surface.num_triangles = numtriangles;
14367         surface.num_firsttriangle = firsttriangle;
14368         surface.num_vertices = numvertices;
14369         surface.num_firstvertex = firstvertex;
14370
14371         // now render it
14372         rsurface.texture = R_GetCurrentTexture(surface.texture);
14373         rsurface.lightmaptexture = NULL;
14374         rsurface.deluxemaptexture = NULL;
14375         rsurface.uselightmaptexture = false;
14376         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14377 }
14378
14379 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14380 {
14381         static msurface_t surface;
14382         const msurface_t *surfacelist = &surface;
14383
14384         // fake enough texture and surface state to render this geometry
14385
14386         surface.texture = texture;
14387         surface.num_triangles = numtriangles;
14388         surface.num_firsttriangle = firsttriangle;
14389         surface.num_vertices = numvertices;
14390         surface.num_firstvertex = firstvertex;
14391
14392         // now render it
14393         rsurface.texture = R_GetCurrentTexture(surface.texture);
14394         rsurface.lightmaptexture = NULL;
14395         rsurface.deluxemaptexture = NULL;
14396         rsurface.uselightmaptexture = false;
14397         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14398 }