]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
disable offsetmapping where TEXF_ALPHA is not set and no height bias exists
[xonotic/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142 #include "dpsoftrast.h"
143
144 #ifdef SUPPORTD3D
145 #include <d3d9.h>
146 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
147 #endif
148
149 extern void R_Shadow_EditLights_Init(void);
150
151 typedef enum r_shadow_rendermode_e
152 {
153         R_SHADOW_RENDERMODE_NONE,
154         R_SHADOW_RENDERMODE_ZPASS_STENCIL,
155         R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL,
156         R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE,
157         R_SHADOW_RENDERMODE_ZFAIL_STENCIL,
158         R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL,
159         R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE,
160         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
161         R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN,
162         R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN,
163         R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN,
164         R_SHADOW_RENDERMODE_LIGHT_GLSL,
165         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
166         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
167         R_SHADOW_RENDERMODE_SHADOWMAP2D
168 }
169 r_shadow_rendermode_t;
170
171 typedef enum r_shadow_shadowmode_e
172 {
173     R_SHADOW_SHADOWMODE_STENCIL,
174     R_SHADOW_SHADOWMODE_SHADOWMAP2D
175 }
176 r_shadow_shadowmode_t;
177
178 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
179 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
180 r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE;
181 r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE;
182 qboolean r_shadow_usingshadowmap2d;
183 qboolean r_shadow_usingshadowmaportho;
184 int r_shadow_shadowmapside;
185 float r_shadow_shadowmap_texturescale[2];
186 float r_shadow_shadowmap_parameters[4];
187 #if 0
188 int r_shadow_drawbuffer;
189 int r_shadow_readbuffer;
190 #endif
191 int r_shadow_cullface_front, r_shadow_cullface_back;
192 GLuint r_shadow_fbo2d;
193 r_shadow_shadowmode_t r_shadow_shadowmode;
194 int r_shadow_shadowmapfilterquality;
195 int r_shadow_shadowmapdepthbits;
196 int r_shadow_shadowmapmaxsize;
197 qboolean r_shadow_shadowmapvsdct;
198 qboolean r_shadow_shadowmapsampler;
199 int r_shadow_shadowmappcf;
200 int r_shadow_shadowmapborder;
201 matrix4x4_t r_shadow_shadowmapmatrix;
202 int r_shadow_lightscissor[4];
203 qboolean r_shadow_usingdeferredprepass;
204
205 int maxshadowtriangles;
206 int *shadowelements;
207
208 int maxshadowvertices;
209 float *shadowvertex3f;
210
211 int maxshadowmark;
212 int numshadowmark;
213 int *shadowmark;
214 int *shadowmarklist;
215 int shadowmarkcount;
216
217 int maxshadowsides;
218 int numshadowsides;
219 unsigned char *shadowsides;
220 int *shadowsideslist;
221
222 int maxvertexupdate;
223 int *vertexupdate;
224 int *vertexremap;
225 int vertexupdatenum;
226
227 int r_shadow_buffer_numleafpvsbytes;
228 unsigned char *r_shadow_buffer_visitingleafpvs;
229 unsigned char *r_shadow_buffer_leafpvs;
230 int *r_shadow_buffer_leaflist;
231
232 int r_shadow_buffer_numsurfacepvsbytes;
233 unsigned char *r_shadow_buffer_surfacepvs;
234 int *r_shadow_buffer_surfacelist;
235 unsigned char *r_shadow_buffer_surfacesides;
236
237 int r_shadow_buffer_numshadowtrispvsbytes;
238 unsigned char *r_shadow_buffer_shadowtrispvs;
239 int r_shadow_buffer_numlighttrispvsbytes;
240 unsigned char *r_shadow_buffer_lighttrispvs;
241
242 rtexturepool_t *r_shadow_texturepool;
243 rtexture_t *r_shadow_attenuationgradienttexture;
244 rtexture_t *r_shadow_attenuation2dtexture;
245 rtexture_t *r_shadow_attenuation3dtexture;
246 skinframe_t *r_shadow_lightcorona;
247 rtexture_t *r_shadow_shadowmap2dtexture;
248 rtexture_t *r_shadow_shadowmap2dcolortexture;
249 rtexture_t *r_shadow_shadowmapvsdcttexture;
250 int r_shadow_shadowmapsize; // changes for each light based on distance
251 int r_shadow_shadowmaplod; // changes for each light based on distance
252
253 GLuint r_shadow_prepassgeometryfbo;
254 GLuint r_shadow_prepasslightingdiffusespecularfbo;
255 GLuint r_shadow_prepasslightingdiffusefbo;
256 int r_shadow_prepass_width;
257 int r_shadow_prepass_height;
258 rtexture_t *r_shadow_prepassgeometrydepthtexture;
259 rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
260 rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
261 rtexture_t *r_shadow_prepasslightingdiffusetexture;
262 rtexture_t *r_shadow_prepasslightingspeculartexture;
263
264 // lights are reloaded when this changes
265 char r_shadow_mapname[MAX_QPATH];
266
267 // used only for light filters (cubemaps)
268 rtexturepool_t *r_shadow_filters_texturepool;
269
270 #ifndef USE_GLES2
271 static const GLenum r_shadow_prepasslightingdrawbuffers[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
272 #endif
273
274 cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"};
275 cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"};
276 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
277 cvar_t r_shadow_deferred = {CVAR_SAVE, "r_shadow_deferred", "0", "uses image-based lighting instead of geometry-based lighting, the method used renders a depth image and a normalmap image, renders lights into separate diffuse and specular images, and then combines this into the normal rendering, requires r_shadow_shadowmapping"};
278 cvar_t r_shadow_deferred_8bitrange = {CVAR_SAVE, "r_shadow_deferred_8bitrange", "4", "dynamic range of image-based lighting when using 32bit color (does not apply to fp)"};
279 //cvar_t r_shadow_deferred_fp = {CVAR_SAVE, "r_shadow_deferred_fp", "0", "use 16bit (1) or 32bit (2) floating point for accumulation of image-based lighting"};
280 cvar_t r_shadow_usebihculling = {0, "r_shadow_usebihculling", "1", "use BIH (Bounding Interval Hierarchy) for culling lit surfaces instead of BSP (Binary Space Partitioning)"};
281 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
282 cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"};
283 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
284 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
285 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
286 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
287 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
288 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
289 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
290 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
291 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
292 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"};
293 cvar_t r_shadow_frontsidecasting = {0, "r_shadow_frontsidecasting", "1", "whether to cast shadows from illuminated triangles (front side of model) or unlit triangles (back side of model)"};
294 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
295 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
296 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
297 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
298 cvar_t r_shadow_realtime_world = {CVAR_SAVE, "r_shadow_realtime_world", "0", "enables rendering of full world lighting (whether loaded from the map, or a .rtlights file, or a .ent file, or a .lights file produced by hlight)"};
299 cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_lightmaps", "0", "brightness to render lightmaps when using full world lighting, try 0.5 for a tenebrae-like appearance"};
300 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
301 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
302 cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"};
303 cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation (slower than compileportalculling but more exact)"};
304 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"};
305 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"};
306 cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "1", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"};
307 cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "-1", "shadowmap filter modes: -1 = auto-select, 0 = no filtering, 1 = bilinear, 2 = bilinear 2x2 blur (fast), 3 = 3x3 blur (moderate), 4 = 4x4 blur (slow)"};
308 cvar_t r_shadow_shadowmapping_depthbits = {CVAR_SAVE, "r_shadow_shadowmapping_depthbits", "24", "requested minimum shadowmap texture depth bits"};
309 cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"};
310 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
311 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
312 cvar_t r_shadow_shadowmapping_precision = {CVAR_SAVE, "r_shadow_shadowmapping_precision", "1", "makes shadowmaps have a maximum resolution of this number of pixels per light source radius unit such that, for example, at precision 0.5 a light with radius 200 will have a maximum resolution of 100 pixels"};
313 //cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
314 //cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
315 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
316 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
317 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
318 cvar_t r_shadow_shadowmapping_polygonfactor = {CVAR_SAVE, "r_shadow_shadowmapping_polygonfactor", "2", "slope-dependent shadowmapping bias"};
319 cvar_t r_shadow_shadowmapping_polygonoffset = {CVAR_SAVE, "r_shadow_shadowmapping_polygonoffset", "0", "constant shadowmapping bias"};
320 cvar_t r_shadow_sortsurfaces = {0, "r_shadow_sortsurfaces", "1", "improve performance by sorting illuminated surfaces by texture"};
321 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
322 cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"};
323 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect OpenGL 2.0 render path)"};
324 cvar_t r_shadow_bouncegrid = {CVAR_SAVE, "r_shadow_bouncegrid", "0", "perform particle tracing for indirect lighting (Global Illumination / radiosity) using a 3D texture covering the scene, only active on levels with realtime lights active (r_shadow_realtime_world is usually required for these)"};
325 cvar_t r_shadow_bouncegrid_bounceanglediffuse = {CVAR_SAVE, "r_shadow_bouncegrid_bounceanglediffuse", "0", "use random bounce direction rather than true reflection, makes some corner areas dark"};
326 cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 8x as many pixels to hold the additional data"};
327 cvar_t r_shadow_bouncegrid_dlightparticlemultiplier = {CVAR_SAVE, "r_shadow_bouncegrid_dlightparticlemultiplier", "0", "if set to a high value like 16 this can make dlights look great, but 0 is recommended for performance reasons"};
328 cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"};
329 cvar_t r_shadow_bouncegrid_includedirectlighting = {CVAR_SAVE, "r_shadow_bouncegrid_includedirectlighting", "0", "allows direct lighting to be recorded, not just indirect (gives an effect somewhat like r_shadow_realtime_world_lightmaps)"};
330 cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"};
331 cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "4", "particles stop at this fraction of light radius (can be more than 1)"};
332 cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "2", "maximum number of bounces for a particle (minimum is 0)"};
333 cvar_t r_shadow_bouncegrid_particlebounceintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particlebounceintensity", "1", "amount of energy carried over after each bounce, this is a multiplier of texture color and the result is clamped to 1 or less, to prevent adding energy on each bounce"};
334 cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"};
335 cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"};
336 cvar_t r_shadow_bouncegrid_spacing = {CVAR_SAVE, "r_shadow_bouncegrid_spacing", "64", "unit size of bouncegrid pixel"};
337 cvar_t r_shadow_bouncegrid_stablerandom = {CVAR_SAVE, "r_shadow_bouncegrid_stablerandom", "1", "make particle distribution consistent from frame to frame"};
338 cvar_t r_shadow_bouncegrid_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"};
339 cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"};
340 cvar_t r_shadow_bouncegrid_static_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_static_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1) when in static mode"};
341 cvar_t r_shadow_bouncegrid_static_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_static_maxbounce", "5", "maximum number of bounces for a particle (minimum is 0) in static mode"};
342 cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"};
343 cvar_t r_shadow_bouncegrid_updateinterval = {CVAR_SAVE, "r_shadow_bouncegrid_updateinterval", "0", "update bouncegrid texture once per this many seconds, useful values are 0, 0.05, or 1000000"};
344 cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"};
345 cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"};
346 cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"};
347 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
348 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"};
349 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
350 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
351 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
352 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
353 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
354 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
355 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
356 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
357 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
358 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
359
360 typedef struct r_shadow_bouncegrid_settings_s
361 {
362         qboolean staticmode;
363         qboolean bounceanglediffuse;
364         qboolean directionalshading;
365         qboolean includedirectlighting;
366         float dlightparticlemultiplier;
367         qboolean hitmodels;
368         float lightradiusscale;
369         int maxbounce;
370         float particlebounceintensity;
371         float particleintensity;
372         int photons;
373         float spacing[3];
374         int stablerandom;
375 }
376 r_shadow_bouncegrid_settings_t;
377
378 r_shadow_bouncegrid_settings_t r_shadow_bouncegridsettings;
379 rtexture_t *r_shadow_bouncegridtexture;
380 matrix4x4_t r_shadow_bouncegridmatrix;
381 vec_t r_shadow_bouncegridintensity;
382 qboolean r_shadow_bouncegriddirectional;
383 static double r_shadow_bouncegridtime;
384 static int r_shadow_bouncegridresolution[3];
385 static int r_shadow_bouncegridnumpixels;
386 static unsigned char *r_shadow_bouncegridpixels;
387 static float *r_shadow_bouncegridhighpixels;
388
389 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
390 #define ATTENTABLESIZE 256
391 // 1D gradient, 2D circle and 3D sphere attenuation textures
392 #define ATTEN1DSIZE 32
393 #define ATTEN2DSIZE 64
394 #define ATTEN3DSIZE 32
395
396 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
397 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
398 static float r_shadow_attentable[ATTENTABLESIZE+1];
399
400 rtlight_t *r_shadow_compilingrtlight;
401 static memexpandablearray_t r_shadow_worldlightsarray;
402 dlight_t *r_shadow_selectedlight;
403 dlight_t r_shadow_bufferlight;
404 vec3_t r_editlights_cursorlocation;
405 qboolean r_editlights_lockcursor;
406
407 extern int con_vislines;
408
409 void R_Shadow_UncompileWorldLights(void);
410 void R_Shadow_ClearWorldLights(void);
411 void R_Shadow_SaveWorldLights(void);
412 void R_Shadow_LoadWorldLights(void);
413 void R_Shadow_LoadLightsFile(void);
414 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
415 void R_Shadow_EditLights_Reload_f(void);
416 void R_Shadow_ValidateCvars(void);
417 static void R_Shadow_MakeTextures(void);
418
419 #define EDLIGHTSPRSIZE                  8
420 skinframe_t *r_editlights_sprcursor;
421 skinframe_t *r_editlights_sprlight;
422 skinframe_t *r_editlights_sprnoshadowlight;
423 skinframe_t *r_editlights_sprcubemaplight;
424 skinframe_t *r_editlights_sprcubemapnoshadowlight;
425 skinframe_t *r_editlights_sprselection;
426
427 void R_Shadow_SetShadowMode(void)
428 {
429         r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4);
430         r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20;
431         r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
432         r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
433         r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
434         r_shadow_shadowmaplod = -1;
435         r_shadow_shadowmapsize = 0;
436         r_shadow_shadowmapsampler = false;
437         r_shadow_shadowmappcf = 0;
438         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
439         if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
440         {
441                 switch(vid.renderpath)
442                 {
443                 case RENDERPATH_GL20:
444                         if(r_shadow_shadowmapfilterquality < 0)
445                         {
446                                 if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
447                                         r_shadow_shadowmappcf = 1;
448                                 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) 
449                                 {
450                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
451                                         r_shadow_shadowmappcf = 1;
452                                 }
453                                 else if(strstr(gl_vendor, "ATI")) 
454                                         r_shadow_shadowmappcf = 1;
455                                 else 
456                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
457                         }
458                         else 
459                         {
460                                 switch (r_shadow_shadowmapfilterquality)
461                                 {
462                                 case 1:
463                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
464                                         break;
465                                 case 2:
466                                         r_shadow_shadowmapsampler = vid.support.arb_shadow;
467                                         r_shadow_shadowmappcf = 1;
468                                         break;
469                                 case 3:
470                                         r_shadow_shadowmappcf = 1;
471                                         break;
472                                 case 4:
473                                         r_shadow_shadowmappcf = 2;
474                                         break;
475                                 }
476                         }
477                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
478                         break;
479                 case RENDERPATH_D3D9:
480                 case RENDERPATH_D3D10:
481                 case RENDERPATH_D3D11:
482                 case RENDERPATH_SOFT:
483                         r_shadow_shadowmapsampler = false;
484                         r_shadow_shadowmappcf = 1;
485                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
486                         break;
487                 case RENDERPATH_GL11:
488                 case RENDERPATH_GL13:
489                 case RENDERPATH_GLES1:
490                 case RENDERPATH_GLES2:
491                         break;
492                 }
493         }
494 }
495
496 qboolean R_Shadow_ShadowMappingEnabled(void)
497 {
498         switch (r_shadow_shadowmode)
499         {
500         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
501                 return true;
502         default:
503                 return false;
504         }
505 }
506
507 void R_Shadow_FreeShadowMaps(void)
508 {
509         R_Shadow_SetShadowMode();
510
511         R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
512
513         r_shadow_fbo2d = 0;
514
515         if (r_shadow_shadowmap2dtexture)
516                 R_FreeTexture(r_shadow_shadowmap2dtexture);
517         r_shadow_shadowmap2dtexture = NULL;
518
519         if (r_shadow_shadowmap2dcolortexture)
520                 R_FreeTexture(r_shadow_shadowmap2dcolortexture);
521         r_shadow_shadowmap2dcolortexture = NULL;
522
523         if (r_shadow_shadowmapvsdcttexture)
524                 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
525         r_shadow_shadowmapvsdcttexture = NULL;
526 }
527
528 void r_shadow_start(void)
529 {
530         // allocate vertex processing arrays
531         r_shadow_bouncegridpixels = NULL;
532         r_shadow_bouncegridhighpixels = NULL;
533         r_shadow_bouncegridnumpixels = 0;
534         r_shadow_bouncegridtexture = NULL;
535         r_shadow_bouncegriddirectional = false;
536         r_shadow_attenuationgradienttexture = NULL;
537         r_shadow_attenuation2dtexture = NULL;
538         r_shadow_attenuation3dtexture = NULL;
539         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
540         r_shadow_shadowmap2dtexture = NULL;
541         r_shadow_shadowmap2dcolortexture = NULL;
542         r_shadow_shadowmapvsdcttexture = NULL;
543         r_shadow_shadowmapmaxsize = 0;
544         r_shadow_shadowmapsize = 0;
545         r_shadow_shadowmaplod = 0;
546         r_shadow_shadowmapfilterquality = -1;
547         r_shadow_shadowmapdepthbits = 0;
548         r_shadow_shadowmapvsdct = false;
549         r_shadow_shadowmapsampler = false;
550         r_shadow_shadowmappcf = 0;
551         r_shadow_fbo2d = 0;
552
553         R_Shadow_FreeShadowMaps();
554
555         r_shadow_texturepool = NULL;
556         r_shadow_filters_texturepool = NULL;
557         R_Shadow_ValidateCvars();
558         R_Shadow_MakeTextures();
559         maxshadowtriangles = 0;
560         shadowelements = NULL;
561         maxshadowvertices = 0;
562         shadowvertex3f = NULL;
563         maxvertexupdate = 0;
564         vertexupdate = NULL;
565         vertexremap = NULL;
566         vertexupdatenum = 0;
567         maxshadowmark = 0;
568         numshadowmark = 0;
569         shadowmark = NULL;
570         shadowmarklist = NULL;
571         shadowmarkcount = 0;
572         maxshadowsides = 0;
573         numshadowsides = 0;
574         shadowsides = NULL;
575         shadowsideslist = NULL;
576         r_shadow_buffer_numleafpvsbytes = 0;
577         r_shadow_buffer_visitingleafpvs = NULL;
578         r_shadow_buffer_leafpvs = NULL;
579         r_shadow_buffer_leaflist = NULL;
580         r_shadow_buffer_numsurfacepvsbytes = 0;
581         r_shadow_buffer_surfacepvs = NULL;
582         r_shadow_buffer_surfacelist = NULL;
583         r_shadow_buffer_surfacesides = NULL;
584         r_shadow_buffer_numshadowtrispvsbytes = 0;
585         r_shadow_buffer_shadowtrispvs = NULL;
586         r_shadow_buffer_numlighttrispvsbytes = 0;
587         r_shadow_buffer_lighttrispvs = NULL;
588
589         r_shadow_usingdeferredprepass = false;
590         r_shadow_prepass_width = r_shadow_prepass_height = 0;
591 }
592
593 static void R_Shadow_FreeDeferred(void);
594 void r_shadow_shutdown(void)
595 {
596         CHECKGLERROR
597         R_Shadow_UncompileWorldLights();
598
599         R_Shadow_FreeShadowMaps();
600
601         r_shadow_usingdeferredprepass = false;
602         if (r_shadow_prepass_width)
603                 R_Shadow_FreeDeferred();
604         r_shadow_prepass_width = r_shadow_prepass_height = 0;
605
606         CHECKGLERROR
607         r_shadow_bouncegridtexture = NULL;
608         r_shadow_bouncegridpixels = NULL;
609         r_shadow_bouncegridhighpixels = NULL;
610         r_shadow_bouncegridnumpixels = 0;
611         r_shadow_bouncegriddirectional = false;
612         r_shadow_attenuationgradienttexture = NULL;
613         r_shadow_attenuation2dtexture = NULL;
614         r_shadow_attenuation3dtexture = NULL;
615         R_FreeTexturePool(&r_shadow_texturepool);
616         R_FreeTexturePool(&r_shadow_filters_texturepool);
617         maxshadowtriangles = 0;
618         if (shadowelements)
619                 Mem_Free(shadowelements);
620         shadowelements = NULL;
621         if (shadowvertex3f)
622                 Mem_Free(shadowvertex3f);
623         shadowvertex3f = NULL;
624         maxvertexupdate = 0;
625         if (vertexupdate)
626                 Mem_Free(vertexupdate);
627         vertexupdate = NULL;
628         if (vertexremap)
629                 Mem_Free(vertexremap);
630         vertexremap = NULL;
631         vertexupdatenum = 0;
632         maxshadowmark = 0;
633         numshadowmark = 0;
634         if (shadowmark)
635                 Mem_Free(shadowmark);
636         shadowmark = NULL;
637         if (shadowmarklist)
638                 Mem_Free(shadowmarklist);
639         shadowmarklist = NULL;
640         shadowmarkcount = 0;
641         maxshadowsides = 0;
642         numshadowsides = 0;
643         if (shadowsides)
644                 Mem_Free(shadowsides);
645         shadowsides = NULL;
646         if (shadowsideslist)
647                 Mem_Free(shadowsideslist);
648         shadowsideslist = NULL;
649         r_shadow_buffer_numleafpvsbytes = 0;
650         if (r_shadow_buffer_visitingleafpvs)
651                 Mem_Free(r_shadow_buffer_visitingleafpvs);
652         r_shadow_buffer_visitingleafpvs = NULL;
653         if (r_shadow_buffer_leafpvs)
654                 Mem_Free(r_shadow_buffer_leafpvs);
655         r_shadow_buffer_leafpvs = NULL;
656         if (r_shadow_buffer_leaflist)
657                 Mem_Free(r_shadow_buffer_leaflist);
658         r_shadow_buffer_leaflist = NULL;
659         r_shadow_buffer_numsurfacepvsbytes = 0;
660         if (r_shadow_buffer_surfacepvs)
661                 Mem_Free(r_shadow_buffer_surfacepvs);
662         r_shadow_buffer_surfacepvs = NULL;
663         if (r_shadow_buffer_surfacelist)
664                 Mem_Free(r_shadow_buffer_surfacelist);
665         r_shadow_buffer_surfacelist = NULL;
666         if (r_shadow_buffer_surfacesides)
667                 Mem_Free(r_shadow_buffer_surfacesides);
668         r_shadow_buffer_surfacesides = NULL;
669         r_shadow_buffer_numshadowtrispvsbytes = 0;
670         if (r_shadow_buffer_shadowtrispvs)
671                 Mem_Free(r_shadow_buffer_shadowtrispvs);
672         r_shadow_buffer_numlighttrispvsbytes = 0;
673         if (r_shadow_buffer_lighttrispvs)
674                 Mem_Free(r_shadow_buffer_lighttrispvs);
675 }
676
677 void r_shadow_newmap(void)
678 {
679         if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
680         if (r_shadow_lightcorona)                 R_SkinFrame_MarkUsed(r_shadow_lightcorona);
681         if (r_editlights_sprcursor)               R_SkinFrame_MarkUsed(r_editlights_sprcursor);
682         if (r_editlights_sprlight)                R_SkinFrame_MarkUsed(r_editlights_sprlight);
683         if (r_editlights_sprnoshadowlight)        R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
684         if (r_editlights_sprcubemaplight)         R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
685         if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
686         if (r_editlights_sprselection)            R_SkinFrame_MarkUsed(r_editlights_sprselection);
687         if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
688                 R_Shadow_EditLights_Reload_f();
689 }
690
691 void R_Shadow_Init(void)
692 {
693         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
694         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
695         Cvar_RegisterVariable(&r_shadow_usebihculling);
696         Cvar_RegisterVariable(&r_shadow_usenormalmap);
697         Cvar_RegisterVariable(&r_shadow_debuglight);
698         Cvar_RegisterVariable(&r_shadow_deferred);
699         Cvar_RegisterVariable(&r_shadow_deferred_8bitrange);
700 //      Cvar_RegisterVariable(&r_shadow_deferred_fp);
701         Cvar_RegisterVariable(&r_shadow_gloss);
702         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
703         Cvar_RegisterVariable(&r_shadow_glossintensity);
704         Cvar_RegisterVariable(&r_shadow_glossexponent);
705         Cvar_RegisterVariable(&r_shadow_gloss2exponent);
706         Cvar_RegisterVariable(&r_shadow_glossexact);
707         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
708         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
709         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
710         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
711         Cvar_RegisterVariable(&r_shadow_projectdistance);
712         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
713         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
714         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
715         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
716         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
717         Cvar_RegisterVariable(&r_shadow_realtime_world);
718         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
719         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
720         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
721         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
722         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
723         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
724         Cvar_RegisterVariable(&r_shadow_scissor);
725         Cvar_RegisterVariable(&r_shadow_shadowmapping);
726         Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
727         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
728         Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
729         Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
730         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
731         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
732 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
733 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
734         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
735         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
736         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
737         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
738         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
739         Cvar_RegisterVariable(&r_shadow_sortsurfaces);
740         Cvar_RegisterVariable(&r_shadow_polygonfactor);
741         Cvar_RegisterVariable(&r_shadow_polygonoffset);
742         Cvar_RegisterVariable(&r_shadow_texture3d);
743         Cvar_RegisterVariable(&r_shadow_bouncegrid);
744         Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
745         Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
746         Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
747         Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
748         Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting);
749         Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
750         Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
751         Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
752         Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
753         Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
754         Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
755         Cvar_RegisterVariable(&r_shadow_bouncegrid_spacing);
756         Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
757         Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
758         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
759         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_lightradiusscale);
760         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_maxbounce);
761         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
762         Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
763         Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
764         Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
765         Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
766         Cvar_RegisterVariable(&r_coronas);
767         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
768         Cvar_RegisterVariable(&r_coronas_occlusionquery);
769         Cvar_RegisterVariable(&gl_flashblend);
770         Cvar_RegisterVariable(&gl_ext_separatestencil);
771         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
772         R_Shadow_EditLights_Init();
773         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
774         maxshadowtriangles = 0;
775         shadowelements = NULL;
776         maxshadowvertices = 0;
777         shadowvertex3f = NULL;
778         maxvertexupdate = 0;
779         vertexupdate = NULL;
780         vertexremap = NULL;
781         vertexupdatenum = 0;
782         maxshadowmark = 0;
783         numshadowmark = 0;
784         shadowmark = NULL;
785         shadowmarklist = NULL;
786         shadowmarkcount = 0;
787         maxshadowsides = 0;
788         numshadowsides = 0;
789         shadowsides = NULL;
790         shadowsideslist = NULL;
791         r_shadow_buffer_numleafpvsbytes = 0;
792         r_shadow_buffer_visitingleafpvs = NULL;
793         r_shadow_buffer_leafpvs = NULL;
794         r_shadow_buffer_leaflist = NULL;
795         r_shadow_buffer_numsurfacepvsbytes = 0;
796         r_shadow_buffer_surfacepvs = NULL;
797         r_shadow_buffer_surfacelist = NULL;
798         r_shadow_buffer_surfacesides = NULL;
799         r_shadow_buffer_shadowtrispvs = NULL;
800         r_shadow_buffer_lighttrispvs = NULL;
801         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
802 }
803
804 matrix4x4_t matrix_attenuationxyz =
805 {
806         {
807                 {0.5, 0.0, 0.0, 0.5},
808                 {0.0, 0.5, 0.0, 0.5},
809                 {0.0, 0.0, 0.5, 0.5},
810                 {0.0, 0.0, 0.0, 1.0}
811         }
812 };
813
814 matrix4x4_t matrix_attenuationz =
815 {
816         {
817                 {0.0, 0.0, 0.5, 0.5},
818                 {0.0, 0.0, 0.0, 0.5},
819                 {0.0, 0.0, 0.0, 0.5},
820                 {0.0, 0.0, 0.0, 1.0}
821         }
822 };
823
824 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
825 {
826         numvertices = ((numvertices + 255) & ~255) * vertscale;
827         numtriangles = ((numtriangles + 255) & ~255) * triscale;
828         // make sure shadowelements is big enough for this volume
829         if (maxshadowtriangles < numtriangles)
830         {
831                 maxshadowtriangles = numtriangles;
832                 if (shadowelements)
833                         Mem_Free(shadowelements);
834                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
835         }
836         // make sure shadowvertex3f is big enough for this volume
837         if (maxshadowvertices < numvertices)
838         {
839                 maxshadowvertices = numvertices;
840                 if (shadowvertex3f)
841                         Mem_Free(shadowvertex3f);
842                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
843         }
844 }
845
846 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
847 {
848         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
849         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
850         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
851         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
852         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
853         {
854                 if (r_shadow_buffer_visitingleafpvs)
855                         Mem_Free(r_shadow_buffer_visitingleafpvs);
856                 if (r_shadow_buffer_leafpvs)
857                         Mem_Free(r_shadow_buffer_leafpvs);
858                 if (r_shadow_buffer_leaflist)
859                         Mem_Free(r_shadow_buffer_leaflist);
860                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
861                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
862                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
863                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
864         }
865         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
866         {
867                 if (r_shadow_buffer_surfacepvs)
868                         Mem_Free(r_shadow_buffer_surfacepvs);
869                 if (r_shadow_buffer_surfacelist)
870                         Mem_Free(r_shadow_buffer_surfacelist);
871                 if (r_shadow_buffer_surfacesides)
872                         Mem_Free(r_shadow_buffer_surfacesides);
873                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
874                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
875                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
876                 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
877         }
878         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
879         {
880                 if (r_shadow_buffer_shadowtrispvs)
881                         Mem_Free(r_shadow_buffer_shadowtrispvs);
882                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
883                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
884         }
885         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
886         {
887                 if (r_shadow_buffer_lighttrispvs)
888                         Mem_Free(r_shadow_buffer_lighttrispvs);
889                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
890                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
891         }
892 }
893
894 void R_Shadow_PrepareShadowMark(int numtris)
895 {
896         // make sure shadowmark is big enough for this volume
897         if (maxshadowmark < numtris)
898         {
899                 maxshadowmark = numtris;
900                 if (shadowmark)
901                         Mem_Free(shadowmark);
902                 if (shadowmarklist)
903                         Mem_Free(shadowmarklist);
904                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
905                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
906                 shadowmarkcount = 0;
907         }
908         shadowmarkcount++;
909         // if shadowmarkcount wrapped we clear the array and adjust accordingly
910         if (shadowmarkcount == 0)
911         {
912                 shadowmarkcount = 1;
913                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
914         }
915         numshadowmark = 0;
916 }
917
918 void R_Shadow_PrepareShadowSides(int numtris)
919 {
920     if (maxshadowsides < numtris)
921     {
922         maxshadowsides = numtris;
923         if (shadowsides)
924                         Mem_Free(shadowsides);
925                 if (shadowsideslist)
926                         Mem_Free(shadowsideslist);
927                 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
928                 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
929         }
930         numshadowsides = 0;
931 }
932
933 static int R_Shadow_ConstructShadowVolume_ZFail(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
934 {
935         int i, j;
936         int outtriangles = 0, outvertices = 0;
937         const int *element;
938         const float *vertex;
939         float ratio, direction[3], projectvector[3];
940
941         if (projectdirection)
942                 VectorScale(projectdirection, projectdistance, projectvector);
943         else
944                 VectorClear(projectvector);
945
946         // create the vertices
947         if (projectdirection)
948         {
949                 for (i = 0;i < numshadowmarktris;i++)
950                 {
951                         element = inelement3i + shadowmarktris[i] * 3;
952                         for (j = 0;j < 3;j++)
953                         {
954                                 if (vertexupdate[element[j]] != vertexupdatenum)
955                                 {
956                                         vertexupdate[element[j]] = vertexupdatenum;
957                                         vertexremap[element[j]] = outvertices;
958                                         vertex = invertex3f + element[j] * 3;
959                                         // project one copy of the vertex according to projectvector
960                                         VectorCopy(vertex, outvertex3f);
961                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
962                                         outvertex3f += 6;
963                                         outvertices += 2;
964                                 }
965                         }
966                 }
967         }
968         else
969         {
970                 for (i = 0;i < numshadowmarktris;i++)
971                 {
972                         element = inelement3i + shadowmarktris[i] * 3;
973                         for (j = 0;j < 3;j++)
974                         {
975                                 if (vertexupdate[element[j]] != vertexupdatenum)
976                                 {
977                                         vertexupdate[element[j]] = vertexupdatenum;
978                                         vertexremap[element[j]] = outvertices;
979                                         vertex = invertex3f + element[j] * 3;
980                                         // project one copy of the vertex to the sphere radius of the light
981                                         // (FIXME: would projecting it to the light box be better?)
982                                         VectorSubtract(vertex, projectorigin, direction);
983                                         ratio = projectdistance / VectorLength(direction);
984                                         VectorCopy(vertex, outvertex3f);
985                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
986                                         outvertex3f += 6;
987                                         outvertices += 2;
988                                 }
989                         }
990                 }
991         }
992
993         if (r_shadow_frontsidecasting.integer)
994         {
995                 for (i = 0;i < numshadowmarktris;i++)
996                 {
997                         int remappedelement[3];
998                         int markindex;
999                         const int *neighbortriangle;
1000
1001                         markindex = shadowmarktris[i] * 3;
1002                         element = inelement3i + markindex;
1003                         neighbortriangle = inneighbor3i + markindex;
1004                         // output the front and back triangles
1005                         outelement3i[0] = vertexremap[element[0]];
1006                         outelement3i[1] = vertexremap[element[1]];
1007                         outelement3i[2] = vertexremap[element[2]];
1008                         outelement3i[3] = vertexremap[element[2]] + 1;
1009                         outelement3i[4] = vertexremap[element[1]] + 1;
1010                         outelement3i[5] = vertexremap[element[0]] + 1;
1011
1012                         outelement3i += 6;
1013                         outtriangles += 2;
1014                         // output the sides (facing outward from this triangle)
1015                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1016                         {
1017                                 remappedelement[0] = vertexremap[element[0]];
1018                                 remappedelement[1] = vertexremap[element[1]];
1019                                 outelement3i[0] = remappedelement[1];
1020                                 outelement3i[1] = remappedelement[0];
1021                                 outelement3i[2] = remappedelement[0] + 1;
1022                                 outelement3i[3] = remappedelement[1];
1023                                 outelement3i[4] = remappedelement[0] + 1;
1024                                 outelement3i[5] = remappedelement[1] + 1;
1025
1026                                 outelement3i += 6;
1027                                 outtriangles += 2;
1028                         }
1029                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1030                         {
1031                                 remappedelement[1] = vertexremap[element[1]];
1032                                 remappedelement[2] = vertexremap[element[2]];
1033                                 outelement3i[0] = remappedelement[2];
1034                                 outelement3i[1] = remappedelement[1];
1035                                 outelement3i[2] = remappedelement[1] + 1;
1036                                 outelement3i[3] = remappedelement[2];
1037                                 outelement3i[4] = remappedelement[1] + 1;
1038                                 outelement3i[5] = remappedelement[2] + 1;
1039
1040                                 outelement3i += 6;
1041                                 outtriangles += 2;
1042                         }
1043                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1044                         {
1045                                 remappedelement[0] = vertexremap[element[0]];
1046                                 remappedelement[2] = vertexremap[element[2]];
1047                                 outelement3i[0] = remappedelement[0];
1048                                 outelement3i[1] = remappedelement[2];
1049                                 outelement3i[2] = remappedelement[2] + 1;
1050                                 outelement3i[3] = remappedelement[0];
1051                                 outelement3i[4] = remappedelement[2] + 1;
1052                                 outelement3i[5] = remappedelement[0] + 1;
1053
1054                                 outelement3i += 6;
1055                                 outtriangles += 2;
1056                         }
1057                 }
1058         }
1059         else
1060         {
1061                 for (i = 0;i < numshadowmarktris;i++)
1062                 {
1063                         int remappedelement[3];
1064                         int markindex;
1065                         const int *neighbortriangle;
1066
1067                         markindex = shadowmarktris[i] * 3;
1068                         element = inelement3i + markindex;
1069                         neighbortriangle = inneighbor3i + markindex;
1070                         // output the front and back triangles
1071                         outelement3i[0] = vertexremap[element[2]];
1072                         outelement3i[1] = vertexremap[element[1]];
1073                         outelement3i[2] = vertexremap[element[0]];
1074                         outelement3i[3] = vertexremap[element[0]] + 1;
1075                         outelement3i[4] = vertexremap[element[1]] + 1;
1076                         outelement3i[5] = vertexremap[element[2]] + 1;
1077
1078                         outelement3i += 6;
1079                         outtriangles += 2;
1080                         // output the sides (facing outward from this triangle)
1081                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1082                         {
1083                                 remappedelement[0] = vertexremap[element[0]];
1084                                 remappedelement[1] = vertexremap[element[1]];
1085                                 outelement3i[0] = remappedelement[0];
1086                                 outelement3i[1] = remappedelement[1];
1087                                 outelement3i[2] = remappedelement[1] + 1;
1088                                 outelement3i[3] = remappedelement[0];
1089                                 outelement3i[4] = remappedelement[1] + 1;
1090                                 outelement3i[5] = remappedelement[0] + 1;
1091
1092                                 outelement3i += 6;
1093                                 outtriangles += 2;
1094                         }
1095                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1096                         {
1097                                 remappedelement[1] = vertexremap[element[1]];
1098                                 remappedelement[2] = vertexremap[element[2]];
1099                                 outelement3i[0] = remappedelement[1];
1100                                 outelement3i[1] = remappedelement[2];
1101                                 outelement3i[2] = remappedelement[2] + 1;
1102                                 outelement3i[3] = remappedelement[1];
1103                                 outelement3i[4] = remappedelement[2] + 1;
1104                                 outelement3i[5] = remappedelement[1] + 1;
1105
1106                                 outelement3i += 6;
1107                                 outtriangles += 2;
1108                         }
1109                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1110                         {
1111                                 remappedelement[0] = vertexremap[element[0]];
1112                                 remappedelement[2] = vertexremap[element[2]];
1113                                 outelement3i[0] = remappedelement[2];
1114                                 outelement3i[1] = remappedelement[0];
1115                                 outelement3i[2] = remappedelement[0] + 1;
1116                                 outelement3i[3] = remappedelement[2];
1117                                 outelement3i[4] = remappedelement[0] + 1;
1118                                 outelement3i[5] = remappedelement[2] + 1;
1119
1120                                 outelement3i += 6;
1121                                 outtriangles += 2;
1122                         }
1123                 }
1124         }
1125         if (outnumvertices)
1126                 *outnumvertices = outvertices;
1127         return outtriangles;
1128 }
1129
1130 static int R_Shadow_ConstructShadowVolume_ZPass(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
1131 {
1132         int i, j, k;
1133         int outtriangles = 0, outvertices = 0;
1134         const int *element;
1135         const float *vertex;
1136         float ratio, direction[3], projectvector[3];
1137         qboolean side[4];
1138
1139         if (projectdirection)
1140                 VectorScale(projectdirection, projectdistance, projectvector);
1141         else
1142                 VectorClear(projectvector);
1143
1144         for (i = 0;i < numshadowmarktris;i++)
1145         {
1146                 int remappedelement[3];
1147                 int markindex;
1148                 const int *neighbortriangle;
1149
1150                 markindex = shadowmarktris[i] * 3;
1151                 neighbortriangle = inneighbor3i + markindex;
1152                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1153                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1154                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1155                 if (side[0] + side[1] + side[2] == 0)
1156                         continue;
1157
1158                 side[3] = side[0];
1159                 element = inelement3i + markindex;
1160
1161                 // create the vertices
1162                 for (j = 0;j < 3;j++)
1163                 {
1164                         if (side[j] + side[j+1] == 0)
1165                                 continue;
1166                         k = element[j];
1167                         if (vertexupdate[k] != vertexupdatenum)
1168                         {
1169                                 vertexupdate[k] = vertexupdatenum;
1170                                 vertexremap[k] = outvertices;
1171                                 vertex = invertex3f + k * 3;
1172                                 VectorCopy(vertex, outvertex3f);
1173                                 if (projectdirection)
1174                                 {
1175                                         // project one copy of the vertex according to projectvector
1176                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
1177                                 }
1178                                 else
1179                                 {
1180                                         // project one copy of the vertex to the sphere radius of the light
1181                                         // (FIXME: would projecting it to the light box be better?)
1182                                         VectorSubtract(vertex, projectorigin, direction);
1183                                         ratio = projectdistance / VectorLength(direction);
1184                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1185                                 }
1186                                 outvertex3f += 6;
1187                                 outvertices += 2;
1188                         }
1189                 }
1190
1191                 // output the sides (facing outward from this triangle)
1192                 if (!side[0])
1193                 {
1194                         remappedelement[0] = vertexremap[element[0]];
1195                         remappedelement[1] = vertexremap[element[1]];
1196                         outelement3i[0] = remappedelement[1];
1197                         outelement3i[1] = remappedelement[0];
1198                         outelement3i[2] = remappedelement[0] + 1;
1199                         outelement3i[3] = remappedelement[1];
1200                         outelement3i[4] = remappedelement[0] + 1;
1201                         outelement3i[5] = remappedelement[1] + 1;
1202
1203                         outelement3i += 6;
1204                         outtriangles += 2;
1205                 }
1206                 if (!side[1])
1207                 {
1208                         remappedelement[1] = vertexremap[element[1]];
1209                         remappedelement[2] = vertexremap[element[2]];
1210                         outelement3i[0] = remappedelement[2];
1211                         outelement3i[1] = remappedelement[1];
1212                         outelement3i[2] = remappedelement[1] + 1;
1213                         outelement3i[3] = remappedelement[2];
1214                         outelement3i[4] = remappedelement[1] + 1;
1215                         outelement3i[5] = remappedelement[2] + 1;
1216
1217                         outelement3i += 6;
1218                         outtriangles += 2;
1219                 }
1220                 if (!side[2])
1221                 {
1222                         remappedelement[0] = vertexremap[element[0]];
1223                         remappedelement[2] = vertexremap[element[2]];
1224                         outelement3i[0] = remappedelement[0];
1225                         outelement3i[1] = remappedelement[2];
1226                         outelement3i[2] = remappedelement[2] + 1;
1227                         outelement3i[3] = remappedelement[0];
1228                         outelement3i[4] = remappedelement[2] + 1;
1229                         outelement3i[5] = remappedelement[0] + 1;
1230
1231                         outelement3i += 6;
1232                         outtriangles += 2;
1233                 }
1234         }
1235         if (outnumvertices)
1236                 *outnumvertices = outvertices;
1237         return outtriangles;
1238 }
1239
1240 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
1241 {
1242         int t, tend;
1243         const int *e;
1244         const float *v[3];
1245         float normal[3];
1246         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1247                 return;
1248         tend = firsttriangle + numtris;
1249         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1250         {
1251                 // surface box entirely inside light box, no box cull
1252                 if (projectdirection)
1253                 {
1254                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1255                         {
1256                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1257                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1258                                         shadowmarklist[numshadowmark++] = t;
1259                         }
1260                 }
1261                 else
1262                 {
1263                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1264                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1265                                         shadowmarklist[numshadowmark++] = t;
1266                 }
1267         }
1268         else
1269         {
1270                 // surface box not entirely inside light box, cull each triangle
1271                 if (projectdirection)
1272                 {
1273                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1274                         {
1275                                 v[0] = invertex3f + e[0] * 3;
1276                                 v[1] = invertex3f + e[1] * 3;
1277                                 v[2] = invertex3f + e[2] * 3;
1278                                 TriangleNormal(v[0], v[1], v[2], normal);
1279                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1280                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1281                                         shadowmarklist[numshadowmark++] = t;
1282                         }
1283                 }
1284                 else
1285                 {
1286                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1287                         {
1288                                 v[0] = invertex3f + e[0] * 3;
1289                                 v[1] = invertex3f + e[1] * 3;
1290                                 v[2] = invertex3f + e[2] * 3;
1291                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1292                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1293                                         shadowmarklist[numshadowmark++] = t;
1294                         }
1295                 }
1296         }
1297 }
1298
1299 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1300 {
1301 #if 1
1302         return false;
1303 #else
1304         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1305                 return false;
1306         // check if the shadow volume intersects the near plane
1307         //
1308         // a ray between the eye and light origin may intersect the caster,
1309         // indicating that the shadow may touch the eye location, however we must
1310         // test the near plane (a polygon), not merely the eye location, so it is
1311         // easiest to enlarge the caster bounding shape slightly for this.
1312         // TODO
1313         return true;
1314 #endif
1315 }
1316
1317 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris, vec3_t trismins, vec3_t trismaxs)
1318 {
1319         int i, tris, outverts;
1320         if (projectdistance < 0.1)
1321         {
1322                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1323                 return;
1324         }
1325         if (!numverts || !nummarktris)
1326                 return;
1327         // make sure shadowelements is big enough for this volume
1328         if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1329                 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1330
1331         if (maxvertexupdate < numverts)
1332         {
1333                 maxvertexupdate = numverts;
1334                 if (vertexupdate)
1335                         Mem_Free(vertexupdate);
1336                 if (vertexremap)
1337                         Mem_Free(vertexremap);
1338                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1339                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1340                 vertexupdatenum = 0;
1341         }
1342         vertexupdatenum++;
1343         if (vertexupdatenum == 0)
1344         {
1345                 vertexupdatenum = 1;
1346                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1347                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1348         }
1349
1350         for (i = 0;i < nummarktris;i++)
1351                 shadowmark[marktris[i]] = shadowmarkcount;
1352
1353         if (r_shadow_compilingrtlight)
1354         {
1355                 // if we're compiling an rtlight, capture the mesh
1356                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1357                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1358                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1359                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1360         }
1361         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1362         {
1363                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1364                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1365                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1366         }
1367         else
1368         {
1369                 // decide which type of shadow to generate and set stencil mode
1370                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1371                 // generate the sides or a solid volume, depending on type
1372                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1373                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1374                 else
1375                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1376                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1377                 r_refdef.stats.lights_shadowtriangles += tris;
1378                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1379                 {
1380                         // increment stencil if frontface is infront of depthbuffer
1381                         GL_CullFace(r_refdef.view.cullface_front);
1382                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1383                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1384                         // decrement stencil if backface is infront of depthbuffer
1385                         GL_CullFace(r_refdef.view.cullface_back);
1386                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1387                 }
1388                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1389                 {
1390                         // decrement stencil if backface is behind depthbuffer
1391                         GL_CullFace(r_refdef.view.cullface_front);
1392                         R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1393                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1394                         // increment stencil if frontface is behind depthbuffer
1395                         GL_CullFace(r_refdef.view.cullface_back);
1396                         R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1397                 }
1398                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1399                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1400         }
1401 }
1402
1403 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1404 {
1405     // p1, p2, p3 are in the cubemap's local coordinate system
1406     // bias = border/(size - border)
1407         int mask = 0x3F;
1408
1409     float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1410           dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1411           dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1412         if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1413         mask &= (3<<4)
1414                         | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1415                         | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1416                         | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1417     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1418         mask &= (3<<4)
1419             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1420             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))            
1421             | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1422
1423     dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1424     dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1425     dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1426     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1427         mask &= (3<<0)
1428             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1429             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))            
1430             | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1431     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1432         mask &= (3<<0)
1433             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1434             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1435             | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1436
1437     dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1438     dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1439     dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1440     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1441         mask &= (3<<2)
1442             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1443             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1444             | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1445     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1446         mask &= (3<<2)
1447             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1448             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1449             | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1450
1451         return mask;
1452 }
1453
1454 int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1455 {
1456         vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1457         float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1458         int mask = 0x3F;
1459
1460         VectorSubtract(maxs, mins, radius);
1461     VectorScale(radius, 0.5f, radius);
1462     VectorAdd(mins, radius, center);
1463     Matrix4x4_Transform(worldtolight, center, lightcenter);
1464         Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1465         VectorSubtract(lightcenter, lightradius, pmin);
1466         VectorAdd(lightcenter, lightradius, pmax);
1467
1468     dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1469     dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1470     if(ap1 > bias*an1 && ap2 > bias*an2)
1471         mask &= (3<<4)
1472             | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1473             | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1474     if(an1 > bias*ap1 && an2 > bias*ap2)
1475         mask &= (3<<4)
1476             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1477             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1478
1479     dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1480     dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1481     if(ap1 > bias*an1 && ap2 > bias*an2)
1482         mask &= (3<<0)
1483             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1484             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1485     if(an1 > bias*ap1 && an2 > bias*ap2)
1486         mask &= (3<<0)
1487             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1488             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1489
1490     dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1491     dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1492     if(ap1 > bias*an1 && ap2 > bias*an2)
1493         mask &= (3<<2)
1494             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1495             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1496     if(an1 > bias*ap1 && an2 > bias*ap2)
1497         mask &= (3<<2)
1498             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1499             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1500
1501     return mask;
1502 }
1503
1504 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1505
1506 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1507 {
1508     // p is in the cubemap's local coordinate system
1509     // bias = border/(size - border)
1510     float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1511     float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1512     float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1513     int mask = 0x3F;
1514     if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1515     if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1516     if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1517     if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1518     if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1519     if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1520     return mask;
1521 }
1522
1523 int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1524 {
1525         int i;
1526         vec3_t p, n;
1527         int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1528         float scale = (size - 2*border)/size, len;
1529         float bias = border / (float)(size - border), dp, dn, ap, an;
1530         // check if cone enclosing side would cross frustum plane 
1531         scale = 2 / (scale*scale + 2);
1532         for (i = 0;i < 5;i++)
1533         {
1534                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1535                         continue;
1536                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1537                 len = scale*VectorLength2(n);
1538                 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1539                 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1540                 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1541         }
1542         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1543         {
1544         Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1545         len = scale*VectorLength(n);
1546                 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1547                 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1548                 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1549         }
1550         // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1551         // check if frustum corners/origin cross plane sides
1552 #if 1
1553     // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1554     Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1555     dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1556     masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1557     masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1558     dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1559     masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1560     masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1561     dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1562     masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1563     masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1564     for (i = 0;i < 4;i++)
1565     {
1566         Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1567         VectorSubtract(n, p, n);
1568         dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1569         if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1570         if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1571         dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1572         if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1573         if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1574         dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1575         if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1576         if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1577     }
1578 #else
1579     // finite version, assumes corners are a finite distance from origin dependent on far plane
1580         for (i = 0;i < 5;i++)
1581         {
1582                 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1583                 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1584                 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1585                 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1586                 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1587                 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1588                 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1589                 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1590                 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1591                 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1592         }
1593 #endif
1594         return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1595 }
1596
1597 int R_Shadow_ChooseSidesFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const matrix4x4_t *worldtolight, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs, int *totals)
1598 {
1599         int t, tend;
1600         const int *e;
1601         const float *v[3];
1602         float normal[3];
1603         vec3_t p[3];
1604         float bias;
1605         int mask, surfacemask = 0;
1606         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1607                 return 0;
1608         bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1609         tend = firsttriangle + numtris;
1610         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1611         {
1612                 // surface box entirely inside light box, no box cull
1613                 if (projectdirection)
1614                 {
1615                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1616                         {
1617                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1618                                 TriangleNormal(v[0], v[1], v[2], normal);
1619                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1620                                 {
1621                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1622                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1623                                         surfacemask |= mask;
1624                                         if(totals)
1625                                         {
1626                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1627                                                 shadowsides[numshadowsides] = mask;
1628                                                 shadowsideslist[numshadowsides++] = t;
1629                                         }
1630                                 }
1631                         }
1632                 }
1633                 else
1634                 {
1635                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1636                         {
1637                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1638                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1639                                 {
1640                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1641                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1642                                         surfacemask |= mask;
1643                                         if(totals)
1644                                         {
1645                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1646                                                 shadowsides[numshadowsides] = mask;
1647                                                 shadowsideslist[numshadowsides++] = t;
1648                                         }
1649                                 }
1650                         }
1651                 }
1652         }
1653         else
1654         {
1655                 // surface box not entirely inside light box, cull each triangle
1656                 if (projectdirection)
1657                 {
1658                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1659                         {
1660                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1661                                 TriangleNormal(v[0], v[1], v[2], normal);
1662                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1663                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1664                                 {
1665                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1666                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1667                                         surfacemask |= mask;
1668                                         if(totals)
1669                                         {
1670                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1671                                                 shadowsides[numshadowsides] = mask;
1672                                                 shadowsideslist[numshadowsides++] = t;
1673                                         }
1674                                 }
1675                         }
1676                 }
1677                 else
1678                 {
1679                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1680                         {
1681                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1682                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1683                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1684                                 {
1685                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1686                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1687                                         surfacemask |= mask;
1688                                         if(totals)
1689                                         {
1690                                                 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1691                                                 shadowsides[numshadowsides] = mask;
1692                                                 shadowsideslist[numshadowsides++] = t;
1693                                         }
1694                                 }
1695                         }
1696                 }
1697         }
1698         return surfacemask;
1699 }
1700
1701 void R_Shadow_ShadowMapFromList(int numverts, int numtris, const float *vertex3f, const int *elements, int numsidetris, const int *sidetotals, const unsigned char *sides, const int *sidetris)
1702 {
1703         int i, j, outtriangles = 0;
1704         int *outelement3i[6];
1705         if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1706                 return;
1707         outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1708         // make sure shadowelements is big enough for this mesh
1709         if (maxshadowtriangles < outtriangles)
1710                 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1711
1712         // compute the offset and size of the separate index lists for each cubemap side
1713         outtriangles = 0;
1714         for (i = 0;i < 6;i++)
1715         {
1716                 outelement3i[i] = shadowelements + outtriangles * 3;
1717                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1718                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1719                 outtriangles += sidetotals[i];
1720         }
1721
1722         // gather up the (sparse) triangles into separate index lists for each cubemap side
1723         for (i = 0;i < numsidetris;i++)
1724         {
1725                 const int *element = elements + sidetris[i] * 3;
1726                 for (j = 0;j < 6;j++)
1727                 {
1728                         if (sides[i] & (1 << j))
1729                         {
1730                                 outelement3i[j][0] = element[0];
1731                                 outelement3i[j][1] = element[1];
1732                                 outelement3i[j][2] = element[2];
1733                                 outelement3i[j] += 3;
1734                         }
1735                 }
1736         }
1737                         
1738         Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1739 }
1740
1741 static void R_Shadow_MakeTextures_MakeCorona(void)
1742 {
1743         float dx, dy;
1744         int x, y, a;
1745         unsigned char pixels[32][32][4];
1746         for (y = 0;y < 32;y++)
1747         {
1748                 dy = (y - 15.5f) * (1.0f / 16.0f);
1749                 for (x = 0;x < 32;x++)
1750                 {
1751                         dx = (x - 15.5f) * (1.0f / 16.0f);
1752                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1753                         a = bound(0, a, 255);
1754                         pixels[y][x][0] = a;
1755                         pixels[y][x][1] = a;
1756                         pixels[y][x][2] = a;
1757                         pixels[y][x][3] = 255;
1758                 }
1759         }
1760         r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1761 }
1762
1763 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1764 {
1765         float dist = sqrt(x*x+y*y+z*z);
1766         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1767         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1768         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1769 }
1770
1771 static void R_Shadow_MakeTextures(void)
1772 {
1773         int x, y, z;
1774         float intensity, dist;
1775         unsigned int *data;
1776         R_Shadow_FreeShadowMaps();
1777         R_FreeTexturePool(&r_shadow_texturepool);
1778         r_shadow_texturepool = R_AllocTexturePool();
1779         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1780         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1781         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1782         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1783         for (x = 0;x <= ATTENTABLESIZE;x++)
1784         {
1785                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1786                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1787                 r_shadow_attentable[x] = bound(0, intensity, 1);
1788         }
1789         // 1D gradient texture
1790         for (x = 0;x < ATTEN1DSIZE;x++)
1791                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1792         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1793         // 2D circle texture
1794         for (y = 0;y < ATTEN2DSIZE;y++)
1795                 for (x = 0;x < ATTEN2DSIZE;x++)
1796                         data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0);
1797         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1798         // 3D sphere texture
1799         if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1800         {
1801                 for (z = 0;z < ATTEN3DSIZE;z++)
1802                         for (y = 0;y < ATTEN3DSIZE;y++)
1803                                 for (x = 0;x < ATTEN3DSIZE;x++)
1804                                         data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375));
1805                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1806         }
1807         else
1808                 r_shadow_attenuation3dtexture = NULL;
1809         Mem_Free(data);
1810
1811         R_Shadow_MakeTextures_MakeCorona();
1812
1813         // Editor light sprites
1814         r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1815         "................"
1816         ".3............3."
1817         "..5...2332...5.."
1818         "...7.3....3.7..."
1819         "....7......7...."
1820         "...3.7....7.3..."
1821         "..2...7..7...2.."
1822         "..3..........3.."
1823         "..3..........3.."
1824         "..2...7..7...2.."
1825         "...3.7....7.3..."
1826         "....7......7...."
1827         "...7.3....3.7..."
1828         "..5...2332...5.."
1829         ".3............3."
1830         "................"
1831         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1832         r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1833         "................"
1834         "................"
1835         "......1111......"
1836         "....11233211...."
1837         "...1234554321..."
1838         "...1356776531..."
1839         "..124677776421.."
1840         "..135777777531.."
1841         "..135777777531.."
1842         "..124677776421.."
1843         "...1356776531..."
1844         "...1234554321..."
1845         "....11233211...."
1846         "......1111......"
1847         "................"
1848         "................"
1849         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1850         r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1851         "................"
1852         "................"
1853         "......1111......"
1854         "....11233211...."
1855         "...1234554321..."
1856         "...1356226531..."
1857         "..12462..26421.."
1858         "..1352....2531.."
1859         "..1352....2531.."
1860         "..12462..26421.."
1861         "...1356226531..."
1862         "...1234554321..."
1863         "....11233211...."
1864         "......1111......"
1865         "................"
1866         "................"
1867         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1868         r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1869         "................"
1870         "................"
1871         "......2772......"
1872         "....27755772...."
1873         "..277533335772.."
1874         "..753333333357.."
1875         "..777533335777.."
1876         "..735775577537.."
1877         "..733357753337.."
1878         "..733337733337.."
1879         "..753337733357.."
1880         "..277537735772.."
1881         "....27777772...."
1882         "......2772......"
1883         "................"
1884         "................"
1885         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1886         r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1887         "................"
1888         "................"
1889         "......2772......"
1890         "....27722772...."
1891         "..2772....2772.."
1892         "..72........27.."
1893         "..7772....2777.."
1894         "..7.27722772.7.."
1895         "..7...2772...7.."
1896         "..7....77....7.."
1897         "..72...77...27.."
1898         "..2772.77.2772.."
1899         "....27777772...."
1900         "......2772......"
1901         "................"
1902         "................"
1903         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1904         r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1905         "................"
1906         ".777752..257777."
1907         ".742........247."
1908         ".72..........27."
1909         ".7............7."
1910         ".5............5."
1911         ".2............2."
1912         "................"
1913         "................"
1914         ".2............2."
1915         ".5............5."
1916         ".7............7."
1917         ".72..........27."
1918         ".742........247."
1919         ".777752..257777."
1920         "................"
1921         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1922 }
1923
1924 void R_Shadow_ValidateCvars(void)
1925 {
1926         if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1927                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1928         if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1929                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1930         if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1931                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1932 }
1933
1934 void R_Shadow_RenderMode_Begin(void)
1935 {
1936 #if 0
1937         GLint drawbuffer;
1938         GLint readbuffer;
1939 #endif
1940         R_Shadow_ValidateCvars();
1941
1942         if (!r_shadow_attenuation2dtexture
1943          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1944          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1945          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1946                 R_Shadow_MakeTextures();
1947
1948         CHECKGLERROR
1949         R_Mesh_ResetTextureState();
1950         GL_BlendFunc(GL_ONE, GL_ZERO);
1951         GL_DepthRange(0, 1);
1952         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1953         GL_DepthTest(true);
1954         GL_DepthMask(false);
1955         GL_Color(0, 0, 0, 1);
1956         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1957         
1958         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1959
1960         if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1961         {
1962                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1963                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1964         }
1965         else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1966         {
1967                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1968                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1969         }
1970         else
1971         {
1972                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1973                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1974         }
1975
1976         switch(vid.renderpath)
1977         {
1978         case RENDERPATH_GL20:
1979         case RENDERPATH_D3D9:
1980         case RENDERPATH_D3D10:
1981         case RENDERPATH_D3D11:
1982         case RENDERPATH_SOFT:
1983         case RENDERPATH_GLES2:
1984                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1985                 break;
1986         case RENDERPATH_GL11:
1987         case RENDERPATH_GL13:
1988         case RENDERPATH_GLES1:
1989                 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
1990                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
1991                 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
1992                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
1993                 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
1994                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
1995                 else
1996                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
1997                 break;
1998         }
1999
2000         CHECKGLERROR
2001 #if 0
2002         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2003         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2004         r_shadow_drawbuffer = drawbuffer;
2005         r_shadow_readbuffer = readbuffer;
2006 #endif
2007         r_shadow_cullface_front = r_refdef.view.cullface_front;
2008         r_shadow_cullface_back = r_refdef.view.cullface_back;
2009 }
2010
2011 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2012 {
2013         rsurface.rtlight = rtlight;
2014 }
2015
2016 void R_Shadow_RenderMode_Reset(void)
2017 {
2018         R_Mesh_SetMainRenderTargets();
2019         R_SetViewport(&r_refdef.view.viewport);
2020         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2021         R_Mesh_ResetTextureState();
2022         GL_DepthRange(0, 1);
2023         GL_DepthTest(true);
2024         GL_DepthMask(false);
2025         GL_DepthFunc(GL_LEQUAL);
2026         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2027         r_refdef.view.cullface_front = r_shadow_cullface_front;
2028         r_refdef.view.cullface_back = r_shadow_cullface_back;
2029         GL_CullFace(r_refdef.view.cullface_back);
2030         GL_Color(1, 1, 1, 1);
2031         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2032         GL_BlendFunc(GL_ONE, GL_ZERO);
2033         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
2034         r_shadow_usingshadowmap2d = false;
2035         r_shadow_usingshadowmaportho = false;
2036         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2037 }
2038
2039 void R_Shadow_ClearStencil(void)
2040 {
2041         GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2042         r_refdef.stats.lights_clears++;
2043 }
2044
2045 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2046 {
2047         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2048         if (r_shadow_rendermode == mode)
2049                 return;
2050         R_Shadow_RenderMode_Reset();
2051         GL_DepthFunc(GL_LESS);
2052         GL_ColorMask(0, 0, 0, 0);
2053         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2054         GL_CullFace(GL_NONE);
2055         R_SetupShader_DepthOrShadow(false);
2056         r_shadow_rendermode = mode;
2057         switch(mode)
2058         {
2059         default:
2060                 break;
2061         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2062         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2063                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2064                 break;
2065         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2066         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2067                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2068                 break;
2069         }
2070 }
2071
2072 static void R_Shadow_MakeVSDCT(void)
2073 {
2074         // maps to a 2x3 texture rectangle with normalized coordinates
2075         // +-
2076         // XX
2077         // YY
2078         // ZZ
2079         // stores abs(dir.xy), offset.xy/2.5
2080         unsigned char data[4*6] =
2081         {
2082                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2083                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2084                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2085                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2086                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2087                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2088         };
2089         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2090 }
2091
2092 static void R_Shadow_MakeShadowMap(int side, int size)
2093 {
2094         switch (r_shadow_shadowmode)
2095         {
2096         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2097                 if (r_shadow_shadowmap2dtexture) return;
2098                 r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
2099                 r_shadow_shadowmap2dcolortexture = NULL;
2100                 switch(vid.renderpath)
2101                 {
2102 #ifdef SUPPORTD3D
2103                 case RENDERPATH_D3D9:
2104                         r_shadow_shadowmap2dcolortexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_BGRA, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2105                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2106                         break;
2107 #endif
2108                 default:
2109                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
2110                         break;
2111                 }
2112                 break;
2113         default:
2114                 return;
2115         }
2116
2117 #ifndef USE_GLES2
2118         // render depth into the fbo, do not render color at all
2119         // validate the fbo now
2120         if (qglDrawBuffer)
2121         {
2122                 int status;
2123                 qglDrawBuffer(GL_NONE);CHECKGLERROR
2124                 qglReadBuffer(GL_NONE);CHECKGLERROR
2125                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER);CHECKGLERROR
2126                 if (status != GL_FRAMEBUFFER_COMPLETE && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
2127                 {
2128                         Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
2129                         Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
2130                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
2131                 }
2132         }
2133 #endif
2134 }
2135
2136 void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2137 {
2138         float nearclip, farclip, bias;
2139         r_viewport_t viewport;
2140         int flipped;
2141         GLuint fbo = 0;
2142         float clearcolor[4];
2143         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2144         farclip = 1.0f;
2145         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2146         r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2147         r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2148         r_shadow_shadowmapside = side;
2149         r_shadow_shadowmapsize = size;
2150
2151         r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2152         r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2153         R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2154         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2155
2156         // complex unrolled cube approach (more flexible)
2157         if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2158                 R_Shadow_MakeVSDCT();
2159         if (!r_shadow_shadowmap2dtexture)
2160                 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2161         if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d;
2162         r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
2163         r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
2164         r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2165
2166         R_Mesh_ResetTextureState();
2167         R_Shadow_RenderMode_Reset();
2168         R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2169         R_SetupShader_DepthOrShadow(true);
2170         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2171         GL_DepthMask(true);
2172         GL_DepthTest(true);
2173
2174 init_done:
2175         R_SetViewport(&viewport);
2176         flipped = (side & 1) ^ (side >> 2);
2177         r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2178         r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2179         switch(vid.renderpath)
2180         {
2181         case RENDERPATH_GL11:
2182         case RENDERPATH_GL13:
2183         case RENDERPATH_GL20:
2184         case RENDERPATH_SOFT:
2185         case RENDERPATH_GLES1:
2186         case RENDERPATH_GLES2:
2187                 GL_CullFace(r_refdef.view.cullface_back);
2188                 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2189                 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2190                 {
2191                         // get tightest scissor rectangle that encloses all viewports in the clear mask
2192                         int x1 = clear & 0x15 ? 0 : size;
2193                         int x2 = clear & 0x2A ? 2 * size : size;
2194                         int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2195                         int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2196                         GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2197                         GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
2198                 }
2199                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2200                 break;
2201         case RENDERPATH_D3D9:
2202         case RENDERPATH_D3D10:
2203         case RENDERPATH_D3D11:
2204                 Vector4Set(clearcolor, 1,1,1,1);
2205                 // completely different meaning than in OpenGL path
2206                 r_shadow_shadowmap_parameters[1] = 0;
2207                 r_shadow_shadowmap_parameters[3] = -bias;
2208                 // we invert the cull mode because we flip the projection matrix
2209                 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2210                 GL_CullFace(r_refdef.view.cullface_front);
2211                 // D3D considers it an error to use a scissor larger than the viewport...  clear just this view
2212                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2213                 if (r_shadow_shadowmapsampler)
2214                 {
2215                         GL_ColorMask(0,0,0,0);
2216                         if (clear)
2217                                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2218                 }
2219                 else
2220                 {
2221                         GL_ColorMask(1,1,1,1);
2222                         if (clear)
2223                                 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2224                 }
2225                 break;
2226         }
2227 }
2228
2229 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2230 {
2231         R_Mesh_ResetTextureState();
2232         R_Mesh_SetMainRenderTargets();
2233         if (transparent)
2234         {
2235                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2236                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2237                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2238                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2239         }
2240         R_Shadow_RenderMode_Reset();
2241         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2242         if (!transparent)
2243                 GL_DepthFunc(GL_EQUAL);
2244         // do global setup needed for the chosen lighting mode
2245         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2246                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2247         r_shadow_usingshadowmap2d = shadowmapping;
2248         r_shadow_rendermode = r_shadow_lightingrendermode;
2249         // only draw light where this geometry was already rendered AND the
2250         // stencil is 128 (values other than this mean shadow)
2251         if (stenciltest)
2252                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2253         else
2254                 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2255 }
2256
2257 static const unsigned short bboxelements[36] =
2258 {
2259         5, 1, 3, 5, 3, 7,
2260         6, 2, 0, 6, 0, 4,
2261         7, 3, 2, 7, 2, 6,
2262         4, 0, 1, 4, 1, 5,
2263         4, 5, 7, 4, 7, 6,
2264         1, 0, 2, 1, 2, 3,
2265 };
2266
2267 static const float bboxpoints[8][3] =
2268 {
2269         {-1,-1,-1},
2270         { 1,-1,-1},
2271         {-1, 1,-1},
2272         { 1, 1,-1},
2273         {-1,-1, 1},
2274         { 1,-1, 1},
2275         {-1, 1, 1},
2276         { 1, 1, 1},
2277 };
2278
2279 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2280 {
2281         int i;
2282         float vertex3f[8*3];
2283         const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2284 // do global setup needed for the chosen lighting mode
2285         R_Shadow_RenderMode_Reset();
2286         r_shadow_rendermode = r_shadow_lightingrendermode;
2287         R_EntityMatrix(&identitymatrix);
2288         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2289         // only draw light where this geometry was already rendered AND the
2290         // stencil is 128 (values other than this mean shadow)
2291         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2292         if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2293                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2294         else
2295                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2296
2297         r_shadow_usingshadowmap2d = shadowmapping;
2298
2299         // render the lighting
2300         R_SetupShader_DeferredLight(rsurface.rtlight);
2301         for (i = 0;i < 8;i++)
2302                 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2303         GL_ColorMask(1,1,1,1);
2304         GL_DepthMask(false);
2305         GL_DepthRange(0, 1);
2306         GL_PolygonOffset(0, 0);
2307         GL_DepthTest(true);
2308         GL_DepthFunc(GL_GREATER);
2309         GL_CullFace(r_refdef.view.cullface_back);
2310         R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2311         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2312 }
2313
2314 void R_Shadow_UpdateBounceGridTexture(void)
2315 {
2316 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2317         dlight_t *light;
2318         int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2319         int bouncecount;
2320         int hitsupercontentsmask;
2321         int maxbounce;
2322         int numpixels;
2323         int resolution[3];
2324         int shootparticles;
2325         int shotparticles;
2326         int photoncount;
2327         int tex[3];
2328         trace_t cliptrace;
2329         //trace_t cliptrace2;
2330         //trace_t cliptrace3;
2331         unsigned char *pixel;
2332         unsigned char *pixels;
2333         float *highpixel;
2334         float *highpixels;
2335         unsigned int lightindex;
2336         unsigned int range;
2337         unsigned int range1;
2338         unsigned int range2;
2339         unsigned int seed = (unsigned int)(realtime * 1000.0f);
2340         vec3_t shotcolor;
2341         vec3_t baseshotcolor;
2342         vec3_t surfcolor;
2343         vec3_t clipend;
2344         vec3_t clipstart;
2345         vec3_t clipdiff;
2346         vec3_t ispacing;
2347         vec3_t maxs;
2348         vec3_t mins;
2349         vec3_t size;
2350         vec3_t spacing;
2351         vec3_t lightcolor;
2352         vec3_t steppos;
2353         vec3_t stepdelta;
2354         vec3_t cullmins, cullmaxs;
2355         vec_t radius;
2356         vec_t s;
2357         vec_t lightintensity;
2358         vec_t photonscaling;
2359         vec_t photonresidual;
2360         float m[16];
2361         float texlerp[2][3];
2362         float splatcolor[32];
2363         float pixelweight[8];
2364         float w;
2365         int c[4];
2366         int pixelindex[8];
2367         int corner;
2368         int pixelsperband;
2369         int pixelband;
2370         int pixelbands;
2371         int numsteps;
2372         int step;
2373         int x, y, z;
2374         rtlight_t *rtlight;
2375         r_shadow_bouncegrid_settings_t settings;
2376         qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2377         qboolean allowdirectionalshading = false;
2378         switch(vid.renderpath)
2379         {
2380         case RENDERPATH_GL20:
2381                 allowdirectionalshading = true;
2382                 if (!vid.support.ext_texture_3d)
2383                         return;
2384                 break;
2385         case RENDERPATH_GLES2:
2386                 // for performance reasons, do not use directional shading on GLES devices
2387                 if (!vid.support.ext_texture_3d)
2388                         return;
2389                 break;
2390                 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2391         case RENDERPATH_GL11:
2392         case RENDERPATH_GL13:
2393         case RENDERPATH_GLES1:
2394         case RENDERPATH_SOFT:
2395         case RENDERPATH_D3D9:
2396         case RENDERPATH_D3D10:
2397         case RENDERPATH_D3D11:
2398                 return;
2399         }
2400
2401         r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2402
2403         // see if there are really any lights to render...
2404         if (enable && r_shadow_bouncegrid_static.integer)
2405         {
2406                 enable = false;
2407                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2408                 for (lightindex = 0;lightindex < range;lightindex++)
2409                 {
2410                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2411                         if (!light || !(light->flags & flag))
2412                                 continue;
2413                         rtlight = &light->rtlight;
2414                         // when static, we skip styled lights because they tend to change...
2415                         if (rtlight->style > 0)
2416                                 continue;
2417                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2418                         if (!VectorLength2(lightcolor))
2419                                 continue;
2420                         enable = true;
2421                         break;
2422                 }
2423         }
2424
2425         if (!enable)
2426         {
2427                 if (r_shadow_bouncegridtexture)
2428                 {
2429                         R_FreeTexture(r_shadow_bouncegridtexture);
2430                         r_shadow_bouncegridtexture = NULL;
2431                 }
2432                 if (r_shadow_bouncegridpixels)
2433                         Mem_Free(r_shadow_bouncegridpixels);
2434                 r_shadow_bouncegridpixels = NULL;
2435                 if (r_shadow_bouncegridhighpixels)
2436                         Mem_Free(r_shadow_bouncegridhighpixels);
2437                 r_shadow_bouncegridhighpixels = NULL;
2438                 r_shadow_bouncegridnumpixels = 0;
2439                 r_shadow_bouncegriddirectional = false;
2440                 return;
2441         }
2442
2443         // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2444         memset(&settings, 0, sizeof(settings));
2445         settings.staticmode                    = r_shadow_bouncegrid_static.integer != 0;
2446         settings.bounceanglediffuse            = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2447         settings.directionalshading            = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2448         settings.dlightparticlemultiplier      = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2449         settings.hitmodels                     = r_shadow_bouncegrid_hitmodels.integer != 0;
2450         settings.includedirectlighting         = r_shadow_bouncegrid_includedirectlighting.integer != 0 || r_shadow_bouncegrid.integer == 2;
2451         settings.lightradiusscale              = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_lightradiusscale.value : r_shadow_bouncegrid_lightradiusscale.value);
2452         settings.maxbounce                     = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_maxbounce.integer : r_shadow_bouncegrid_maxbounce.integer);
2453         settings.particlebounceintensity       = r_shadow_bouncegrid_particlebounceintensity.value;
2454         settings.particleintensity             = r_shadow_bouncegrid_particleintensity.value * 16384.0f * (settings.directionalshading ? 4.0f : 1.0f) / (r_shadow_bouncegrid_spacing.value * r_shadow_bouncegrid_spacing.value);
2455         settings.photons                       = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2456         settings.spacing[0]                    = r_shadow_bouncegrid_spacing.value;
2457         settings.spacing[1]                    = r_shadow_bouncegrid_spacing.value;
2458         settings.spacing[2]                    = r_shadow_bouncegrid_spacing.value;
2459         settings.stablerandom                  = r_shadow_bouncegrid_stablerandom.integer;
2460
2461         // bound the values for sanity
2462         settings.photons = bound(1, settings.photons, 1048576);
2463         settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2464         settings.maxbounce = bound(0, settings.maxbounce, 16);
2465         settings.spacing[0] = bound(1, settings.spacing[0], 512);
2466         settings.spacing[1] = bound(1, settings.spacing[1], 512);
2467         settings.spacing[2] = bound(1, settings.spacing[2], 512);
2468
2469         // get the spacing values
2470         spacing[0] = settings.spacing[0];
2471         spacing[1] = settings.spacing[1];
2472         spacing[2] = settings.spacing[2];
2473         ispacing[0] = 1.0f / spacing[0];
2474         ispacing[1] = 1.0f / spacing[1];
2475         ispacing[2] = 1.0f / spacing[2];
2476
2477         // calculate texture size enclosing entire world bounds at the spacing
2478         VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2479         VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2480         VectorSubtract(maxs, mins, size);
2481         // now we can calculate the resolution we want
2482         c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2483         c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2484         c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2485         // figure out the exact texture size (honoring power of 2 if required)
2486         c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2487         c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2488         c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2489         if (vid.support.arb_texture_non_power_of_two)
2490         {
2491                 resolution[0] = c[0];
2492                 resolution[1] = c[1];
2493                 resolution[2] = c[2];
2494         }
2495         else
2496         {
2497                 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2498                 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2499                 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2500         }
2501         size[0] = spacing[0] * resolution[0];
2502         size[1] = spacing[1] * resolution[1];
2503         size[2] = spacing[2] * resolution[2];
2504
2505         // if dynamic we may or may not want to use the world bounds
2506         // if the dynamic size is smaller than the world bounds, use it instead
2507         if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2508         {
2509                 // we know the resolution we want
2510                 c[0] = r_shadow_bouncegrid_x.integer;
2511                 c[1] = r_shadow_bouncegrid_y.integer;
2512                 c[2] = r_shadow_bouncegrid_z.integer;
2513                 // now we can calculate the texture size (power of 2 if required)
2514                 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2515                 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2516                 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2517                 if (vid.support.arb_texture_non_power_of_two)
2518                 {
2519                         resolution[0] = c[0];
2520                         resolution[1] = c[1];
2521                         resolution[2] = c[2];
2522                 }
2523                 else
2524                 {
2525                         for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2526                         for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2527                         for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2528                 }
2529                 size[0] = spacing[0] * resolution[0];
2530                 size[1] = spacing[1] * resolution[1];
2531                 size[2] = spacing[2] * resolution[2];
2532                 // center the rendering on the view
2533                 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2534                 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2535                 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2536         }
2537
2538         // recalculate the maxs in case the resolution was not satisfactory
2539         VectorAdd(mins, size, maxs);
2540
2541         // if all the settings seem identical to the previous update, return
2542         if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2543                 return;
2544
2545         // store the new settings
2546         r_shadow_bouncegridsettings = settings;
2547
2548         pixelbands = settings.directionalshading ? 8 : 1;
2549         pixelsperband = resolution[0]*resolution[1]*resolution[2];
2550         numpixels = pixelsperband*pixelbands;
2551
2552         // we're going to update the bouncegrid, update the matrix...
2553         memset(m, 0, sizeof(m));
2554         m[0] = 1.0f / size[0];
2555         m[3] = -mins[0] * m[0];
2556         m[5] = 1.0f / size[1];
2557         m[7] = -mins[1] * m[5];
2558         m[10] = 1.0f / size[2];
2559         m[11] = -mins[2] * m[10];
2560         m[15] = 1.0f;
2561         Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2562         // reallocate pixels for this update if needed...
2563         if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2564         {
2565                 if (r_shadow_bouncegridtexture)
2566                 {
2567                         R_FreeTexture(r_shadow_bouncegridtexture);
2568                         r_shadow_bouncegridtexture = NULL;
2569                 }
2570                 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2571                 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2572         }
2573         r_shadow_bouncegridnumpixels = numpixels;
2574         pixels = r_shadow_bouncegridpixels;
2575         highpixels = r_shadow_bouncegridhighpixels;
2576         x = pixelsperband*4;
2577         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2578         {
2579                 if (pixelband == 1)
2580                         memset(pixels + pixelband * x, 128, x);
2581                 else
2582                         memset(pixels + pixelband * x, 0, x);
2583         }
2584         memset(highpixels, 0, numpixels * sizeof(float[4]));
2585         // figure out what we want to interact with
2586         if (settings.hitmodels)
2587                 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2588         else
2589                 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2590         maxbounce = settings.maxbounce;
2591         // clear variables that produce warnings otherwise
2592         memset(splatcolor, 0, sizeof(splatcolor));
2593         // iterate world rtlights
2594         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2595         range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2596         range2 = range + range1;
2597         photoncount = 0;
2598         for (lightindex = 0;lightindex < range2;lightindex++)
2599         {
2600                 if (lightindex < range)
2601                 {
2602                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2603                         if (!light)
2604                                 continue;
2605                         rtlight = &light->rtlight;
2606                         VectorClear(rtlight->photoncolor);
2607                         rtlight->photons = 0;
2608                         if (!(light->flags & flag))
2609                                 continue;
2610                         if (settings.staticmode)
2611                         {
2612                                 // when static, we skip styled lights because they tend to change...
2613                                 if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2)
2614                                         continue;
2615                         }
2616                 }
2617                 else
2618                 {
2619                         rtlight = r_refdef.scene.lights[lightindex - range];
2620                         VectorClear(rtlight->photoncolor);
2621                         rtlight->photons = 0;
2622                 }
2623                 // draw only visible lights (major speedup)
2624                 radius = rtlight->radius * settings.lightradiusscale;
2625                 cullmins[0] = rtlight->shadoworigin[0] - radius;
2626                 cullmins[1] = rtlight->shadoworigin[1] - radius;
2627                 cullmins[2] = rtlight->shadoworigin[2] - radius;
2628                 cullmaxs[0] = rtlight->shadoworigin[0] + radius;
2629                 cullmaxs[1] = rtlight->shadoworigin[1] + radius;
2630                 cullmaxs[2] = rtlight->shadoworigin[2] + radius;
2631                 if (R_CullBox(cullmins, cullmaxs))
2632                         continue;
2633                 if (r_refdef.scene.worldmodel
2634                  && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs
2635                  && !r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, cullmins, cullmaxs))
2636                         continue;
2637                 w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2638                 if (w * VectorLength2(rtlight->color) == 0.0f)
2639                         continue;
2640                 w *= (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1);
2641                 VectorScale(rtlight->color, w, rtlight->photoncolor);
2642                 //if (!VectorLength2(rtlight->photoncolor))
2643                 //      continue;
2644                 // shoot particles from this light
2645                 // use a calculation for the number of particles that will not
2646                 // vary with lightstyle, otherwise we get randomized particle
2647                 // distribution, the seeded random is only consistent for a
2648                 // consistent number of particles on this light...
2649                 s = rtlight->radius;
2650                 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2651                 if (lightindex >= range)
2652                         lightintensity *= settings.dlightparticlemultiplier;
2653                 rtlight->photons = max(0.0f, lightintensity * s * s);
2654                 photoncount += rtlight->photons;
2655         }
2656         photonscaling = (float)settings.photons / max(1, photoncount);
2657         photonresidual = 0.0f;
2658         for (lightindex = 0;lightindex < range2;lightindex++)
2659         {
2660                 if (lightindex < range)
2661                 {
2662                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2663                         if (!light)
2664                                 continue;
2665                         rtlight = &light->rtlight;
2666                 }
2667                 else
2668                         rtlight = r_refdef.scene.lights[lightindex - range];
2669                 // skip a light with no photons
2670                 if (rtlight->photons == 0.0f)
2671                         continue;
2672                 // skip a light with no photon color)
2673                 if (VectorLength2(rtlight->photoncolor) == 0.0f)
2674                         continue;
2675                 photonresidual += rtlight->photons * photonscaling;
2676                 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2677                 if (!shootparticles)
2678                         continue;
2679                 photonresidual -= shootparticles;
2680                 radius = rtlight->radius * settings.lightradiusscale;
2681                 s = settings.particleintensity / shootparticles;
2682                 VectorScale(rtlight->photoncolor, s, baseshotcolor);
2683                 r_refdef.stats.bouncegrid_lights++;
2684                 r_refdef.stats.bouncegrid_particles += shootparticles;
2685                 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2686                 {
2687                         if (settings.stablerandom > 0)
2688                                 seed = lightindex * 11937 + shotparticles;
2689                         VectorCopy(baseshotcolor, shotcolor);
2690                         VectorCopy(rtlight->shadoworigin, clipstart);
2691                         if (settings.stablerandom < 0)
2692                                 VectorRandom(clipend);
2693                         else
2694                                 VectorCheeseRandom(clipend);
2695                         VectorMA(clipstart, radius, clipend, clipend);
2696                         for (bouncecount = 0;;bouncecount++)
2697                         {
2698                                 r_refdef.stats.bouncegrid_traces++;
2699                                 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2700                                 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2701                                 //if (settings.staticmode)
2702                                 //      Collision_ClipLineToWorld(&cliptrace, cl.worldmodel, clipstart, clipend, hitsupercontentsmask, true);
2703                                 //else
2704                                         cliptrace = CL_TraceLine(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), NULL, hitsupercontentsmask, true, false, NULL, true, true);
2705                                 if (bouncecount > 0 || settings.includedirectlighting)
2706                                 {
2707                                         // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2708                                         // accumulate average shotcolor
2709                                         w = VectorLength(shotcolor);
2710                                         splatcolor[ 0] = shotcolor[0];
2711                                         splatcolor[ 1] = shotcolor[1];
2712                                         splatcolor[ 2] = shotcolor[2];
2713                                         splatcolor[ 3] = 0.0f;
2714                                         if (pixelbands > 1)
2715                                         {
2716                                                 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2717                                                 VectorNormalize(clipdiff);
2718                                                 // store bentnormal in case the shader has a use for it
2719                                                 splatcolor[ 4] = clipdiff[0] * w;
2720                                                 splatcolor[ 5] = clipdiff[1] * w;
2721                                                 splatcolor[ 6] = clipdiff[2] * w;
2722                                                 splatcolor[ 7] = w;
2723                                                 // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z)
2724                                                 splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]);
2725                                                 splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]);
2726                                                 splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]);
2727                                                 splatcolor[11] = 0.0f;
2728                                                 splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]);
2729                                                 splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]);
2730                                                 splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]);
2731                                                 splatcolor[15] = 0.0f;
2732                                                 splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]);
2733                                                 splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]);
2734                                                 splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]);
2735                                                 splatcolor[19] = 0.0f;
2736                                                 splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]);
2737                                                 splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]);
2738                                                 splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]);
2739                                                 splatcolor[23] = 0.0f;
2740                                                 splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]);
2741                                                 splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]);
2742                                                 splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]);
2743                                                 splatcolor[27] = 0.0f;
2744                                                 splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]);
2745                                                 splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]);
2746                                                 splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]);
2747                                                 splatcolor[31] = 0.0f;
2748                                         }
2749                                         // calculate the number of steps we need to traverse this distance
2750                                         VectorSubtract(cliptrace.endpos, clipstart, stepdelta);
2751                                         numsteps = (int)(VectorLength(stepdelta) * ispacing[0]);
2752                                         numsteps = bound(1, numsteps, 1024);
2753                                         w = 1.0f / numsteps;
2754                                         VectorScale(stepdelta, w, stepdelta);
2755                                         VectorMA(clipstart, 0.5f, stepdelta, steppos);
2756                                         for (step = 0;step < numsteps;step++)
2757                                         {
2758                                                 r_refdef.stats.bouncegrid_splats++;
2759                                                 // figure out which texture pixel this is in
2760                                                 texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]) - 0.5f;
2761                                                 texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]) - 0.5f;
2762                                                 texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]) - 0.5f;
2763                                                 tex[0] = (int)floor(texlerp[1][0]);
2764                                                 tex[1] = (int)floor(texlerp[1][1]);
2765                                                 tex[2] = (int)floor(texlerp[1][2]);
2766                                                 if (tex[0] >= 1 && tex[1] >= 1 && tex[2] >= 1 && tex[0] < resolution[0] - 2 && tex[1] < resolution[1] - 2 && tex[2] < resolution[2] - 2)
2767                                                 {
2768                                                         // it is within bounds...  do the real work now
2769                                                         // calculate the lerp factors
2770                                                         texlerp[1][0] -= tex[0];
2771                                                         texlerp[1][1] -= tex[1];
2772                                                         texlerp[1][2] -= tex[2];
2773                                                         texlerp[0][0] = 1.0f - texlerp[1][0];
2774                                                         texlerp[0][1] = 1.0f - texlerp[1][1];
2775                                                         texlerp[0][2] = 1.0f - texlerp[1][2];
2776                                                         // calculate individual pixel indexes and weights
2777                                                         pixelindex[0] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2778                                                         pixelindex[1] = (((tex[2]  )*resolution[1]+tex[1]  )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2779                                                         pixelindex[2] = (((tex[2]  )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]  );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2780                                                         pixelindex[3] = (((tex[2]  )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[3] = (texlerp[1][0]*texlerp[1][1]*texlerp[0][2]);
2781                                                         pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1]  )*resolution[0]+tex[0]  );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2782                                                         pixelindex[5] = (((tex[2]+1)*resolution[1]+tex[1]  )*resolution[0]+tex[0]+1);pixelweight[5] = (texlerp[1][0]*texlerp[0][1]*texlerp[1][2]);
2783                                                         pixelindex[6] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0]  );pixelweight[6] = (texlerp[0][0]*texlerp[1][1]*texlerp[1][2]);
2784                                                         pixelindex[7] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[7] = (texlerp[1][0]*texlerp[1][1]*texlerp[1][2]);
2785                                                         // update the 8 pixels...
2786                                                         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2787                                                         {
2788                                                                 for (corner = 0;corner < 8;corner++)
2789                                                                 {
2790                                                                         // calculate address for pixel
2791                                                                         w = pixelweight[corner];
2792                                                                         pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2793                                                                         highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2794                                                                         // add to the high precision pixel color
2795                                                                         highpixel[0] += (splatcolor[pixelband*4+0]*w);
2796                                                                         highpixel[1] += (splatcolor[pixelband*4+1]*w);
2797                                                                         highpixel[2] += (splatcolor[pixelband*4+2]*w);
2798                                                                         highpixel[3] += (splatcolor[pixelband*4+3]*w);
2799                                                                         // flag the low precision pixel as needing to be updated
2800                                                                         pixel[3] = 255;
2801                                                                         // advance to next band of coefficients
2802                                                                         //pixel += pixelsperband*4;
2803                                                                         //highpixel += pixelsperband*4;
2804                                                                 }
2805                                                         }
2806                                                 }
2807                                                 VectorAdd(steppos, stepdelta, steppos);
2808                                         }
2809                                 }
2810                                 if (cliptrace.fraction >= 1.0f)
2811                                         break;
2812                                 r_refdef.stats.bouncegrid_hits++;
2813                                 if (bouncecount >= maxbounce)
2814                                         break;
2815                                 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2816                                 // also clamp the resulting color to never add energy, even if the user requests extreme values
2817                                 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2818                                         VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2819                                 else
2820                                         VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2821                                 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2822                                 surfcolor[0] = min(surfcolor[0], 1.0f);
2823                                 surfcolor[1] = min(surfcolor[1], 1.0f);
2824                                 surfcolor[2] = min(surfcolor[2], 1.0f);
2825                                 VectorMultiply(shotcolor, surfcolor, shotcolor);
2826                                 if (VectorLength2(baseshotcolor) == 0.0f)
2827                                         break;
2828                                 r_refdef.stats.bouncegrid_bounces++;
2829                                 if (settings.bounceanglediffuse)
2830                                 {
2831                                         // random direction, primarily along plane normal
2832                                         s = VectorDistance(cliptrace.endpos, clipend);
2833                                         if (settings.stablerandom < 0)
2834                                                 VectorRandom(clipend);
2835                                         else
2836                                                 VectorCheeseRandom(clipend);
2837                                         VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2838                                         VectorNormalize(clipend);
2839                                         VectorScale(clipend, s, clipend);
2840                                 }
2841                                 else
2842                                 {
2843                                         // reflect the remaining portion of the line across plane normal
2844                                         VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2845                                         VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2846                                 }
2847                                 // calculate the new line start and end
2848                                 VectorCopy(cliptrace.endpos, clipstart);
2849                                 VectorAdd(clipstart, clipend, clipend);
2850                         }
2851                 }
2852         }
2853         // generate pixels array from highpixels array
2854         // skip first and last columns, rows, and layers as these are blank
2855         // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2856         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2857         {
2858                 for (z = 1;z < resolution[2]-1;z++)
2859                 {
2860                         for (y = 1;y < resolution[1]-1;y++)
2861                         {
2862                                 for (x = 1, pixelindex[0] = ((pixelband*resolution[2]+z)*resolution[1]+y)*resolution[0]+x, pixel = pixels + 4*pixelindex[0], highpixel = highpixels + 4*pixelindex[0];x < resolution[0]-1;x++, pixel += 4, highpixel += 4)
2863                                 {
2864                                         // only convert pixels that were hit by photons
2865                                         if (pixel[3] == 255)
2866                                         {
2867                                                 // normalize the bentnormal...
2868                                                 if (pixelband == 1)
2869                                                 {
2870                                                         VectorNormalize(highpixel);
2871                                                         c[0] = (int)(highpixel[0]*128.0f+128.0f);
2872                                                         c[1] = (int)(highpixel[1]*128.0f+128.0f);
2873                                                         c[2] = (int)(highpixel[2]*128.0f+128.0f);
2874                                                         c[3] = (int)(highpixel[3]*128.0f+128.0f);
2875                                                 }
2876                                                 else
2877                                                 {
2878                                                         c[0] = (int)(highpixel[0]*256.0f);
2879                                                         c[1] = (int)(highpixel[1]*256.0f);
2880                                                         c[2] = (int)(highpixel[2]*256.0f);
2881                                                         c[3] = (int)(highpixel[3]*256.0f);
2882                                                 }
2883                                                 pixel[2] = (unsigned char)bound(0, c[0], 255);
2884                                                 pixel[1] = (unsigned char)bound(0, c[1], 255);
2885                                                 pixel[0] = (unsigned char)bound(0, c[2], 255);
2886                                                 pixel[3] = (unsigned char)bound(0, c[3], 255);
2887                                         }
2888                                 }
2889                         }
2890                 }
2891         }
2892         if (r_shadow_bouncegridtexture && r_shadow_bouncegridresolution[0] == resolution[0] && r_shadow_bouncegridresolution[1] == resolution[1] && r_shadow_bouncegridresolution[2] == resolution[2] && r_shadow_bouncegriddirectional == settings.directionalshading)
2893                 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands);
2894         else
2895         {
2896                 VectorCopy(resolution, r_shadow_bouncegridresolution);
2897                 r_shadow_bouncegriddirectional = settings.directionalshading;
2898                 if (r_shadow_bouncegridtexture)
2899                         R_FreeTexture(r_shadow_bouncegridtexture);
2900                 r_shadow_bouncegridtexture = R_LoadTexture3D(r_shadow_texturepool, "bouncegrid", resolution[0], resolution[1], resolution[2]*pixelbands, pixels, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, 0, NULL);
2901         }
2902         r_shadow_bouncegridtime = realtime;
2903 }
2904
2905 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2906 {
2907         R_Shadow_RenderMode_Reset();
2908         GL_BlendFunc(GL_ONE, GL_ONE);
2909         GL_DepthRange(0, 1);
2910         GL_DepthTest(r_showshadowvolumes.integer < 2);
2911         GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2912         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2913         GL_CullFace(GL_NONE);
2914         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2915 }
2916
2917 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2918 {
2919         R_Shadow_RenderMode_Reset();
2920         GL_BlendFunc(GL_ONE, GL_ONE);
2921         GL_DepthRange(0, 1);
2922         GL_DepthTest(r_showlighting.integer < 2);
2923         GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2924         if (!transparent)
2925                 GL_DepthFunc(GL_EQUAL);
2926         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2927         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2928 }
2929
2930 void R_Shadow_RenderMode_End(void)
2931 {
2932         R_Shadow_RenderMode_Reset();
2933         R_Shadow_RenderMode_ActiveLight(NULL);
2934         GL_DepthMask(true);
2935         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2936         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2937 }
2938
2939 int bboxedges[12][2] =
2940 {
2941         // top
2942         {0, 1}, // +X
2943         {0, 2}, // +Y
2944         {1, 3}, // Y, +X
2945         {2, 3}, // X, +Y
2946         // bottom
2947         {4, 5}, // +X
2948         {4, 6}, // +Y
2949         {5, 7}, // Y, +X
2950         {6, 7}, // X, +Y
2951         // verticals
2952         {0, 4}, // +Z
2953         {1, 5}, // X, +Z
2954         {2, 6}, // Y, +Z
2955         {3, 7}, // XY, +Z
2956 };
2957
2958 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2959 {
2960         if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass || r_trippy.integer)
2961         {
2962                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2963                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2964                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2965                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2966                 return false;
2967         }
2968         if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2969                 return true; // invisible
2970         if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2971         || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2972         || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2973         || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2974                 r_refdef.stats.lights_scissored++;
2975         return false;
2976 }
2977
2978 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
2979 {
2980         int i;
2981         const float *vertex3f;
2982         const float *normal3f;
2983         float *color4f;
2984         float dist, dot, distintensity, shadeintensity, v[3], n[3];
2985         switch (r_shadow_rendermode)
2986         {
2987         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
2988         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
2989                 if (VectorLength2(diffusecolor) > 0)
2990                 {
2991                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
2992                         {
2993                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2994                                 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2995                                 if ((dot = DotProduct(n, v)) < 0)
2996                                 {
2997                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2998                                         VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
2999                                 }
3000                                 else
3001                                         VectorCopy(ambientcolor, color4f);
3002                                 if (r_refdef.fogenabled)
3003                                 {
3004                                         float f;
3005                                         f = RSurf_FogVertex(vertex3f);
3006                                         VectorScale(color4f, f, color4f);
3007                                 }
3008                                 color4f[3] = 1;
3009                         }
3010                 }
3011                 else
3012                 {
3013                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3014                         {
3015                                 VectorCopy(ambientcolor, color4f);
3016                                 if (r_refdef.fogenabled)
3017                                 {
3018                                         float f;
3019                                         Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3020                                         f = RSurf_FogVertex(vertex3f);
3021                                         VectorScale(color4f + 4*i, f, color4f);
3022                                 }
3023                                 color4f[3] = 1;
3024                         }
3025                 }
3026                 break;
3027         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3028                 if (VectorLength2(diffusecolor) > 0)
3029                 {
3030                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3031                         {
3032                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3033                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3034                                 {
3035                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3036                                         if ((dot = DotProduct(n, v)) < 0)
3037                                         {
3038                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3039                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3040                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3041                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3042                                         }
3043                                         else
3044                                         {
3045                                                 color4f[0] = ambientcolor[0] * distintensity;
3046                                                 color4f[1] = ambientcolor[1] * distintensity;
3047                                                 color4f[2] = ambientcolor[2] * distintensity;
3048                                         }
3049                                         if (r_refdef.fogenabled)
3050                                         {
3051                                                 float f;
3052                                                 f = RSurf_FogVertex(vertex3f);
3053                                                 VectorScale(color4f, f, color4f);
3054                                         }
3055                                 }
3056                                 else
3057                                         VectorClear(color4f);
3058                                 color4f[3] = 1;
3059                         }
3060                 }
3061                 else
3062                 {
3063                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3064                         {
3065                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3066                                 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3067                                 {
3068                                         color4f[0] = ambientcolor[0] * distintensity;
3069                                         color4f[1] = ambientcolor[1] * distintensity;
3070                                         color4f[2] = ambientcolor[2] * distintensity;
3071                                         if (r_refdef.fogenabled)
3072                                         {
3073                                                 float f;
3074                                                 f = RSurf_FogVertex(vertex3f);
3075                                                 VectorScale(color4f, f, color4f);
3076                                         }
3077                                 }
3078                                 else
3079                                         VectorClear(color4f);
3080                                 color4f[3] = 1;
3081                         }
3082                 }
3083                 break;
3084         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3085                 if (VectorLength2(diffusecolor) > 0)
3086                 {
3087                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4)
3088                         {
3089                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3090                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3091                                 {
3092                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3093                                         Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3094                                         if ((dot = DotProduct(n, v)) < 0)
3095                                         {
3096                                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3097                                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3098                                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3099                                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3100                                         }
3101                                         else
3102                                         {
3103                                                 color4f[0] = ambientcolor[0] * distintensity;
3104                                                 color4f[1] = ambientcolor[1] * distintensity;
3105                                                 color4f[2] = ambientcolor[2] * distintensity;
3106                                         }
3107                                         if (r_refdef.fogenabled)
3108                                         {
3109                                                 float f;
3110                                                 f = RSurf_FogVertex(vertex3f);
3111                                                 VectorScale(color4f, f, color4f);
3112                                         }
3113                                 }
3114                                 else
3115                                         VectorClear(color4f);
3116                                 color4f[3] = 1;
3117                         }
3118                 }
3119                 else
3120                 {
3121                         for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3122                         {
3123                                 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3124                                 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3125                                 {
3126                                         distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3127                                         color4f[0] = ambientcolor[0] * distintensity;
3128                                         color4f[1] = ambientcolor[1] * distintensity;
3129                                         color4f[2] = ambientcolor[2] * distintensity;
3130                                         if (r_refdef.fogenabled)
3131                                         {
3132                                                 float f;
3133                                                 f = RSurf_FogVertex(vertex3f);
3134                                                 VectorScale(color4f, f, color4f);
3135                                         }
3136                                 }
3137                                 else
3138                                         VectorClear(color4f);
3139                                 color4f[3] = 1;
3140                         }
3141                 }
3142                 break;
3143         default:
3144                 break;
3145         }
3146 }
3147
3148 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3149 {
3150         // used to display how many times a surface is lit for level design purposes
3151         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3152         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3153         RSurf_DrawBatch();
3154 }
3155
3156 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3157 {
3158         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3159         R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL, false);
3160         RSurf_DrawBatch();
3161 }
3162
3163 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3164 {
3165         int renders;
3166         int i;
3167         int stop;
3168         int newfirstvertex;
3169         int newlastvertex;
3170         int newnumtriangles;
3171         int *newe;
3172         const int *e;
3173         float *c;
3174         int maxtriangles = 4096;
3175         static int newelements[4096*3];
3176         R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3177         for (renders = 0;renders < 4;renders++)
3178         {
3179                 stop = true;
3180                 newfirstvertex = 0;
3181                 newlastvertex = 0;
3182                 newnumtriangles = 0;
3183                 newe = newelements;
3184                 // due to low fillrate on the cards this vertex lighting path is
3185                 // designed for, we manually cull all triangles that do not
3186                 // contain a lit vertex
3187                 // this builds batches of triangles from multiple surfaces and
3188                 // renders them at once
3189                 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3190                 {
3191                         if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3192                         {
3193                                 if (newnumtriangles)
3194                                 {
3195                                         newfirstvertex = min(newfirstvertex, e[0]);
3196                                         newlastvertex  = max(newlastvertex, e[0]);
3197                                 }
3198                                 else
3199                                 {
3200                                         newfirstvertex = e[0];
3201                                         newlastvertex = e[0];
3202                                 }
3203                                 newfirstvertex = min(newfirstvertex, e[1]);
3204                                 newlastvertex  = max(newlastvertex, e[1]);
3205                                 newfirstvertex = min(newfirstvertex, e[2]);
3206                                 newlastvertex  = max(newlastvertex, e[2]);
3207                                 newe[0] = e[0];
3208                                 newe[1] = e[1];
3209                                 newe[2] = e[2];
3210                                 newnumtriangles++;
3211                                 newe += 3;
3212                                 if (newnumtriangles >= maxtriangles)
3213                                 {
3214                                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3215                                         newnumtriangles = 0;
3216                                         newe = newelements;
3217                                         stop = false;
3218                                 }
3219                         }
3220                 }
3221                 if (newnumtriangles >= 1)
3222                 {
3223                         R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3224                         stop = false;
3225                 }
3226                 // if we couldn't find any lit triangles, exit early
3227                 if (stop)
3228                         break;
3229                 // now reduce the intensity for the next overbright pass
3230                 // we have to clamp to 0 here incase the drivers have improper
3231                 // handling of negative colors
3232                 // (some old drivers even have improper handling of >1 color)
3233                 stop = true;
3234                 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3235                 {
3236                         if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3237                         {
3238                                 c[0] = max(0, c[0] - 1);
3239                                 c[1] = max(0, c[1] - 1);
3240                                 c[2] = max(0, c[2] - 1);
3241                                 stop = false;
3242                         }
3243                         else
3244                                 VectorClear(c);
3245                 }
3246                 // another check...
3247                 if (stop)
3248                         break;
3249         }
3250 }
3251
3252 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3253 {
3254         // OpenGL 1.1 path (anything)
3255         float ambientcolorbase[3], diffusecolorbase[3];
3256         float ambientcolorpants[3], diffusecolorpants[3];
3257         float ambientcolorshirt[3], diffusecolorshirt[3];
3258         const float *surfacecolor = rsurface.texture->dlightcolor;
3259         const float *surfacepants = rsurface.colormap_pantscolor;
3260         const float *surfaceshirt = rsurface.colormap_shirtcolor;
3261         rtexture_t *basetexture = rsurface.texture->basetexture;
3262         rtexture_t *pantstexture = rsurface.texture->pantstexture;
3263         rtexture_t *shirttexture = rsurface.texture->shirttexture;
3264         qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3265         qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3266         ambientscale *= 2 * r_refdef.view.colorscale;
3267         diffusescale *= 2 * r_refdef.view.colorscale;
3268         ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3269         diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3270         ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3271         diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3272         ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3273         diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3274         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3275         rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3276         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3277         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3278         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3279         R_Mesh_TexBind(0, basetexture);
3280         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3281         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3282         switch(r_shadow_rendermode)
3283         {
3284         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3285                 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3286                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3287                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3288                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3289                 break;
3290         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3291                 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3292                 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3293                 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3294                 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3295                 // fall through
3296         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3297                 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3298                 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3299                 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3300                 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3301                 break;
3302         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3303                 break;
3304         default:
3305                 break;
3306         }
3307         //R_Mesh_TexBind(0, basetexture);
3308         R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3309         if (dopants)
3310         {
3311                 R_Mesh_TexBind(0, pantstexture);
3312                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3313         }
3314         if (doshirt)
3315         {
3316                 R_Mesh_TexBind(0, shirttexture);
3317                 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3318         }
3319 }
3320
3321 extern cvar_t gl_lightmaps;
3322 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3323 {
3324         float ambientscale, diffusescale, specularscale;
3325         qboolean negated;
3326         float lightcolor[3];
3327         VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3328         ambientscale = rsurface.rtlight->ambientscale + rsurface.texture->rtlightambient;
3329         diffusescale = rsurface.rtlight->diffusescale * max(0, 1.0 - rsurface.texture->rtlightambient);
3330         specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3331         if (!r_shadow_usenormalmap.integer)
3332         {
3333                 ambientscale += 1.0f * diffusescale;
3334                 diffusescale = 0;
3335                 specularscale = 0;
3336         }
3337         if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3338                 return;
3339         negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3340         if(negated)
3341         {
3342                 VectorNegate(lightcolor, lightcolor);
3343                 GL_BlendEquationSubtract(true);
3344         }
3345         RSurf_SetupDepthAndCulling();
3346         switch (r_shadow_rendermode)
3347         {
3348         case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3349                 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3350                 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3351                 break;
3352         case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3353                 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3354                 break;
3355         case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3356         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3357         case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3358         case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3359                 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3360                 break;
3361         default:
3362                 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3363                 break;
3364         }
3365         if(negated)
3366                 GL_BlendEquationSubtract(false);
3367 }
3368
3369 void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
3370 {
3371         matrix4x4_t tempmatrix = *matrix;
3372         Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3373
3374         // if this light has been compiled before, free the associated data
3375         R_RTLight_Uncompile(rtlight);
3376
3377         // clear it completely to avoid any lingering data
3378         memset(rtlight, 0, sizeof(*rtlight));
3379
3380         // copy the properties
3381         rtlight->matrix_lighttoworld = tempmatrix;
3382         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3383         Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3384         rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3385         VectorCopy(color, rtlight->color);
3386         rtlight->cubemapname[0] = 0;
3387         if (cubemapname && cubemapname[0])
3388                 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3389         rtlight->shadow = shadow;
3390         rtlight->corona = corona;
3391         rtlight->style = style;
3392         rtlight->isstatic = isstatic;
3393         rtlight->coronasizescale = coronasizescale;
3394         rtlight->ambientscale = ambientscale;
3395         rtlight->diffusescale = diffusescale;
3396         rtlight->specularscale = specularscale;
3397         rtlight->flags = flags;
3398
3399         // compute derived data
3400         //rtlight->cullradius = rtlight->radius;
3401         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3402         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3403         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3404         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3405         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3406         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3407         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3408 }
3409
3410 // compiles rtlight geometry
3411 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3412 void R_RTLight_Compile(rtlight_t *rtlight)
3413 {
3414         int i;
3415         int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3416         int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3417         entity_render_t *ent = r_refdef.scene.worldentity;
3418         dp_model_t *model = r_refdef.scene.worldmodel;
3419         unsigned char *data;
3420         shadowmesh_t *mesh;
3421
3422         // compile the light
3423         rtlight->compiled = true;
3424         rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3425         rtlight->static_numleafs = 0;
3426         rtlight->static_numleafpvsbytes = 0;
3427         rtlight->static_leaflist = NULL;
3428         rtlight->static_leafpvs = NULL;
3429         rtlight->static_numsurfaces = 0;
3430         rtlight->static_surfacelist = NULL;
3431         rtlight->static_shadowmap_receivers = 0x3F;
3432         rtlight->static_shadowmap_casters = 0x3F;
3433         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3434         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3435         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3436         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3437         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3438         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3439
3440         if (model && model->GetLightInfo)
3441         {
3442                 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3443                 r_shadow_compilingrtlight = rtlight;
3444                 R_FrameData_SetMark();
3445                 model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, 0, NULL);
3446                 R_FrameData_ReturnToMark();
3447                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3448                 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3449                 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3450                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3451                 rtlight->static_numsurfaces = numsurfaces;
3452                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3453                 rtlight->static_numleafs = numleafs;
3454                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3455                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3456                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3457                 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3458                 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3459                 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3460                 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3461                 if (rtlight->static_numsurfaces)
3462                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3463                 if (rtlight->static_numleafs)
3464                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3465                 if (rtlight->static_numleafpvsbytes)
3466                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3467                 if (rtlight->static_numshadowtrispvsbytes)
3468                         memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3469                 if (rtlight->static_numlighttrispvsbytes)
3470                         memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3471                 R_FrameData_SetMark();
3472                 switch (rtlight->shadowmode)
3473                 {
3474                 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3475                         if (model->CompileShadowMap && rtlight->shadow)
3476                                 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3477                         break;
3478                 default:
3479                         if (model->CompileShadowVolume && rtlight->shadow)
3480                                 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3481                         break;
3482                 }
3483                 R_FrameData_ReturnToMark();
3484                 // now we're done compiling the rtlight
3485                 r_shadow_compilingrtlight = NULL;
3486         }
3487
3488
3489         // use smallest available cullradius - box radius or light radius
3490         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3491         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3492
3493         shadowzpasstris = 0;
3494         if (rtlight->static_meshchain_shadow_zpass)
3495                 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3496                         shadowzpasstris += mesh->numtriangles;
3497
3498         shadowzfailtris = 0;
3499         if (rtlight->static_meshchain_shadow_zfail)
3500                 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3501                         shadowzfailtris += mesh->numtriangles;
3502
3503         lighttris = 0;
3504         if (rtlight->static_numlighttrispvsbytes)
3505                 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3506                         if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3507                                 lighttris++;
3508
3509         shadowtris = 0;
3510         if (rtlight->static_numlighttrispvsbytes)
3511                 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3512                         if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3513                                 shadowtris++;
3514
3515         if (developer_extra.integer)
3516                 Con_DPrintf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris);
3517 }
3518
3519 void R_RTLight_Uncompile(rtlight_t *rtlight)
3520 {
3521         if (rtlight->compiled)
3522         {
3523                 if (rtlight->static_meshchain_shadow_zpass)
3524                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3525                 rtlight->static_meshchain_shadow_zpass = NULL;
3526                 if (rtlight->static_meshchain_shadow_zfail)
3527                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3528                 rtlight->static_meshchain_shadow_zfail = NULL;
3529                 if (rtlight->static_meshchain_shadow_shadowmap)
3530                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3531                 rtlight->static_meshchain_shadow_shadowmap = NULL;
3532                 // these allocations are grouped
3533                 if (rtlight->static_surfacelist)
3534                         Mem_Free(rtlight->static_surfacelist);
3535                 rtlight->static_numleafs = 0;
3536                 rtlight->static_numleafpvsbytes = 0;
3537                 rtlight->static_leaflist = NULL;
3538                 rtlight->static_leafpvs = NULL;
3539                 rtlight->static_numsurfaces = 0;
3540                 rtlight->static_surfacelist = NULL;
3541                 rtlight->static_numshadowtrispvsbytes = 0;
3542                 rtlight->static_shadowtrispvs = NULL;
3543                 rtlight->static_numlighttrispvsbytes = 0;
3544                 rtlight->static_lighttrispvs = NULL;
3545                 rtlight->compiled = false;
3546         }
3547 }
3548
3549 void R_Shadow_UncompileWorldLights(void)
3550 {
3551         size_t lightindex;
3552         dlight_t *light;
3553         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3554         for (lightindex = 0;lightindex < range;lightindex++)
3555         {
3556                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3557                 if (!light)
3558                         continue;
3559                 R_RTLight_Uncompile(&light->rtlight);
3560         }
3561 }
3562
3563 void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3564 {
3565         int i, j;
3566         mplane_t plane;
3567         // reset the count of frustum planes
3568         // see rtlight->cached_frustumplanes definition for how much this array
3569         // can hold
3570         rtlight->cached_numfrustumplanes = 0;
3571
3572         if (r_trippy.integer)
3573                 return;
3574
3575         // haven't implemented a culling path for ortho rendering
3576         if (!r_refdef.view.useperspective)
3577         {
3578                 // check if the light is on screen and copy the 4 planes if it is
3579                 for (i = 0;i < 4;i++)
3580                         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3581                                 break;
3582                 if (i == 4)
3583                         for (i = 0;i < 4;i++)
3584                                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3585                 return;
3586         }
3587
3588 #if 1
3589         // generate a deformed frustum that includes the light origin, this is
3590         // used to cull shadow casting surfaces that can not possibly cast a
3591         // shadow onto the visible light-receiving surfaces, which can be a
3592         // performance gain
3593         //
3594         // if the light origin is onscreen the result will be 4 planes exactly
3595         // if the light origin is offscreen on only one axis the result will
3596         // be exactly 5 planes (split-side case)
3597         // if the light origin is offscreen on two axes the result will be
3598         // exactly 4 planes (stretched corner case)
3599         for (i = 0;i < 4;i++)
3600         {
3601                 // quickly reject standard frustum planes that put the light
3602                 // origin outside the frustum
3603                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3604                         continue;
3605                 // copy the plane
3606                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3607         }
3608         // if all the standard frustum planes were accepted, the light is onscreen
3609         // otherwise we need to generate some more planes below...
3610         if (rtlight->cached_numfrustumplanes < 4)
3611         {
3612                 // at least one of the stock frustum planes failed, so we need to
3613                 // create one or two custom planes to enclose the light origin
3614                 for (i = 0;i < 4;i++)
3615                 {
3616                         // create a plane using the view origin and light origin, and a
3617                         // single point from the frustum corner set
3618                         TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3619                         VectorNormalize(plane.normal);
3620                         plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3621                         // see if this plane is backwards and flip it if so
3622                         for (j = 0;j < 4;j++)
3623                                 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3624                                         break;
3625                         if (j < 4)
3626                         {
3627                                 VectorNegate(plane.normal, plane.normal);
3628                                 plane.dist *= -1;
3629                                 // flipped plane, test again to see if it is now valid
3630                                 for (j = 0;j < 4;j++)
3631                                         if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3632                                                 break;
3633                                 // if the plane is still not valid, then it is dividing the
3634                                 // frustum and has to be rejected
3635                                 if (j < 4)
3636                                         continue;
3637                         }
3638                         // we have created a valid plane, compute extra info
3639                         PlaneClassify(&plane);
3640                         // copy the plane
3641                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3642 #if 1
3643                         // if we've found 5 frustum planes then we have constructed a
3644                         // proper split-side case and do not need to keep searching for
3645                         // planes to enclose the light origin
3646                         if (rtlight->cached_numfrustumplanes == 5)
3647                                 break;
3648 #endif
3649                 }
3650         }
3651 #endif
3652
3653 #if 0
3654         for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3655         {
3656                 plane = rtlight->cached_frustumplanes[i];
3657                 Con_Printf("light %p plane #%i %f %f %f : %f (%f %f %f %f %f)\n", rtlight, i, plane.normal[0], plane.normal[1], plane.normal[2], plane.dist, PlaneDiff(r_refdef.view.frustumcorner[0], &plane), PlaneDiff(r_refdef.view.frustumcorner[1], &plane), PlaneDiff(r_refdef.view.frustumcorner[2], &plane), PlaneDiff(r_refdef.view.frustumcorner[3], &plane), PlaneDiff(rtlight->shadoworigin, &plane));
3658         }
3659 #endif
3660
3661 #if 0
3662         // now add the light-space box planes if the light box is rotated, as any
3663         // caster outside the oriented light box is irrelevant (even if it passed
3664         // the worldspace light box, which is axial)
3665         if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3666         {
3667                 for (i = 0;i < 6;i++)
3668                 {
3669                         vec3_t v;
3670                         VectorClear(v);
3671                         v[i >> 1] = (i & 1) ? -1 : 1;
3672                         Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3673                         VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3674                         plane.dist = VectorNormalizeLength(plane.normal);
3675                         plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3676                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3677                 }
3678         }
3679 #endif
3680
3681 #if 0
3682         // add the world-space reduced box planes
3683         for (i = 0;i < 6;i++)
3684         {
3685                 VectorClear(plane.normal);
3686                 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3687                 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3688                 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3689         }
3690 #endif
3691
3692 #if 0
3693         {
3694         int j, oldnum;
3695         vec3_t points[8];
3696         vec_t bestdist;
3697         // reduce all plane distances to tightly fit the rtlight cull box, which
3698         // is in worldspace
3699         VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3700         VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3701         VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3702         VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3703         VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3704         VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3705         VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3706         VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3707         oldnum = rtlight->cached_numfrustumplanes;
3708         rtlight->cached_numfrustumplanes = 0;
3709         for (j = 0;j < oldnum;j++)
3710         {
3711                 // find the nearest point on the box to this plane
3712                 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3713                 for (i = 1;i < 8;i++)
3714                 {
3715                         dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3716                         if (bestdist > dist)
3717                                 bestdist = dist;
3718                 }
3719                 Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rtlight->cached_frustumplanes[j].normal[0], rtlight->cached_frustumplanes[j].normal[1], rtlight->cached_frustumplanes[j].normal[2], rtlight->cached_frustumplanes[j].dist, bestdist);
3720                 // if the nearest point is near or behind the plane, we want this
3721                 // plane, otherwise the plane is useless as it won't cull anything
3722                 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3723                 {
3724                         PlaneClassify(&rtlight->cached_frustumplanes[j]);
3725                         rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3726                 }
3727         }
3728         }
3729 #endif
3730 }
3731
3732 void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3733 {
3734         shadowmesh_t *mesh;
3735
3736         RSurf_ActiveWorldEntity();
3737
3738         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3739         {
3740                 CHECKGLERROR
3741                 GL_CullFace(GL_NONE);
3742                 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3743                 for (;mesh;mesh = mesh->next)
3744                 {
3745                         if (!mesh->sidetotals[r_shadow_shadowmapside])
3746                                 continue;
3747                         r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside];
3748                         if (mesh->vertex3fbuffer)
3749                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3750                         else
3751                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3752                         R_Mesh_Draw(0, mesh->numverts, mesh->sideoffsets[r_shadow_shadowmapside], mesh->sidetotals[r_shadow_shadowmapside], mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3753                 }
3754                 CHECKGLERROR
3755         }
3756         else if (r_refdef.scene.worldentity->model)
3757                 r_refdef.scene.worldmodel->DrawShadowMap(r_shadow_shadowmapside, r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, surfacesides, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3758
3759         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3760 }
3761
3762 void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3763 {
3764         qboolean zpass = false;
3765         shadowmesh_t *mesh;
3766         int t, tend;
3767         int surfacelistindex;
3768         msurface_t *surface;
3769
3770         // if triangle neighbors are disabled, shadowvolumes are disabled
3771         if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3772                 return;
3773
3774         RSurf_ActiveWorldEntity();
3775
3776         if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3777         {
3778                 CHECKGLERROR
3779                 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3780                 {
3781                         zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3782                         R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3783                 }
3784                 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3785                 for (;mesh;mesh = mesh->next)
3786                 {
3787                         r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3788                         if (mesh->vertex3fbuffer)
3789                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3790                         else
3791                                 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3792                         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3793                         {
3794                                 // increment stencil if frontface is infront of depthbuffer
3795                                 GL_CullFace(r_refdef.view.cullface_back);
3796                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3797                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3798                                 // decrement stencil if backface is infront of depthbuffer
3799                                 GL_CullFace(r_refdef.view.cullface_front);
3800                                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3801                         }
3802                         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3803                         {
3804                                 // decrement stencil if backface is behind depthbuffer
3805                                 GL_CullFace(r_refdef.view.cullface_front);
3806                                 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3807                                 R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3808                                 // increment stencil if frontface is behind depthbuffer
3809                                 GL_CullFace(r_refdef.view.cullface_back);
3810                                 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3811                         }
3812                         R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
3813                 }
3814                 CHECKGLERROR
3815         }
3816         else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3817         {
3818                 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3819                 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3820                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3821                 {
3822                         surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3823                         for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3824                                 if (CHECKPVSBIT(trispvs, t))
3825                                         shadowmarklist[numshadowmark++] = t;
3826                 }
3827                 R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3828         }
3829         else if (numsurfaces)
3830         {
3831                 r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs);
3832         }
3833
3834         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3835 }
3836
3837 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3838 {
3839         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3840         vec_t relativeshadowradius;
3841         RSurf_ActiveModelEntity(ent, false, false, false);
3842         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3843         // we need to re-init the shader for each entity because the matrix changed
3844         relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3845         relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3846         relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3847         relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3848         relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3849         relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3850         relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3851         switch (r_shadow_rendermode)
3852         {
3853         case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3854                 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3855                 break;
3856         default:
3857                 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3858                 break;
3859         }
3860         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3861 }
3862
3863 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3864 {
3865         // set up properties for rendering light onto this entity
3866         RSurf_ActiveModelEntity(ent, true, true, false);
3867         Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3868         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3869         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3870         Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3871 }
3872
3873 void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3874 {
3875         if (!r_refdef.scene.worldmodel->DrawLight)
3876                 return;
3877
3878         // set up properties for rendering light onto this entity
3879         RSurf_ActiveWorldEntity();
3880         rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3881         Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3882         Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3883         VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3884
3885         r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3886
3887         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3888 }
3889
3890 void R_Shadow_DrawEntityLight(entity_render_t *ent)
3891 {
3892         dp_model_t *model = ent->model;
3893         if (!model->DrawLight)
3894                 return;
3895
3896         R_Shadow_SetupEntityLight(ent);
3897
3898         model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3899
3900         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3901 }
3902
3903 void R_Shadow_PrepareLight(rtlight_t *rtlight)
3904 {
3905         int i;
3906         float f;
3907         int numleafs, numsurfaces;
3908         int *leaflist, *surfacelist;
3909         unsigned char *leafpvs;
3910         unsigned char *shadowtrispvs;
3911         unsigned char *lighttrispvs;
3912         //unsigned char *surfacesides;
3913         int numlightentities;
3914         int numlightentities_noselfshadow;
3915         int numshadowentities;
3916         int numshadowentities_noselfshadow;
3917         static entity_render_t *lightentities[MAX_EDICTS];
3918         static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3919         static entity_render_t *shadowentities[MAX_EDICTS];
3920         static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3921         qboolean nolight;
3922
3923         rtlight->draw = false;
3924
3925         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3926         // skip lights that are basically invisible (color 0 0 0)
3927         nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3928
3929         // loading is done before visibility checks because loading should happen
3930         // all at once at the start of a level, not when it stalls gameplay.
3931         // (especially important to benchmarks)
3932         // compile light
3933         if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3934         {
3935                 if (rtlight->compiled)
3936                         R_RTLight_Uncompile(rtlight);
3937                 R_RTLight_Compile(rtlight);
3938         }
3939
3940         // load cubemap
3941         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
3942
3943         // look up the light style value at this time
3944         f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3945         VectorScale(rtlight->color, f, rtlight->currentcolor);
3946         /*
3947         if (rtlight->selected)
3948         {
3949                 f = 2 + sin(realtime * M_PI * 4.0);
3950                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
3951         }
3952         */
3953
3954         // if lightstyle is currently off, don't draw the light
3955         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
3956                 return;
3957
3958         // skip processing on corona-only lights
3959         if (nolight)
3960                 return;
3961
3962         // if the light box is offscreen, skip it
3963         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
3964                 return;
3965
3966         VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
3967         VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
3968
3969         R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
3970
3971         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
3972         {
3973                 // compiled light, world available and can receive realtime lighting
3974                 // retrieve leaf information
3975                 numleafs = rtlight->static_numleafs;
3976                 leaflist = rtlight->static_leaflist;
3977                 leafpvs = rtlight->static_leafpvs;
3978                 numsurfaces = rtlight->static_numsurfaces;
3979                 surfacelist = rtlight->static_surfacelist;
3980                 //surfacesides = NULL;
3981                 shadowtrispvs = rtlight->static_shadowtrispvs;
3982                 lighttrispvs = rtlight->static_lighttrispvs;
3983         }
3984         else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
3985         {
3986                 // dynamic light, world available and can receive realtime lighting
3987                 // calculate lit surfaces and leafs
3988                 r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rtlight->cached_cullmins, rtlight->cached_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes);
3989                 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
3990                 leaflist = r_shadow_buffer_leaflist;
3991                 leafpvs = r_shadow_buffer_leafpvs;
3992                 surfacelist = r_shadow_buffer_surfacelist;
3993                 //surfacesides = r_shadow_buffer_surfacesides;
3994                 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
3995                 lighttrispvs = r_shadow_buffer_lighttrispvs;
3996                 // if the reduced leaf bounds are offscreen, skip it
3997                 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
3998                         return;
3999         }
4000         else
4001         {
4002                 // no world
4003                 numleafs = 0;
4004                 leaflist = NULL;
4005                 leafpvs = NULL;
4006                 numsurfaces = 0;
4007                 surfacelist = NULL;
4008                 //surfacesides = NULL;
4009                 shadowtrispvs = NULL;
4010                 lighttrispvs = NULL;
4011         }
4012         // check if light is illuminating any visible leafs
4013         if (numleafs)
4014         {
4015                 for (i = 0;i < numleafs;i++)
4016                         if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4017                                 break;
4018                 if (i == numleafs)
4019                         return;
4020         }
4021
4022         // make a list of lit entities and shadow casting entities
4023         numlightentities = 0;
4024         numlightentities_noselfshadow = 0;
4025         numshadowentities = 0;
4026         numshadowentities_noselfshadow = 0;
4027
4028         // add dynamic entities that are lit by the light
4029         for (i = 0;i < r_refdef.scene.numentities;i++)
4030         {
4031                 dp_model_t *model;
4032                 entity_render_t *ent = r_refdef.scene.entities[i];
4033                 vec3_t org;
4034                 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4035                         continue;
4036                 // skip the object entirely if it is not within the valid
4037                 // shadow-casting region (which includes the lit region)
4038                 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4039                         continue;
4040                 if (!(model = ent->model))
4041                         continue;
4042                 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4043                 {
4044                         // this entity wants to receive light, is visible, and is
4045                         // inside the light box
4046                         // TODO: check if the surfaces in the model can receive light
4047                         // so now check if it's in a leaf seen by the light
4048                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4049                                 continue;
4050                         if (ent->flags & RENDER_NOSELFSHADOW)
4051                                 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4052                         else
4053                                 lightentities[numlightentities++] = ent;
4054                         // since it is lit, it probably also casts a shadow...
4055                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4056                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4057                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4058                         {
4059                                 // note: exterior models without the RENDER_NOSELFSHADOW
4060                                 // flag still create a RENDER_NOSELFSHADOW shadow but
4061                                 // are lit normally, this means that they are
4062                                 // self-shadowing but do not shadow other
4063                                 // RENDER_NOSELFSHADOW entities such as the gun
4064                                 // (very weird, but keeps the player shadow off the gun)
4065                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4066                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4067                                 else
4068                                         shadowentities[numshadowentities++] = ent;
4069                         }
4070                 }
4071                 else if (ent->flags & RENDER_SHADOW)
4072                 {
4073                         // this entity is not receiving light, but may still need to
4074                         // cast a shadow...
4075                         // TODO: check if the surfaces in the model can cast shadow
4076                         // now check if it is in a leaf seen by the light
4077                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs))
4078                                 continue;
4079                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4080                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4081                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4082                         {
4083                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4084                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4085                                 else
4086                                         shadowentities[numshadowentities++] = ent;
4087                         }
4088                 }
4089         }
4090
4091         // return if there's nothing at all to light
4092         if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4093                 return;
4094
4095         // count this light in the r_speeds
4096         r_refdef.stats.lights++;
4097
4098         // flag it as worth drawing later
4099         rtlight->draw = true;
4100
4101         // cache all the animated entities that cast a shadow but are not visible
4102         for (i = 0;i < numshadowentities;i++)
4103                 if (!shadowentities[i]->animcache_vertex3f)
4104                         R_AnimCache_GetEntity(shadowentities[i], false, false);
4105         for (i = 0;i < numshadowentities_noselfshadow;i++)
4106                 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4107                         R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4108
4109         // allocate some temporary memory for rendering this light later in the frame
4110         // reusable buffers need to be copied, static data can be used as-is
4111         rtlight->cached_numlightentities               = numlightentities;
4112         rtlight->cached_numlightentities_noselfshadow  = numlightentities_noselfshadow;
4113         rtlight->cached_numshadowentities              = numshadowentities;
4114         rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4115         rtlight->cached_numsurfaces                    = numsurfaces;
4116         rtlight->cached_lightentities                  = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4117         rtlight->cached_lightentities_noselfshadow     = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4118         rtlight->cached_shadowentities                 = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4119         rtlight->cached_shadowentities_noselfshadow    = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4120         if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4121         {
4122                 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4123                 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4124                 rtlight->cached_shadowtrispvs                  =   (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4125                 rtlight->cached_lighttrispvs                   =   (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4126                 rtlight->cached_surfacelist                    =              (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4127         }
4128         else
4129         {
4130                 // compiled light data
4131                 rtlight->cached_shadowtrispvs = shadowtrispvs;
4132                 rtlight->cached_lighttrispvs = lighttrispvs;
4133                 rtlight->cached_surfacelist = surfacelist;
4134         }
4135 }
4136
4137 void R_Shadow_DrawLight(rtlight_t *rtlight)
4138 {
4139         int i;
4140         int numsurfaces;
4141         unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4142         int numlightentities;
4143         int numlightentities_noselfshadow;
4144         int numshadowentities;
4145         int numshadowentities_noselfshadow;
4146         entity_render_t **lightentities;
4147         entity_render_t **lightentities_noselfshadow;
4148         entity_render_t **shadowentities;
4149         entity_render_t **shadowentities_noselfshadow;
4150         int *surfacelist;
4151         static unsigned char entitysides[MAX_EDICTS];
4152         static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4153         vec3_t nearestpoint;
4154         vec_t distance;
4155         qboolean castshadows;
4156         int lodlinear;
4157
4158         // check if we cached this light this frame (meaning it is worth drawing)
4159         if (!rtlight->draw)
4160                 return;
4161
4162         numlightentities = rtlight->cached_numlightentities;
4163         numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4164         numshadowentities = rtlight->cached_numshadowentities;
4165         numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4166         numsurfaces = rtlight->cached_numsurfaces;
4167         lightentities = rtlight->cached_lightentities;
4168         lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4169         shadowentities = rtlight->cached_shadowentities;
4170         shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4171         shadowtrispvs = rtlight->cached_shadowtrispvs;
4172         lighttrispvs = rtlight->cached_lighttrispvs;
4173         surfacelist = rtlight->cached_surfacelist;
4174
4175         // set up a scissor rectangle for this light
4176         if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4177                 return;
4178
4179         // don't let sound skip if going slow
4180         if (r_refdef.scene.extraupdate)
4181                 S_ExtraUpdate ();
4182
4183         // make this the active rtlight for rendering purposes
4184         R_Shadow_RenderMode_ActiveLight(rtlight);
4185
4186         if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4187         {
4188                 // optionally draw visible shape of the shadow volumes
4189                 // for performance analysis by level designers
4190                 R_Shadow_RenderMode_VisibleShadowVolumes();
4191                 if (numsurfaces)
4192                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4193                 for (i = 0;i < numshadowentities;i++)
4194                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4195                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4196                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4197                 R_Shadow_RenderMode_VisibleLighting(false, false);
4198         }
4199
4200         if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4201         {
4202                 // optionally draw the illuminated areas
4203                 // for performance analysis by level designers
4204                 R_Shadow_RenderMode_VisibleLighting(false, false);
4205                 if (numsurfaces)
4206                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4207                 for (i = 0;i < numlightentities;i++)
4208                         R_Shadow_DrawEntityLight(lightentities[i]);
4209                 for (i = 0;i < numlightentities_noselfshadow;i++)
4210                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4211         }
4212
4213         castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4214
4215         nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4216         nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4217         nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4218         distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4219
4220         lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4221         //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4222         lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4223
4224         if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4225         {
4226                 float borderbias;
4227                 int side;
4228                 int size;
4229                 int castermask = 0;
4230                 int receivermask = 0;
4231                 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4232                 Matrix4x4_Abs(&radiustolight);
4233
4234                 r_shadow_shadowmaplod = 0;
4235                 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4236                         if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4237                                 r_shadow_shadowmaplod = i;
4238
4239                 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4240                         
4241                 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4242
4243                 surfacesides = NULL;
4244                 if (numsurfaces)
4245                 {
4246                         if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4247                         {
4248                                 castermask = rtlight->static_shadowmap_casters;
4249                                 receivermask = rtlight->static_shadowmap_receivers;
4250                         }
4251                         else
4252                         {
4253                                 surfacesides = r_shadow_buffer_surfacesides;
4254                                 for(i = 0;i < numsurfaces;i++)
4255                                 {
4256                                         msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4257                                         surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);           
4258                                         castermask |= surfacesides[i];
4259                                         receivermask |= surfacesides[i];
4260                                 }
4261                         }
4262                 }
4263                 if (receivermask < 0x3F) 
4264                 {
4265                         for (i = 0;i < numlightentities;i++)
4266                                 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4267                         if (receivermask < 0x3F)
4268                                 for(i = 0; i < numlightentities_noselfshadow;i++)
4269                                         receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4270                 }
4271
4272                 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4273
4274                 if (receivermask)
4275                 {
4276                         for (i = 0;i < numshadowentities;i++)
4277                                 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4278                         for (i = 0;i < numshadowentities_noselfshadow;i++)
4279                                 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); 
4280                 }
4281
4282                 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4283
4284                 // render shadow casters into 6 sided depth texture
4285                 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4286                 {
4287                         R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4288                         if (! (castermask & (1 << side))) continue;
4289                         if (numsurfaces)
4290                                 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4291                         for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4292                                 R_Shadow_DrawEntityShadow(shadowentities[i]);
4293                 }
4294
4295                 if (numlightentities_noselfshadow)
4296                 {
4297                         // render lighting using the depth texture as shadowmap
4298                         // draw lighting in the unmasked areas
4299                         R_Shadow_RenderMode_Lighting(false, false, true);
4300                         for (i = 0;i < numlightentities_noselfshadow;i++)
4301                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4302                 }
4303
4304                 // render shadow casters into 6 sided depth texture
4305                 if (numshadowentities_noselfshadow)
4306                 {
4307                         for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4308                         {
4309                                 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4310                                 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4311                                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4312                         }
4313                 }
4314
4315                 // render lighting using the depth texture as shadowmap
4316                 // draw lighting in the unmasked areas
4317                 R_Shadow_RenderMode_Lighting(false, false, true);
4318                 // draw lighting in the unmasked areas
4319                 if (numsurfaces)
4320                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4321                 for (i = 0;i < numlightentities;i++)
4322                         R_Shadow_DrawEntityLight(lightentities[i]);
4323         }
4324         else if (castshadows && vid.stencil)
4325         {
4326                 // draw stencil shadow volumes to mask off pixels that are in shadow
4327                 // so that they won't receive lighting
4328                 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4329                 R_Shadow_ClearStencil();
4330
4331                 if (numsurfaces)
4332                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4333                 for (i = 0;i < numshadowentities;i++)
4334                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4335
4336                 // draw lighting in the unmasked areas
4337                 R_Shadow_RenderMode_Lighting(true, false, false);
4338                 for (i = 0;i < numlightentities_noselfshadow;i++)
4339                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4340
4341                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4342                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4343
4344                 // draw lighting in the unmasked areas
4345                 R_Shadow_RenderMode_Lighting(true, false, false);
4346                 if (numsurfaces)
4347                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4348                 for (i = 0;i < numlightentities;i++)
4349                         R_Shadow_DrawEntityLight(lightentities[i]);
4350         }
4351         else
4352         {
4353                 // draw lighting in the unmasked areas
4354                 R_Shadow_RenderMode_Lighting(false, false, false);
4355                 if (numsurfaces)
4356                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4357                 for (i = 0;i < numlightentities;i++)
4358                         R_Shadow_DrawEntityLight(lightentities[i]);
4359                 for (i = 0;i < numlightentities_noselfshadow;i++)
4360                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4361         }
4362
4363         if (r_shadow_usingdeferredprepass)
4364         {
4365                 // when rendering deferred lighting, we simply rasterize the box
4366                 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4367                         R_Shadow_RenderMode_DrawDeferredLight(false, true);
4368                 else if (castshadows && vid.stencil)
4369                         R_Shadow_RenderMode_DrawDeferredLight(true, false);
4370                 else
4371                         R_Shadow_RenderMode_DrawDeferredLight(false, false);
4372         }
4373 }
4374
4375 static void R_Shadow_FreeDeferred(void)
4376 {
4377         R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4378         r_shadow_prepassgeometryfbo = 0;
4379
4380         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4381         r_shadow_prepasslightingdiffusespecularfbo = 0;
4382
4383         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4384         r_shadow_prepasslightingdiffusefbo = 0;
4385
4386         if (r_shadow_prepassgeometrydepthtexture)
4387                 R_FreeTexture(r_shadow_prepassgeometrydepthtexture);
4388         r_shadow_prepassgeometrydepthtexture = NULL;
4389
4390         if (r_shadow_prepassgeometrydepthcolortexture)
4391                 R_FreeTexture(r_shadow_prepassgeometrydepthcolortexture);
4392         r_shadow_prepassgeometrydepthcolortexture = NULL;
4393
4394         if (r_shadow_prepassgeometrynormalmaptexture)
4395                 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4396         r_shadow_prepassgeometrynormalmaptexture = NULL;
4397
4398         if (r_shadow_prepasslightingdiffusetexture)
4399                 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4400         r_shadow_prepasslightingdiffusetexture = NULL;
4401
4402         if (r_shadow_prepasslightingspeculartexture)
4403                 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4404         r_shadow_prepasslightingspeculartexture = NULL;
4405 }
4406
4407 void R_Shadow_DrawPrepass(void)
4408 {
4409         int i;
4410         int flag;
4411         int lnum;
4412         size_t lightindex;
4413         dlight_t *light;
4414         size_t range;
4415         entity_render_t *ent;
4416         float clearcolor[4];
4417
4418         R_Mesh_ResetTextureState();
4419         GL_DepthMask(true);
4420         GL_ColorMask(1,1,1,1);
4421         GL_BlendFunc(GL_ONE, GL_ZERO);
4422         GL_Color(1,1,1,1);
4423         GL_DepthTest(true);
4424         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4425         Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4426         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4427         if (r_timereport_active)
4428                 R_TimeReport("prepasscleargeom");
4429
4430         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4431                 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4432         if (r_timereport_active)
4433                 R_TimeReport("prepassworld");
4434
4435         for (i = 0;i < r_refdef.scene.numentities;i++)
4436         {
4437                 if (!r_refdef.viewcache.entityvisible[i])
4438                         continue;
4439                 ent = r_refdef.scene.entities[i];
4440                 if (ent->model && ent->model->DrawPrepass != NULL)
4441                         ent->model->DrawPrepass(ent);
4442         }
4443
4444         if (r_timereport_active)
4445                 R_TimeReport("prepassmodels");
4446
4447         GL_DepthMask(false);
4448         GL_ColorMask(1,1,1,1);
4449         GL_Color(1,1,1,1);
4450         GL_DepthTest(true);
4451         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4452         Vector4Set(clearcolor, 0, 0, 0, 0);
4453         GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4454         if (r_timereport_active)
4455                 R_TimeReport("prepassclearlit");
4456
4457         R_Shadow_RenderMode_Begin();
4458
4459         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4460         if (r_shadow_debuglight.integer >= 0)
4461         {
4462                 lightindex = r_shadow_debuglight.integer;
4463                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4464                 if (light && (light->flags & flag) && light->rtlight.draw)
4465                         R_Shadow_DrawLight(&light->rtlight);
4466         }
4467         else
4468         {
4469                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4470                 for (lightindex = 0;lightindex < range;lightindex++)
4471                 {
4472                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4473                         if (light && (light->flags & flag) && light->rtlight.draw)
4474                                 R_Shadow_DrawLight(&light->rtlight);
4475                 }
4476         }
4477         if (r_refdef.scene.rtdlight)
4478                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4479                         if (r_refdef.scene.lights[lnum]->draw)
4480                                 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4481
4482         R_Mesh_SetMainRenderTargets();
4483
4484         R_Shadow_RenderMode_End();
4485
4486         if (r_timereport_active)
4487                 R_TimeReport("prepasslights");
4488 }
4489
4490 void R_Shadow_DrawLightSprites(void);
4491 void R_Shadow_PrepareLights(void)
4492 {
4493         int flag;
4494         int lnum;
4495         size_t lightindex;
4496         dlight_t *light;
4497         size_t range;
4498         float f;
4499         GLenum status;
4500
4501         if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4502                 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4503                 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) || 
4504                 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || 
4505                 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer || 
4506                 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
4507                 R_Shadow_FreeShadowMaps();
4508
4509         r_shadow_usingshadowmaportho = false;
4510
4511         switch (vid.renderpath)
4512         {
4513         case RENDERPATH_GL20:
4514         case RENDERPATH_D3D9:
4515         case RENDERPATH_D3D10:
4516         case RENDERPATH_D3D11:
4517         case RENDERPATH_SOFT:
4518 #ifndef USE_GLES2
4519                 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4520                 {
4521                         r_shadow_usingdeferredprepass = false;
4522                         if (r_shadow_prepass_width)
4523                                 R_Shadow_FreeDeferred();
4524                         r_shadow_prepass_width = r_shadow_prepass_height = 0;
4525                         break;
4526                 }
4527
4528                 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4529                 {
4530                         R_Shadow_FreeDeferred();
4531
4532                         r_shadow_usingdeferredprepass = true;
4533                         r_shadow_prepass_width = vid.width;
4534                         r_shadow_prepass_height = vid.height;
4535                         r_shadow_prepassgeometrydepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "prepassgeometrydepthmap", vid.width, vid.height, 24, false);
4536                         switch (vid.renderpath)
4537                         {
4538                         case RENDERPATH_D3D9:
4539                                 r_shadow_prepassgeometrydepthcolortexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrydepthcolormap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4540                                 break;
4541                         default:
4542                                 break;
4543                         }
4544                         r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4545                         r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4546                         r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4547
4548                         // set up the geometry pass fbo (depth + normalmap)
4549                         r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4550                         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4551                         // render depth into one texture and normalmap into the other
4552                         if (qglDrawBuffersARB)
4553                         {
4554                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
4555                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4556                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER);CHECKGLERROR
4557                                 if (status != GL_FRAMEBUFFER_COMPLETE)
4558                                 {
4559                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4560                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4561                                         r_shadow_usingdeferredprepass = false;
4562                                 }
4563                         }
4564
4565                         // set up the lighting pass fbo (diffuse + specular)
4566                         r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4567                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4568                         // render diffuse into one texture and specular into another,
4569                         // with depth and normalmap bound as textures,
4570                         // with depth bound as attachment as well
4571                         if (qglDrawBuffersARB)
4572                         {
4573                                 qglDrawBuffersARB(2, r_shadow_prepasslightingdrawbuffers);CHECKGLERROR
4574                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4575                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER);CHECKGLERROR
4576                                 if (status != GL_FRAMEBUFFER_COMPLETE)
4577                                 {
4578                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4579                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4580                                         r_shadow_usingdeferredprepass = false;
4581                                 }
4582                         }
4583
4584                         // set up the lighting pass fbo (diffuse)
4585                         r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4586                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4587                         // render diffuse into one texture,
4588                         // with depth and normalmap bound as textures,
4589                         // with depth bound as attachment as well
4590                         if (qglDrawBuffersARB)
4591                         {
4592                                 qglDrawBuffer(GL_COLOR_ATTACHMENT0);CHECKGLERROR
4593                                 qglReadBuffer(GL_NONE);CHECKGLERROR
4594                                 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER);CHECKGLERROR
4595                                 if (status != GL_FRAMEBUFFER_COMPLETE)
4596                                 {
4597                                         Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4598                                         Cvar_SetValueQuick(&r_shadow_deferred, 0);
4599                                         r_shadow_usingdeferredprepass = false;
4600                                 }
4601                         }
4602                 }
4603 #endif
4604                 break;
4605         case RENDERPATH_GL11:
4606         case RENDERPATH_GL13:
4607         case RENDERPATH_GLES1:
4608         case RENDERPATH_GLES2:
4609                 r_shadow_usingdeferredprepass = false;
4610                 break;
4611         }
4612
4613         R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles);
4614
4615         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4616         if (r_shadow_bouncegrid.integer != 2)
4617         {
4618                 if (r_shadow_debuglight.integer >= 0)
4619                 {
4620                         lightindex = r_shadow_debuglight.integer;
4621                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4622                         if (light)
4623                                 R_Shadow_PrepareLight(&light->rtlight);
4624                 }
4625                 else
4626                 {
4627                         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4628                         for (lightindex = 0;lightindex < range;lightindex++)
4629                         {
4630                                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4631                                 if (light && (light->flags & flag))
4632                                         R_Shadow_PrepareLight(&light->rtlight);
4633                         }
4634                 }
4635         }
4636         if (r_refdef.scene.rtdlight)
4637         {
4638                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4639                         R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4640         }
4641         else if(gl_flashblend.integer)
4642         {
4643                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4644                 {
4645                         rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4646                         f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4647                         VectorScale(rtlight->color, f, rtlight->currentcolor);
4648                 }
4649         }
4650
4651         if (r_editlights.integer)
4652                 R_Shadow_DrawLightSprites();
4653 }
4654
4655 void R_Shadow_DrawLights(void)
4656 {
4657         int flag;
4658         int lnum;
4659         size_t lightindex;
4660         dlight_t *light;
4661         size_t range;
4662
4663         R_Shadow_RenderMode_Begin();
4664
4665         if (r_shadow_bouncegrid.integer != 2)
4666         {
4667                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4668                 if (r_shadow_debuglight.integer >= 0)
4669                 {
4670                         lightindex = r_shadow_debuglight.integer;
4671                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4672                         if (light)
4673                                 R_Shadow_DrawLight(&light->rtlight);
4674                 }
4675                 else
4676                 {
4677                         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4678                         for (lightindex = 0;lightindex < range;lightindex++)
4679                         {
4680                                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4681                                 if (light && (light->flags & flag))
4682                                         R_Shadow_DrawLight(&light->rtlight);
4683                         }
4684                 }
4685         }
4686         if (r_refdef.scene.rtdlight)
4687                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4688                         R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4689
4690         R_Shadow_RenderMode_End();
4691 }
4692
4693 extern const float r_screenvertex3f[12];
4694 extern void R_SetupView(qboolean allowwaterclippingplane);
4695 extern void R_ResetViewRendering3D(void);
4696 extern void R_ResetViewRendering2D(void);
4697 extern cvar_t r_shadows;
4698 extern cvar_t r_shadows_darken;
4699 extern cvar_t r_shadows_drawafterrtlighting;
4700 extern cvar_t r_shadows_castfrombmodels;
4701 extern cvar_t r_shadows_throwdistance;
4702 extern cvar_t r_shadows_throwdirection;
4703 extern cvar_t r_shadows_focus;
4704 extern cvar_t r_shadows_shadowmapscale;
4705
4706 void R_Shadow_PrepareModelShadows(void)
4707 {
4708         int i;
4709         float scale, size, radius, dot1, dot2;
4710         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4711         entity_render_t *ent;
4712
4713         if (!r_refdef.scene.numentities)
4714                 return;
4715
4716         switch (r_shadow_shadowmode)
4717         {
4718         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4719                 if (r_shadows.integer >= 2) 
4720                         break;
4721                 // fall through
4722         case R_SHADOW_SHADOWMODE_STENCIL:
4723                 for (i = 0;i < r_refdef.scene.numentities;i++)
4724                 {
4725                         ent = r_refdef.scene.entities[i];
4726                         if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4727                                 R_AnimCache_GetEntity(ent, false, false);
4728                 }
4729                 return;
4730         default:
4731                 return;
4732         }
4733
4734         size = 2*r_shadow_shadowmapmaxsize;
4735         scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4736         radius = 0.5f * size / scale;
4737
4738         Math_atov(r_shadows_throwdirection.string, shadowdir);
4739         VectorNormalize(shadowdir);
4740         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4741         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4742         if (fabs(dot1) <= fabs(dot2))
4743                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4744         else
4745                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4746         VectorNormalize(shadowforward);
4747         CrossProduct(shadowdir, shadowforward, shadowright);
4748         Math_atov(r_shadows_focus.string, shadowfocus);
4749         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4750         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4751         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4752         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4753         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4754                 dot1 = 1;
4755         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4756
4757         shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4758         shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4759         shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4760         shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4761         shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4762         shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4763
4764         for (i = 0;i < r_refdef.scene.numentities;i++)
4765         {
4766                 ent = r_refdef.scene.entities[i];
4767                 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4768                         continue;
4769                 // cast shadows from anything of the map (submodels are optional)
4770                 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4771                         R_AnimCache_GetEntity(ent, false, false);
4772         }
4773 }
4774
4775 void R_DrawModelShadowMaps(void)
4776 {
4777         int i;
4778         float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4779         entity_render_t *ent;
4780         vec3_t relativelightorigin;
4781         vec3_t relativelightdirection, relativeforward, relativeright;
4782         vec3_t relativeshadowmins, relativeshadowmaxs;
4783         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4784         float m[12];
4785         matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4786         r_viewport_t viewport;
4787         GLuint fbo = 0;
4788         float clearcolor[4];
4789
4790         if (!r_refdef.scene.numentities)
4791                 return;
4792
4793         switch (r_shadow_shadowmode)
4794         {
4795         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4796                 break;
4797         default:
4798                 return;
4799         }
4800
4801         R_ResetViewRendering3D();
4802         R_Shadow_RenderMode_Begin();
4803         R_Shadow_RenderMode_ActiveLight(NULL);
4804
4805         switch (r_shadow_shadowmode)
4806         {
4807         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4808                 if (!r_shadow_shadowmap2dtexture)
4809                         R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4810                 fbo = r_shadow_fbo2d;
4811                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
4812                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
4813                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4814                 break;
4815         default:
4816                 break;
4817         }
4818
4819         size = 2*r_shadow_shadowmapmaxsize;
4820         scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4821         radius = 0.5f / scale;
4822         nearclip = -r_shadows_throwdistance.value;
4823         farclip = r_shadows_throwdistance.value;
4824         bias = r_shadow_shadowmapping_bias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4825
4826         r_shadow_shadowmap_parameters[0] = size;
4827         r_shadow_shadowmap_parameters[1] = size;
4828         r_shadow_shadowmap_parameters[2] = 1.0;
4829         r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4830
4831         Math_atov(r_shadows_throwdirection.string, shadowdir);
4832         VectorNormalize(shadowdir);
4833         Math_atov(r_shadows_focus.string, shadowfocus);
4834         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4835         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4836         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4837         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4838         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4839         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4840         if (fabs(dot1) <= fabs(dot2)) 
4841                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4842         else
4843                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4844         VectorNormalize(shadowforward);
4845         VectorM(scale, shadowforward, &m[0]);
4846         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4847                 dot1 = 1;
4848         m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4849         CrossProduct(shadowdir, shadowforward, shadowright);
4850         VectorM(scale, shadowright, &m[4]);
4851         m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4852         VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4853         m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4854         Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4855         Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4856         R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL); 
4857
4858         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4859
4860         R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
4861         R_SetupShader_DepthOrShadow(true);
4862         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4863         GL_DepthMask(true);
4864         GL_DepthTest(true);
4865         R_SetViewport(&viewport);
4866         GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4867         Vector4Set(clearcolor, 1,1,1,1);
4868         // in D3D9 we have to render to a color texture shadowmap
4869         // in GL we render directly to a depth texture only
4870         if (r_shadow_shadowmap2dtexture)
4871                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4872         else
4873                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4874         // render into a slightly restricted region so that the borders of the
4875         // shadowmap area fade away, rather than streaking across everything
4876         // outside the usable area
4877         GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4878
4879 #if 0
4880         // debugging
4881         R_Mesh_SetMainRenderTargets();
4882         R_SetupShader_ShowDepth(true);
4883         GL_ColorMask(1,1,1,1);
4884         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4885 #endif
4886
4887         for (i = 0;i < r_refdef.scene.numentities;i++)
4888         {
4889                 ent = r_refdef.scene.entities[i];
4890
4891                 // cast shadows from anything of the map (submodels are optional)
4892                 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4893                 {
4894                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4895                         Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4896                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4897                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4898                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4899                         relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4900                         relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4901                         relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4902                         relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4903                         relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4904                         relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4905                         RSurf_ActiveModelEntity(ent, false, false, false);
4906                         ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4907                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4908                 }
4909         }
4910
4911 #if 0
4912         if (r_test.integer)
4913         {
4914                 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4915                 CHECKGLERROR
4916                 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4917                 CHECKGLERROR
4918                 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4919                 Cvar_SetValueQuick(&r_test, 0);
4920                 Z_Free(rawpixels);
4921         }
4922 #endif
4923
4924         R_Shadow_RenderMode_End();
4925
4926         Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4927         Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4928         Matrix4x4_CreateScale3(&scalematrix, size, -size, 1); 
4929         Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4930         Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4931         Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4932
4933         switch (vid.renderpath)
4934         {
4935         case RENDERPATH_GL11:
4936         case RENDERPATH_GL13:
4937         case RENDERPATH_GL20:
4938         case RENDERPATH_SOFT:
4939         case RENDERPATH_GLES1:
4940         case RENDERPATH_GLES2:
4941                 break;
4942         case RENDERPATH_D3D9:
4943         case RENDERPATH_D3D10:
4944         case RENDERPATH_D3D11:
4945 #ifdef OPENGL_ORIENTATION
4946                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4947                 r_shadow_shadowmapmatrix.m[0][1]        *= -1.0f;
4948                 r_shadow_shadowmapmatrix.m[0][2]        *= -1.0f;
4949                 r_shadow_shadowmapmatrix.m[0][3]        *= -1.0f;
4950 #else
4951                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4952                 r_shadow_shadowmapmatrix.m[1][0]        *= -1.0f;
4953                 r_shadow_shadowmapmatrix.m[2][0]        *= -1.0f;
4954                 r_shadow_shadowmapmatrix.m[3][0]        *= -1.0f;
4955 #endif
4956                 break;
4957         }
4958
4959         r_shadow_usingshadowmaportho = true;
4960         switch (r_shadow_shadowmode)
4961         {
4962         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4963                 r_shadow_usingshadowmap2d = true;
4964                 break;
4965         default:
4966                 break;
4967         }
4968 }
4969
4970 void R_DrawModelShadows(void)
4971 {
4972         int i;
4973         float relativethrowdistance;
4974         entity_render_t *ent;
4975         vec3_t relativelightorigin;
4976         vec3_t relativelightdirection;
4977         vec3_t relativeshadowmins, relativeshadowmaxs;
4978         vec3_t tmp, shadowdir;
4979
4980         if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
4981                 return;
4982
4983         R_ResetViewRendering3D();
4984         //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
4985         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
4986         R_Shadow_RenderMode_Begin();
4987         R_Shadow_RenderMode_ActiveLight(NULL);
4988         r_shadow_lightscissor[0] = r_refdef.view.x;
4989         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
4990         r_shadow_lightscissor[2] = r_refdef.view.width;
4991         r_shadow_lightscissor[3] = r_refdef.view.height;
4992         R_Shadow_RenderMode_StencilShadowVolumes(false);
4993
4994         // get shadow dir
4995         if (r_shadows.integer == 2)
4996         {
4997                 Math_atov(r_shadows_throwdirection.string, shadowdir);
4998                 VectorNormalize(shadowdir);
4999         }
5000
5001         R_Shadow_ClearStencil();
5002
5003         for (i = 0;i < r_refdef.scene.numentities;i++)
5004         {
5005                 ent = r_refdef.scene.entities[i];
5006
5007                 // cast shadows from anything of the map (submodels are optional)
5008                 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
5009                 {
5010                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5011                         VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5012                         VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5013                         if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5014                                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5015                         else
5016                         {
5017                                 if(ent->entitynumber != 0)
5018                                 {
5019                                         if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5020                                         {
5021                                                 // FIXME handle this
5022                                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5023                                         }
5024                                         else
5025                                         {
5026                                                 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5027                                                 int entnum, entnum2, recursion;
5028                                                 entnum = entnum2 = ent->entitynumber;
5029                                                 for(recursion = 32; recursion > 0; --recursion)
5030                                                 {
5031                                                         entnum2 = cl.entities[entnum].state_current.tagentity;
5032                                                         if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5033                                                                 entnum = entnum2;
5034                                                         else
5035                                                                 break;
5036                                                 }
5037                                                 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5038                                                 {
5039                                                         VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5040                                                         // transform into modelspace of OUR entity
5041                                                         Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5042                                                         Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5043                                                 }
5044                                                 else
5045                                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5046                                         }
5047                                 }
5048                                 else
5049                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5050                         }
5051
5052                         VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5053                         RSurf_ActiveModelEntity(ent, false, false, false);
5054                         ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5055                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5056                 }
5057         }
5058
5059         // not really the right mode, but this will disable any silly stencil features
5060         R_Shadow_RenderMode_End();
5061
5062         // set up ortho view for rendering this pass
5063         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5064         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5065         //GL_ScissorTest(true);
5066         //R_EntityMatrix(&identitymatrix);
5067         //R_Mesh_ResetTextureState();
5068         R_ResetViewRendering2D();
5069
5070         // set up a darkening blend on shadowed areas
5071         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5072         //GL_DepthRange(0, 1);
5073         //GL_DepthTest(false);
5074         //GL_DepthMask(false);
5075         //GL_PolygonOffset(0, 0);CHECKGLERROR
5076         GL_Color(0, 0, 0, r_shadows_darken.value);
5077         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5078         //GL_DepthFunc(GL_ALWAYS);
5079         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5080
5081         // apply the blend to the shadowed areas
5082         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5083         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, true);
5084         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5085
5086         // restore the viewport
5087         R_SetViewport(&r_refdef.view.viewport);
5088
5089         // restore other state to normal
5090         //R_Shadow_RenderMode_End();
5091 }
5092
5093 void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5094 {
5095         float zdist;
5096         vec3_t centerorigin;
5097         float vertex3f[12];
5098         // if it's too close, skip it
5099         if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5100                 return;
5101         zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5102         if (zdist < 32)
5103                 return;
5104         if (usequery && r_numqueries + 2 <= r_maxqueries)
5105         {
5106                 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5107                 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5108                 // we count potential samples in the middle of the screen, we count actual samples at the light location, this allows counting potential samples of off-screen lights
5109                 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5110
5111                 switch(vid.renderpath)
5112                 {
5113                 case RENDERPATH_GL11:
5114                 case RENDERPATH_GL13:
5115                 case RENDERPATH_GL20:
5116                 case RENDERPATH_GLES1:
5117                 case RENDERPATH_GLES2:
5118 #ifdef GL_SAMPLES_PASSED_ARB
5119                         CHECKGLERROR
5120                         // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5121                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5122                         GL_DepthFunc(GL_ALWAYS);
5123                         R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5124                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5125                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5126                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5127                         GL_DepthFunc(GL_LEQUAL);
5128                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5129                         R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5130                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5131                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5132                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5133                         CHECKGLERROR
5134 #endif
5135                         break;
5136                 case RENDERPATH_D3D9:
5137                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5138                         break;
5139                 case RENDERPATH_D3D10:
5140                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5141                         break;
5142                 case RENDERPATH_D3D11:
5143                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5144                         break;
5145                 case RENDERPATH_SOFT:
5146                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5147                         break;
5148                 }
5149         }
5150         rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5151 }
5152
5153 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5154
5155 void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5156 {
5157         vec3_t color;
5158         GLint allpixels = 0, visiblepixels = 0;
5159         // now we have to check the query result
5160         if (rtlight->corona_queryindex_visiblepixels)
5161         {
5162                 switch(vid.renderpath)
5163                 {
5164                 case RENDERPATH_GL11:
5165                 case RENDERPATH_GL13:
5166                 case RENDERPATH_GL20:
5167                 case RENDERPATH_GLES1:
5168                 case RENDERPATH_GLES2:
5169 #ifdef GL_SAMPLES_PASSED_ARB
5170                         CHECKGLERROR
5171                         qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5172                         qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5173                         CHECKGLERROR
5174 #endif
5175                         break;
5176                 case RENDERPATH_D3D9:
5177                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5178                         break;
5179                 case RENDERPATH_D3D10:
5180                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5181                         break;
5182                 case RENDERPATH_D3D11:
5183                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5184                         break;
5185                 case RENDERPATH_SOFT:
5186                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5187                         break;
5188                 }
5189                 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5190                 if (visiblepixels < 1 || allpixels < 1)
5191                         return;
5192                 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5193                 cscale *= rtlight->corona_visibility;
5194         }
5195         else
5196         {
5197                 // FIXME: these traces should scan all render entities instead of cl.world
5198                 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5199                         return;
5200         }
5201         VectorScale(rtlight->currentcolor, cscale, color);
5202         if (VectorLength(color) > (1.0f / 256.0f))
5203         {
5204                 float vertex3f[12];
5205                 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5206                 if(negated)
5207                 {
5208                         VectorNegate(color, color);
5209                         GL_BlendEquationSubtract(true);
5210                 }
5211                 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5212                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, RENDER_NODEPTHTEST, 0, color[0], color[1], color[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5213                 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5214                 if(negated)
5215                         GL_BlendEquationSubtract(false);
5216         }
5217 }
5218
5219 void R_Shadow_DrawCoronas(void)
5220 {
5221         int i, flag;
5222         qboolean usequery = false;
5223         size_t lightindex;
5224         dlight_t *light;
5225         rtlight_t *rtlight;
5226         size_t range;
5227         if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5228                 return;
5229         if (r_waterstate.renderingscene)
5230                 return;
5231         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5232         R_EntityMatrix(&identitymatrix);
5233
5234         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5235
5236         // check occlusion of coronas
5237         // use GL_ARB_occlusion_query if available
5238         // otherwise use raytraces
5239         r_numqueries = 0;
5240         switch (vid.renderpath)
5241         {
5242         case RENDERPATH_GL11:
5243         case RENDERPATH_GL13:
5244         case RENDERPATH_GL20:
5245         case RENDERPATH_GLES1:
5246         case RENDERPATH_GLES2:
5247                 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5248 #ifdef GL_SAMPLES_PASSED_ARB
5249                 if (usequery)
5250                 {
5251                         GL_ColorMask(0,0,0,0);
5252                         if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5253                         if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5254                         {
5255                                 i = r_maxqueries;
5256                                 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5257                                 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5258                                 CHECKGLERROR
5259                                 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5260                                 CHECKGLERROR
5261                         }
5262                         RSurf_ActiveWorldEntity();
5263                         GL_BlendFunc(GL_ONE, GL_ZERO);
5264                         GL_CullFace(GL_NONE);
5265                         GL_DepthMask(false);
5266                         GL_DepthRange(0, 1);
5267                         GL_PolygonOffset(0, 0);
5268                         GL_DepthTest(true);
5269                         R_Mesh_ResetTextureState();
5270                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1, false, false);
5271                 }
5272 #endif
5273                 break;
5274         case RENDERPATH_D3D9:
5275                 usequery = false;
5276                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5277                 break;
5278         case RENDERPATH_D3D10:
5279                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5280                 break;
5281         case RENDERPATH_D3D11:
5282                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5283                 break;
5284         case RENDERPATH_SOFT:
5285                 usequery = false;
5286                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5287                 break;
5288         }
5289         for (lightindex = 0;lightindex < range;lightindex++)
5290         {
5291                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5292                 if (!light)
5293                         continue;
5294                 rtlight = &light->rtlight;
5295                 rtlight->corona_visibility = 0;
5296                 rtlight->corona_queryindex_visiblepixels = 0;
5297                 rtlight->corona_queryindex_allpixels = 0;
5298                 if (!(rtlight->flags & flag))
5299                         continue;
5300                 if (rtlight->corona <= 0)
5301                         continue;
5302                 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5303                         continue;
5304                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5305         }
5306         for (i = 0;i < r_refdef.scene.numlights;i++)
5307         {
5308                 rtlight = r_refdef.scene.lights[i];
5309                 rtlight->corona_visibility = 0;
5310                 rtlight->corona_queryindex_visiblepixels = 0;
5311                 rtlight->corona_queryindex_allpixels = 0;
5312                 if (!(rtlight->flags & flag))
5313                         continue;
5314                 if (rtlight->corona <= 0)
5315                         continue;
5316                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5317         }
5318         if (usequery)
5319                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5320
5321         // now draw the coronas using the query data for intensity info
5322         for (lightindex = 0;lightindex < range;lightindex++)
5323         {
5324                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5325                 if (!light)
5326                         continue;
5327                 rtlight = &light->rtlight;
5328                 if (rtlight->corona_visibility <= 0)
5329                         continue;
5330                 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5331         }
5332         for (i = 0;i < r_refdef.scene.numlights;i++)
5333         {
5334                 rtlight = r_refdef.scene.lights[i];
5335                 if (rtlight->corona_visibility <= 0)
5336                         continue;
5337                 if (gl_flashblend.integer)
5338                         R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5339                 else
5340                         R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5341         }
5342 }
5343
5344
5345
5346 dlight_t *R_Shadow_NewWorldLight(void)
5347 {
5348         return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5349 }
5350
5351 void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
5352 {
5353         matrix4x4_t matrix;
5354         // validate parameters
5355         if (style < 0 || style >= MAX_LIGHTSTYLES)
5356         {
5357                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5358                 style = 0;
5359         }
5360         if (!cubemapname)
5361                 cubemapname = "";
5362
5363         // copy to light properties
5364         VectorCopy(origin, light->origin);
5365         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5366         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5367         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5368         /*
5369         light->color[0] = max(color[0], 0);
5370         light->color[1] = max(color[1], 0);
5371         light->color[2] = max(color[2], 0);
5372         */
5373         light->color[0] = color[0];
5374         light->color[1] = color[1];
5375         light->color[2] = color[2];
5376         light->radius = max(radius, 0);
5377         light->style = style;
5378         light->shadow = shadowenable;
5379         light->corona = corona;
5380         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5381         light->coronasizescale = coronasizescale;
5382         light->ambientscale = ambientscale;
5383         light->diffusescale = diffusescale;
5384         light->specularscale = specularscale;
5385         light->flags = flags;
5386
5387         // update renderable light data
5388         Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5389         R_RTLight_Update(&light->rtlight, true, &matrix, light->color, light->style, light->cubemapname[0] ? light->cubemapname : NULL, light->shadow, light->corona, light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5390 }
5391
5392 void R_Shadow_FreeWorldLight(dlight_t *light)
5393 {
5394         if (r_shadow_selectedlight == light)
5395                 r_shadow_selectedlight = NULL;
5396         R_RTLight_Uncompile(&light->rtlight);
5397         Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5398 }
5399
5400 void R_Shadow_ClearWorldLights(void)
5401 {
5402         size_t lightindex;
5403         dlight_t *light;
5404         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5405         for (lightindex = 0;lightindex < range;lightindex++)
5406         {
5407                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5408                 if (light)
5409                         R_Shadow_FreeWorldLight(light);
5410         }
5411         r_shadow_selectedlight = NULL;
5412 }
5413
5414 void R_Shadow_SelectLight(dlight_t *light)
5415 {
5416         if (r_shadow_selectedlight)
5417                 r_shadow_selectedlight->selected = false;
5418         r_shadow_selectedlight = light;
5419         if (r_shadow_selectedlight)
5420                 r_shadow_selectedlight->selected = true;
5421 }
5422
5423 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5424 {
5425         // this is never batched (there can be only one)
5426         float vertex3f[12];
5427         R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5428         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5429         R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5430 }
5431
5432 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5433 {
5434         float intensity;
5435         float s;
5436         vec3_t spritecolor;
5437         skinframe_t *skinframe;
5438         float vertex3f[12];
5439
5440         // this is never batched (due to the ent parameter changing every time)
5441         // so numsurfaces == 1 and surfacelist[0] == lightnumber
5442         const dlight_t *light = (dlight_t *)ent;
5443         s = EDLIGHTSPRSIZE;
5444
5445         R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5446
5447         intensity = 0.5f;
5448         VectorScale(light->color, intensity, spritecolor);
5449         if (VectorLength(spritecolor) < 0.1732f)
5450                 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5451         if (VectorLength(spritecolor) > 1.0f)
5452                 VectorNormalize(spritecolor);
5453
5454         // draw light sprite
5455         if (light->cubemapname[0] && !light->shadow)
5456                 skinframe = r_editlights_sprcubemapnoshadowlight;
5457         else if (light->cubemapname[0])
5458                 skinframe = r_editlights_sprcubemaplight;
5459         else if (!light->shadow)
5460                 skinframe = r_editlights_sprnoshadowlight;
5461         else
5462                 skinframe = r_editlights_sprlight;
5463
5464         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, spritecolor[0], spritecolor[1], spritecolor[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5465         R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5466
5467         // draw selection sprite if light is selected
5468         if (light->selected)
5469         {
5470                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5471                 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5472                 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5473         }
5474 }
5475
5476 void R_Shadow_DrawLightSprites(void)
5477 {
5478         size_t lightindex;
5479         dlight_t *light;
5480         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5481         for (lightindex = 0;lightindex < range;lightindex++)
5482         {
5483                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5484                 if (light)
5485                         R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5486         }
5487         if (!r_editlights_lockcursor)
5488                 R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5489 }
5490
5491 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5492 {
5493         unsigned int range;
5494         dlight_t *light;
5495         rtlight_t *rtlight;
5496         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5497         if (lightindex >= range)
5498                 return -1;
5499         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5500         if (!light)
5501                 return 0;
5502         rtlight = &light->rtlight;
5503         //if (!(rtlight->flags & flag))
5504         //      return 0;
5505         VectorCopy(rtlight->shadoworigin, origin);
5506         *radius = rtlight->radius;
5507         VectorCopy(rtlight->color, color);
5508         return 1;
5509 }
5510
5511 void R_Shadow_SelectLightInView(void)
5512 {
5513         float bestrating, rating, temp[3];
5514         dlight_t *best;
5515         size_t lightindex;
5516         dlight_t *light;
5517         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5518         best = NULL;
5519         bestrating = 0;
5520
5521         if (r_editlights_lockcursor)
5522                 return;
5523         for (lightindex = 0;lightindex < range;lightindex++)
5524         {
5525                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5526                 if (!light)
5527                         continue;
5528                 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5529                 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5530                 if (rating >= 0.95)
5531                 {
5532                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5533                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5534                         {
5535                                 bestrating = rating;
5536                                 best = light;
5537                         }
5538                 }
5539         }
5540         R_Shadow_SelectLight(best);
5541 }
5542
5543 void R_Shadow_LoadWorldLights(void)
5544 {
5545         int n, a, style, shadow, flags;
5546         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5547         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5548         if (cl.worldmodel == NULL)
5549         {
5550                 Con_Print("No map loaded.\n");
5551                 return;
5552         }
5553         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5554         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5555         if (lightsstring)
5556         {
5557                 s = lightsstring;
5558                 n = 0;
5559                 while (*s)
5560                 {
5561                         t = s;
5562                         /*
5563                         shadow = true;
5564                         for (;COM_Parse(t, true) && strcmp(
5565                         if (COM_Parse(t, true))
5566                         {
5567                                 if (com_token[0] == '!')
5568                                 {
5569                                         shadow = false;
5570                                         origin[0] = atof(com_token+1);
5571                                 }
5572                                 else
5573                                         origin[0] = atof(com_token);
5574                                 if (Com_Parse(t
5575                         }
5576                         */
5577                         t = s;
5578                         while (*s && *s != '\n' && *s != '\r')
5579                                 s++;
5580                         if (!*s)
5581                                 break;
5582                         tempchar = *s;
5583                         shadow = true;
5584                         // check for modifier flags
5585                         if (*t == '!')
5586                         {
5587                                 shadow = false;
5588                                 t++;
5589                         }
5590                         *s = 0;
5591 #if _MSC_VER >= 1400
5592 #define sscanf sscanf_s
5593 #endif
5594                         cubemapname[sizeof(cubemapname)-1] = 0;
5595 #if MAX_QPATH != 128
5596 #error update this code if MAX_QPATH changes
5597 #endif
5598                         a = sscanf(t, "%f %f %f %f %f %f %f %d %127s %f %f %f %f %f %f %f %f %i", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, cubemapname
5599 #if _MSC_VER >= 1400
5600 , sizeof(cubemapname)
5601 #endif
5602 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5603                         *s = tempchar;
5604                         if (a < 18)
5605                                 flags = LIGHTFLAG_REALTIMEMODE;
5606                         if (a < 17)
5607                                 specularscale = 1;
5608                         if (a < 16)
5609                                 diffusescale = 1;
5610                         if (a < 15)
5611                                 ambientscale = 0;
5612                         if (a < 14)
5613                                 coronasizescale = 0.25f;
5614                         if (a < 13)
5615                                 VectorClear(angles);
5616                         if (a < 10)
5617                                 corona = 0;
5618                         if (a < 9 || !strcmp(cubemapname, "\"\""))
5619                                 cubemapname[0] = 0;
5620                         // remove quotes on cubemapname
5621                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5622                         {
5623                                 size_t namelen;
5624                                 namelen = strlen(cubemapname) - 2;
5625                                 memmove(cubemapname, cubemapname + 1, namelen);
5626                                 cubemapname[namelen] = '\0';
5627                         }
5628                         if (a < 8)
5629                         {
5630                                 Con_Printf("found %d parameters on line %i, should be 8 or more parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style \"cubemapname\" corona angles[0] angles[1] angles[2] coronasizescale ambientscale diffusescale specularscale flags)\n", a, n + 1);
5631                                 break;
5632                         }
5633                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5634                         if (*s == '\r')
5635                                 s++;
5636                         if (*s == '\n')
5637                                 s++;
5638                         n++;
5639                 }
5640                 if (*s)
5641                         Con_Printf("invalid rtlights file \"%s\"\n", name);
5642                 Mem_Free(lightsstring);
5643         }
5644 }
5645
5646 void R_Shadow_SaveWorldLights(void)
5647 {
5648         size_t lightindex;
5649         dlight_t *light;
5650         size_t bufchars, bufmaxchars;
5651         char *buf, *oldbuf;
5652         char name[MAX_QPATH];
5653         char line[MAX_INPUTLINE];
5654         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5655         // I hate lines which are 3 times my screen size :( --blub
5656         if (!range)
5657                 return;
5658         if (cl.worldmodel == NULL)
5659         {
5660                 Con_Print("No map loaded.\n");
5661                 return;
5662         }
5663         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5664         bufchars = bufmaxchars = 0;
5665         buf = NULL;
5666         for (lightindex = 0;lightindex < range;lightindex++)
5667         {
5668                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5669                 if (!light)
5670                         continue;
5671                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5672                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f %f %f %f %f %i\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2], light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags);
5673                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5674                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d \"%s\" %f %f %f %f\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style, light->cubemapname, light->corona, light->angles[0], light->angles[1], light->angles[2]);
5675                 else
5676                         dpsnprintf(line, sizeof(line), "%s%f %f %f %f %f %f %f %d\n", light->shadow ? "" : "!", light->origin[0], light->origin[1], light->origin[2], light->radius, light->color[0], light->color[1], light->color[2], light->style);
5677                 if (bufchars + strlen(line) > bufmaxchars)
5678                 {
5679                         bufmaxchars = bufchars + strlen(line) + 2048;
5680                         oldbuf = buf;
5681                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5682                         if (oldbuf)
5683                         {
5684                                 if (bufchars)
5685                                         memcpy(buf, oldbuf, bufchars);
5686                                 Mem_Free(oldbuf);
5687                         }
5688                 }
5689                 if (strlen(line))
5690                 {
5691                         memcpy(buf + bufchars, line, strlen(line));
5692                         bufchars += strlen(line);
5693                 }
5694         }
5695         if (bufchars)
5696                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5697         if (buf)
5698                 Mem_Free(buf);
5699 }
5700
5701 void R_Shadow_LoadLightsFile(void)
5702 {
5703         int n, a, style;
5704         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5705         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5706         if (cl.worldmodel == NULL)
5707         {
5708                 Con_Print("No map loaded.\n");
5709                 return;
5710         }
5711         dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5712         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5713         if (lightsstring)
5714         {
5715                 s = lightsstring;
5716                 n = 0;
5717                 while (*s)
5718                 {
5719                         t = s;
5720                         while (*s && *s != '\n' && *s != '\r')
5721                                 s++;
5722                         if (!*s)
5723                                 break;
5724                         tempchar = *s;
5725                         *s = 0;
5726                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &origin[0], &origin[1], &origin[2], &falloff, &color[0], &color[1], &color[2], &subtract, &spotdir[0], &spotdir[1], &spotdir[2], &spotcone, &distbias, &style);
5727                         *s = tempchar;
5728                         if (a < 14)
5729                         {
5730                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
5731                                 break;
5732                         }
5733                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5734                         radius = bound(15, radius, 4096);
5735                         VectorScale(color, (2.0f / (8388608.0f)), color);
5736                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5737                         if (*s == '\r')
5738                                 s++;
5739                         if (*s == '\n')
5740                                 s++;
5741                         n++;
5742                 }
5743                 if (*s)
5744                         Con_Printf("invalid lights file \"%s\"\n", name);
5745                 Mem_Free(lightsstring);
5746         }
5747 }
5748
5749 // tyrlite/hmap2 light types in the delay field
5750 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5751
5752 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5753 {
5754         int entnum;
5755         int style;
5756         int islight;
5757         int skin;
5758         int pflags;
5759         //int effects;
5760         int type;
5761         int n;
5762         char *entfiledata;
5763         const char *data;
5764         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5765         char key[256], value[MAX_INPUTLINE];
5766
5767         if (cl.worldmodel == NULL)
5768         {
5769                 Con_Print("No map loaded.\n");
5770                 return;
5771         }
5772         // try to load a .ent file first
5773         dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5774         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5775         // and if that is not found, fall back to the bsp file entity string
5776         if (!data)
5777                 data = cl.worldmodel->brush.entities;
5778         if (!data)
5779                 return;
5780         for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++)
5781         {
5782                 type = LIGHTTYPE_MINUSX;
5783                 origin[0] = origin[1] = origin[2] = 0;
5784                 originhack[0] = originhack[1] = originhack[2] = 0;
5785                 angles[0] = angles[1] = angles[2] = 0;
5786                 color[0] = color[1] = color[2] = 1;
5787                 light[0] = light[1] = light[2] = 1;light[3] = 300;
5788                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5789                 fadescale = 1;
5790                 lightscale = 1;
5791                 style = 0;
5792                 skin = 0;
5793                 pflags = 0;
5794                 //effects = 0;
5795                 islight = false;
5796                 while (1)
5797                 {
5798                         if (!COM_ParseToken_Simple(&data, false, false))
5799                                 break; // error
5800                         if (com_token[0] == '}')
5801                                 break; // end of entity
5802                         if (com_token[0] == '_')
5803                                 strlcpy(key, com_token + 1, sizeof(key));
5804                         else
5805                                 strlcpy(key, com_token, sizeof(key));
5806                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5807                                 key[strlen(key)-1] = 0;
5808                         if (!COM_ParseToken_Simple(&data, false, false))
5809                                 break; // error
5810                         strlcpy(value, com_token, sizeof(value));
5811
5812                         // now that we have the key pair worked out...
5813                         if (!strcmp("light", key))
5814                         {
5815                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5816                                 if (n == 1)
5817                                 {
5818                                         // quake
5819                                         light[0] = vec[0] * (1.0f / 256.0f);
5820                                         light[1] = vec[0] * (1.0f / 256.0f);
5821                                         light[2] = vec[0] * (1.0f / 256.0f);
5822                                         light[3] = vec[0];
5823                                 }
5824                                 else if (n == 4)
5825                                 {
5826                                         // halflife
5827                                         light[0] = vec[0] * (1.0f / 255.0f);
5828                                         light[1] = vec[1] * (1.0f / 255.0f);
5829                                         light[2] = vec[2] * (1.0f / 255.0f);
5830                                         light[3] = vec[3];
5831                                 }
5832                         }
5833                         else if (!strcmp("delay", key))
5834                                 type = atoi(value);
5835                         else if (!strcmp("origin", key))
5836                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5837                         else if (!strcmp("angle", key))
5838                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5839                         else if (!strcmp("angles", key))
5840                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5841                         else if (!strcmp("color", key))
5842                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5843                         else if (!strcmp("wait", key))
5844                                 fadescale = atof(value);
5845                         else if (!strcmp("classname", key))
5846                         {
5847                                 if (!strncmp(value, "light", 5))
5848                                 {
5849                                         islight = true;
5850                                         if (!strcmp(value, "light_fluoro"))
5851                                         {
5852                                                 originhack[0] = 0;
5853                                                 originhack[1] = 0;
5854                                                 originhack[2] = 0;
5855                                                 overridecolor[0] = 1;
5856                                                 overridecolor[1] = 1;
5857                                                 overridecolor[2] = 1;
5858                                         }
5859                                         if (!strcmp(value, "light_fluorospark"))
5860                                         {
5861                                                 originhack[0] = 0;
5862                                                 originhack[1] = 0;
5863                                                 originhack[2] = 0;
5864                                                 overridecolor[0] = 1;
5865                                                 overridecolor[1] = 1;
5866                                                 overridecolor[2] = 1;
5867                                         }
5868                                         if (!strcmp(value, "light_globe"))
5869                                         {
5870                                                 originhack[0] = 0;
5871                                                 originhack[1] = 0;
5872                                                 originhack[2] = 0;
5873                                                 overridecolor[0] = 1;
5874                                                 overridecolor[1] = 0.8;
5875                                                 overridecolor[2] = 0.4;
5876                                         }
5877                                         if (!strcmp(value, "light_flame_large_yellow"))
5878                                         {
5879                                                 originhack[0] = 0;
5880                                                 originhack[1] = 0;
5881                                                 originhack[2] = 0;
5882                                                 overridecolor[0] = 1;
5883                                                 overridecolor[1] = 0.5;
5884                                                 overridecolor[2] = 0.1;
5885                                         }
5886                                         if (!strcmp(value, "light_flame_small_yellow"))
5887                                         {
5888                                                 originhack[0] = 0;
5889                                                 originhack[1] = 0;
5890                                                 originhack[2] = 0;
5891                                                 overridecolor[0] = 1;
5892                                                 overridecolor[1] = 0.5;
5893                                                 overridecolor[2] = 0.1;
5894                                         }
5895                                         if (!strcmp(value, "light_torch_small_white"))
5896                                         {
5897                                                 originhack[0] = 0;
5898                                                 originhack[1] = 0;
5899                                                 originhack[2] = 0;
5900                                                 overridecolor[0] = 1;
5901                                                 overridecolor[1] = 0.5;
5902                                                 overridecolor[2] = 0.1;
5903                                         }
5904                                         if (!strcmp(value, "light_torch_small_walltorch"))
5905                                         {
5906                                                 originhack[0] = 0;
5907                                                 originhack[1] = 0;
5908                                                 originhack[2] = 0;
5909                                                 overridecolor[0] = 1;
5910                                                 overridecolor[1] = 0.5;
5911                                                 overridecolor[2] = 0.1;
5912                                         }
5913                                 }
5914                         }
5915                         else if (!strcmp("style", key))
5916                                 style = atoi(value);
5917                         else if (!strcmp("skin", key))
5918                                 skin = (int)atof(value);
5919                         else if (!strcmp("pflags", key))
5920                                 pflags = (int)atof(value);
5921                         //else if (!strcmp("effects", key))
5922                         //      effects = (int)atof(value);
5923                         else if (cl.worldmodel->type == mod_brushq3)
5924                         {
5925                                 if (!strcmp("scale", key))
5926                                         lightscale = atof(value);
5927                                 if (!strcmp("fade", key))
5928                                         fadescale = atof(value);
5929                         }
5930                 }
5931                 if (!islight)
5932                         continue;
5933                 if (lightscale <= 0)
5934                         lightscale = 1;
5935                 if (fadescale <= 0)
5936                         fadescale = 1;
5937                 if (color[0] == color[1] && color[0] == color[2])
5938                 {
5939                         color[0] *= overridecolor[0];
5940                         color[1] *= overridecolor[1];
5941                         color[2] *= overridecolor[2];
5942                 }
5943                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
5944                 color[0] = color[0] * light[0];
5945                 color[1] = color[1] * light[1];
5946                 color[2] = color[2] * light[2];
5947                 switch (type)
5948                 {
5949                 case LIGHTTYPE_MINUSX:
5950                         break;
5951                 case LIGHTTYPE_RECIPX:
5952                         radius *= 2;
5953                         VectorScale(color, (1.0f / 16.0f), color);
5954                         break;
5955                 case LIGHTTYPE_RECIPXX:
5956                         radius *= 2;
5957                         VectorScale(color, (1.0f / 16.0f), color);
5958                         break;
5959                 default:
5960                 case LIGHTTYPE_NONE:
5961                         break;
5962                 case LIGHTTYPE_SUN:
5963                         break;
5964                 case LIGHTTYPE_MINUSXX:
5965                         break;
5966                 }
5967                 VectorAdd(origin, originhack, origin);
5968                 if (radius >= 1)
5969                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5970         }
5971         if (entfiledata)
5972                 Mem_Free(entfiledata);
5973 }
5974
5975
5976 void R_Shadow_SetCursorLocationForView(void)
5977 {
5978         vec_t dist, push;
5979         vec3_t dest, endpos;
5980         trace_t trace;
5981         VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
5982         trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
5983         if (trace.fraction < 1)
5984         {
5985                 dist = trace.fraction * r_editlights_cursordistance.value;
5986                 push = r_editlights_cursorpushback.value;
5987                 if (push > dist)
5988                         push = dist;
5989                 push = -push;
5990                 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
5991                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
5992         }
5993         else
5994         {
5995                 VectorClear( endpos );
5996         }
5997         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5998         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5999         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6000 }
6001
6002 void R_Shadow_UpdateWorldLightSelection(void)
6003 {
6004         if (r_editlights.integer)
6005         {
6006                 R_Shadow_SetCursorLocationForView();
6007                 R_Shadow_SelectLightInView();
6008         }
6009         else
6010                 R_Shadow_SelectLight(NULL);
6011 }
6012
6013 void R_Shadow_EditLights_Clear_f(void)
6014 {
6015         R_Shadow_ClearWorldLights();
6016 }
6017
6018 void R_Shadow_EditLights_Reload_f(void)
6019 {
6020         if (!cl.worldmodel)
6021                 return;
6022         strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6023         R_Shadow_ClearWorldLights();
6024         R_Shadow_LoadWorldLights();
6025         if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6026         {
6027                 R_Shadow_LoadLightsFile();
6028                 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6029                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6030         }
6031 }
6032
6033 void R_Shadow_EditLights_Save_f(void)
6034 {
6035         if (!cl.worldmodel)
6036                 return;
6037         R_Shadow_SaveWorldLights();
6038 }
6039
6040 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6041 {
6042         R_Shadow_ClearWorldLights();
6043         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6044 }
6045
6046 void R_Shadow_EditLights_ImportLightsFile_f(void)
6047 {
6048         R_Shadow_ClearWorldLights();
6049         R_Shadow_LoadLightsFile();
6050 }
6051
6052 void R_Shadow_EditLights_Spawn_f(void)
6053 {
6054         vec3_t color;
6055         if (!r_editlights.integer)
6056         {
6057                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6058                 return;
6059         }
6060         if (Cmd_Argc() != 1)
6061         {
6062                 Con_Print("r_editlights_spawn does not take parameters\n");
6063                 return;
6064         }
6065         color[0] = color[1] = color[2] = 1;
6066         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6067 }
6068
6069 void R_Shadow_EditLights_Edit_f(void)
6070 {
6071         vec3_t origin, angles, color;
6072         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6073         int style, shadows, flags, normalmode, realtimemode;
6074         char cubemapname[MAX_INPUTLINE];
6075         if (!r_editlights.integer)
6076         {
6077                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6078                 return;
6079         }
6080         if (!r_shadow_selectedlight)
6081         {
6082                 Con_Print("No selected light.\n");
6083                 return;
6084         }
6085         VectorCopy(r_shadow_selectedlight->origin, origin);
6086         VectorCopy(r_shadow_selectedlight->angles, angles);
6087         VectorCopy(r_shadow_selectedlight->color, color);
6088         radius = r_shadow_selectedlight->radius;
6089         style = r_shadow_selectedlight->style;
6090         if (r_shadow_selectedlight->cubemapname)
6091                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6092         else
6093                 cubemapname[0] = 0;
6094         shadows = r_shadow_selectedlight->shadow;
6095         corona = r_shadow_selectedlight->corona;
6096         coronasizescale = r_shadow_selectedlight->coronasizescale;
6097         ambientscale = r_shadow_selectedlight->ambientscale;
6098         diffusescale = r_shadow_selectedlight->diffusescale;
6099         specularscale = r_shadow_selectedlight->specularscale;
6100         flags = r_shadow_selectedlight->flags;
6101         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6102         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6103         if (!strcmp(Cmd_Argv(1), "origin"))
6104         {
6105                 if (Cmd_Argc() != 5)
6106                 {
6107                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6108                         return;
6109                 }
6110                 origin[0] = atof(Cmd_Argv(2));
6111                 origin[1] = atof(Cmd_Argv(3));
6112                 origin[2] = atof(Cmd_Argv(4));
6113         }
6114         else if (!strcmp(Cmd_Argv(1), "originscale"))
6115         {
6116                 if (Cmd_Argc() != 5)
6117                 {
6118                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6119                         return;
6120                 }
6121                 origin[0] *= atof(Cmd_Argv(2));
6122                 origin[1] *= atof(Cmd_Argv(3));
6123                 origin[2] *= atof(Cmd_Argv(4));
6124         }
6125         else if (!strcmp(Cmd_Argv(1), "originx"))
6126         {
6127                 if (Cmd_Argc() != 3)
6128                 {
6129                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6130                         return;
6131                 }
6132                 origin[0] = atof(Cmd_Argv(2));
6133         }
6134         else if (!strcmp(Cmd_Argv(1), "originy"))
6135         {
6136                 if (Cmd_Argc() != 3)
6137                 {
6138                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6139                         return;
6140                 }
6141                 origin[1] = atof(Cmd_Argv(2));
6142         }
6143         else if (!strcmp(Cmd_Argv(1), "originz"))
6144         {
6145                 if (Cmd_Argc() != 3)
6146                 {
6147                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6148                         return;
6149                 }
6150                 origin[2] = atof(Cmd_Argv(2));
6151         }
6152         else if (!strcmp(Cmd_Argv(1), "move"))
6153         {
6154                 if (Cmd_Argc() != 5)
6155                 {
6156                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6157                         return;
6158                 }
6159                 origin[0] += atof(Cmd_Argv(2));
6160                 origin[1] += atof(Cmd_Argv(3));
6161                 origin[2] += atof(Cmd_Argv(4));
6162         }
6163         else if (!strcmp(Cmd_Argv(1), "movex"))
6164         {
6165                 if (Cmd_Argc() != 3)
6166                 {
6167                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6168                         return;
6169                 }
6170                 origin[0] += atof(Cmd_Argv(2));
6171         }
6172         else if (!strcmp(Cmd_Argv(1), "movey"))
6173         {
6174                 if (Cmd_Argc() != 3)
6175                 {
6176                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6177                         return;
6178                 }
6179                 origin[1] += atof(Cmd_Argv(2));
6180         }
6181         else if (!strcmp(Cmd_Argv(1), "movez"))
6182         {
6183                 if (Cmd_Argc() != 3)
6184                 {
6185                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6186                         return;
6187                 }
6188                 origin[2] += atof(Cmd_Argv(2));
6189         }
6190         else if (!strcmp(Cmd_Argv(1), "angles"))
6191         {
6192                 if (Cmd_Argc() != 5)
6193                 {
6194                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6195                         return;
6196                 }
6197                 angles[0] = atof(Cmd_Argv(2));
6198                 angles[1] = atof(Cmd_Argv(3));
6199                 angles[2] = atof(Cmd_Argv(4));
6200         }
6201         else if (!strcmp(Cmd_Argv(1), "anglesx"))
6202         {
6203                 if (Cmd_Argc() != 3)
6204                 {
6205                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6206                         return;
6207                 }
6208                 angles[0] = atof(Cmd_Argv(2));
6209         }
6210         else if (!strcmp(Cmd_Argv(1), "anglesy"))
6211         {
6212                 if (Cmd_Argc() != 3)
6213                 {
6214                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6215                         return;
6216                 }
6217                 angles[1] = atof(Cmd_Argv(2));
6218         }
6219         else if (!strcmp(Cmd_Argv(1), "anglesz"))
6220         {
6221                 if (Cmd_Argc() != 3)
6222                 {
6223                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6224                         return;
6225                 }
6226                 angles[2] = atof(Cmd_Argv(2));
6227         }
6228         else if (!strcmp(Cmd_Argv(1), "color"))
6229         {
6230                 if (Cmd_Argc() != 5)
6231                 {
6232                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6233                         return;
6234                 }
6235                 color[0] = atof(Cmd_Argv(2));
6236                 color[1] = atof(Cmd_Argv(3));
6237                 color[2] = atof(Cmd_Argv(4));
6238         }
6239         else if (!strcmp(Cmd_Argv(1), "radius"))
6240         {
6241                 if (Cmd_Argc() != 3)
6242                 {
6243                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6244                         return;
6245                 }
6246                 radius = atof(Cmd_Argv(2));
6247         }
6248         else if (!strcmp(Cmd_Argv(1), "colorscale"))
6249         {
6250                 if (Cmd_Argc() == 3)
6251                 {
6252                         double scale = atof(Cmd_Argv(2));
6253                         color[0] *= scale;
6254                         color[1] *= scale;
6255                         color[2] *= scale;
6256                 }
6257                 else
6258                 {
6259                         if (Cmd_Argc() != 5)
6260                         {
6261                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
6262                                 return;
6263                         }
6264                         color[0] *= atof(Cmd_Argv(2));
6265                         color[1] *= atof(Cmd_Argv(3));
6266                         color[2] *= atof(Cmd_Argv(4));
6267                 }
6268         }
6269         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6270         {
6271                 if (Cmd_Argc() != 3)
6272                 {
6273                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6274                         return;
6275                 }
6276                 radius *= atof(Cmd_Argv(2));
6277         }
6278         else if (!strcmp(Cmd_Argv(1), "style"))
6279         {
6280                 if (Cmd_Argc() != 3)
6281                 {
6282                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6283                         return;
6284                 }
6285                 style = atoi(Cmd_Argv(2));
6286         }
6287         else if (!strcmp(Cmd_Argv(1), "cubemap"))
6288         {
6289                 if (Cmd_Argc() > 3)
6290                 {
6291                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6292                         return;
6293                 }
6294                 if (Cmd_Argc() == 3)
6295                         strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6296                 else
6297                         cubemapname[0] = 0;
6298         }
6299         else if (!strcmp(Cmd_Argv(1), "shadows"))
6300         {
6301                 if (Cmd_Argc() != 3)
6302                 {
6303                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6304                         return;
6305                 }
6306                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6307         }
6308         else if (!strcmp(Cmd_Argv(1), "corona"))
6309         {
6310                 if (Cmd_Argc() != 3)
6311                 {
6312                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6313                         return;
6314                 }
6315                 corona = atof(Cmd_Argv(2));
6316         }
6317         else if (!strcmp(Cmd_Argv(1), "coronasize"))
6318         {
6319                 if (Cmd_Argc() != 3)
6320                 {
6321                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6322                         return;
6323                 }
6324                 coronasizescale = atof(Cmd_Argv(2));
6325         }
6326         else if (!strcmp(Cmd_Argv(1), "ambient"))
6327         {
6328                 if (Cmd_Argc() != 3)
6329                 {
6330                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6331                         return;
6332                 }
6333                 ambientscale = atof(Cmd_Argv(2));
6334         }
6335         else if (!strcmp(Cmd_Argv(1), "diffuse"))
6336         {
6337                 if (Cmd_Argc() != 3)
6338                 {
6339                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6340                         return;
6341                 }
6342                 diffusescale = atof(Cmd_Argv(2));
6343         }
6344         else if (!strcmp(Cmd_Argv(1), "specular"))
6345         {
6346                 if (Cmd_Argc() != 3)
6347                 {
6348                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6349                         return;
6350                 }
6351                 specularscale = atof(Cmd_Argv(2));
6352         }
6353         else if (!strcmp(Cmd_Argv(1), "normalmode"))
6354         {
6355                 if (Cmd_Argc() != 3)
6356                 {
6357                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6358                         return;
6359                 }
6360                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6361         }
6362         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6363         {
6364                 if (Cmd_Argc() != 3)
6365                 {
6366                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6367                         return;
6368                 }
6369                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6370         }
6371         else
6372         {
6373                 Con_Print("usage: r_editlights_edit [property] [value]\n");
6374                 Con_Print("Selected light's properties:\n");
6375                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6376                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6377                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6378                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
6379                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
6380                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
6381                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6382                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
6383                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
6384                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
6385                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
6386                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
6387                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6388                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6389                 return;
6390         }
6391         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6392         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6393 }
6394
6395 void R_Shadow_EditLights_EditAll_f(void)
6396 {
6397         size_t lightindex;
6398         dlight_t *light, *oldselected;
6399         size_t range;
6400
6401         if (!r_editlights.integer)
6402         {
6403                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6404                 return;
6405         }
6406
6407         oldselected = r_shadow_selectedlight;
6408         // EditLights doesn't seem to have a "remove" command or something so:
6409         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6410         for (lightindex = 0;lightindex < range;lightindex++)
6411         {
6412                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6413                 if (!light)
6414                         continue;
6415                 R_Shadow_SelectLight(light);
6416                 R_Shadow_EditLights_Edit_f();
6417         }
6418         // return to old selected (to not mess editing once selection is locked)
6419         R_Shadow_SelectLight(oldselected);
6420 }
6421
6422 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6423 {
6424         int lightnumber, lightcount;
6425         size_t lightindex, range;
6426         dlight_t *light;
6427         float x, y;
6428         char temp[256];
6429         if (!r_editlights.integer)
6430                 return;
6431         x = vid_conwidth.value - 240;
6432         y = 5;
6433         DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6434         lightnumber = -1;
6435         lightcount = 0;
6436         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6437         for (lightindex = 0;lightindex < range;lightindex++)
6438         {
6439                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6440                 if (!light)
6441                         continue;
6442                 if (light == r_shadow_selectedlight)
6443                         lightnumber = lightindex;
6444                 lightcount++;
6445         }
6446         dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6447         dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8;
6448         y += 8;
6449         if (r_shadow_selectedlight == NULL)
6450                 return;
6451         dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6452         dpsnprintf(temp, sizeof(temp), "Origin       : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6453         dpsnprintf(temp, sizeof(temp), "Angles       : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6454         dpsnprintf(temp, sizeof(temp), "Color        : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6455         dpsnprintf(temp, sizeof(temp), "Radius       : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6456         dpsnprintf(temp, sizeof(temp), "Corona       : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6457         dpsnprintf(temp, sizeof(temp), "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6458         dpsnprintf(temp, sizeof(temp), "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6459         dpsnprintf(temp, sizeof(temp), "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6460         dpsnprintf(temp, sizeof(temp), "CoronaSize   : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6461         dpsnprintf(temp, sizeof(temp), "Ambient      : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6462         dpsnprintf(temp, sizeof(temp), "Diffuse      : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6463         dpsnprintf(temp, sizeof(temp), "Specular     : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6464         dpsnprintf(temp, sizeof(temp), "NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6465         dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8;
6466 }
6467
6468 void R_Shadow_EditLights_ToggleShadow_f(void)
6469 {
6470         if (!r_editlights.integer)
6471         {
6472                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6473                 return;
6474         }
6475         if (!r_shadow_selectedlight)
6476         {
6477                 Con_Print("No selected light.\n");
6478                 return;
6479         }
6480         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, r_shadow_selectedlight->corona, r_shadow_selectedlight->style, !r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6481 }
6482
6483 void R_Shadow_EditLights_ToggleCorona_f(void)
6484 {
6485         if (!r_editlights.integer)
6486         {
6487                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6488                 return;
6489         }
6490         if (!r_shadow_selectedlight)
6491         {
6492                 Con_Print("No selected light.\n");
6493                 return;
6494         }
6495         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, !r_shadow_selectedlight->corona, r_shadow_selectedlight->style, r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags);
6496 }
6497
6498 void R_Shadow_EditLights_Remove_f(void)
6499 {
6500         if (!r_editlights.integer)
6501         {
6502                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
6503                 return;
6504         }
6505         if (!r_shadow_selectedlight)
6506         {
6507                 Con_Print("No selected light.\n");
6508                 return;
6509         }
6510         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6511         r_shadow_selectedlight = NULL;
6512 }
6513
6514 void R_Shadow_EditLights_Help_f(void)
6515 {
6516         Con_Print(
6517 "Documentation on r_editlights system:\n"
6518 "Settings:\n"
6519 "r_editlights : enable/disable editing mode\n"
6520 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6521 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6522 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6523 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6524 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6525 "Commands:\n"
6526 "r_editlights_help : this help\n"
6527 "r_editlights_clear : remove all lights\n"
6528 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6529 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6530 "r_editlights_save : save to .rtlights file\n"
6531 "r_editlights_spawn : create a light with default settings\n"
6532 "r_editlights_edit command : edit selected light - more documentation below\n"
6533 "r_editlights_remove : remove selected light\n"
6534 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6535 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6536 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6537 "Edit commands:\n"
6538 "origin x y z : set light location\n"
6539 "originx x: set x component of light location\n"
6540 "originy y: set y component of light location\n"
6541 "originz z: set z component of light location\n"
6542 "move x y z : adjust light location\n"
6543 "movex x: adjust x component of light location\n"
6544 "movey y: adjust y component of light location\n"
6545 "movez z: adjust z component of light location\n"
6546 "angles x y z : set light angles\n"
6547 "anglesx x: set x component of light angles\n"
6548 "anglesy y: set y component of light angles\n"
6549 "anglesz z: set z component of light angles\n"
6550 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6551 "radius radius : set radius (size) of light\n"
6552 "colorscale grey : multiply color of light (1 does nothing)\n"
6553 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6554 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6555 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6556 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6557 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6558 "cubemap basename : set filter cubemap of light (not yet supported)\n"
6559 "shadows 1/0 : turn on/off shadows\n"
6560 "corona n : set corona intensity\n"
6561 "coronasize n : set corona size (0-1)\n"
6562 "ambient n : set ambient intensity (0-1)\n"
6563 "diffuse n : set diffuse intensity (0-1)\n"
6564 "specular n : set specular intensity (0-1)\n"
6565 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6566 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6567 "<nothing> : print light properties to console\n"
6568         );
6569 }
6570
6571 void R_Shadow_EditLights_CopyInfo_f(void)
6572 {
6573         if (!r_editlights.integer)
6574         {
6575                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
6576                 return;
6577         }
6578         if (!r_shadow_selectedlight)
6579         {
6580                 Con_Print("No selected light.\n");
6581                 return;
6582         }
6583         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6584         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6585         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6586         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6587         if (r_shadow_selectedlight->cubemapname)
6588                 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6589         else
6590                 r_shadow_bufferlight.cubemapname[0] = 0;
6591         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6592         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6593         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6594         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6595         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6596         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6597         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6598 }
6599
6600 void R_Shadow_EditLights_PasteInfo_f(void)
6601 {
6602         if (!r_editlights.integer)
6603         {
6604                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
6605                 return;
6606         }
6607         if (!r_shadow_selectedlight)
6608         {
6609                 Con_Print("No selected light.\n");
6610                 return;
6611         }
6612         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_bufferlight.angles, r_shadow_bufferlight.color, r_shadow_bufferlight.radius, r_shadow_bufferlight.corona, r_shadow_bufferlight.style, r_shadow_bufferlight.shadow, r_shadow_bufferlight.cubemapname, r_shadow_bufferlight.coronasizescale, r_shadow_bufferlight.ambientscale, r_shadow_bufferlight.diffusescale, r_shadow_bufferlight.specularscale, r_shadow_bufferlight.flags);
6613 }
6614
6615 void R_Shadow_EditLights_Lock_f(void)
6616 {
6617         if (!r_editlights.integer)
6618         {
6619                 Con_Print("Cannot lock on light when not in editing mode.  Set r_editlights to 1.\n");
6620                 return;
6621         }
6622         if (r_editlights_lockcursor)
6623         {
6624                 r_editlights_lockcursor = false;
6625                 return;
6626         }
6627         if (!r_shadow_selectedlight)
6628         {
6629                 Con_Print("No selected light to lock on.\n");
6630                 return;
6631         }
6632         r_editlights_lockcursor = true;
6633 }
6634
6635 void R_Shadow_EditLights_Init(void)
6636 {
6637         Cvar_RegisterVariable(&r_editlights);
6638         Cvar_RegisterVariable(&r_editlights_cursordistance);
6639         Cvar_RegisterVariable(&r_editlights_cursorpushback);
6640         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6641         Cvar_RegisterVariable(&r_editlights_cursorgrid);
6642         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6643         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6644         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6645         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f, "reloads rtlights file (or imports from .lights file or .ent file or the map itself)");
6646         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6647         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6648         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6649         Cmd_AddCommand("r_editlights_editall", R_Shadow_EditLights_EditAll_f, "changes a property on ALL lights at once (tip: use radiusscale and colorscale to alter these properties)");
6650         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6651         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6652         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6653         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6654         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6655         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6656         Cmd_AddCommand("r_editlights_pasteinfo", R_Shadow_EditLights_PasteInfo_f, "apply the stored properties onto the selected light (making it exactly identical except for origin)");
6657         Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6658 }
6659
6660
6661
6662 /*
6663 =============================================================================
6664
6665 LIGHT SAMPLING
6666
6667 =============================================================================
6668 */
6669
6670 void R_LightPoint(vec3_t color, const vec3_t p, const int flags)
6671 {
6672         int i, numlights, flag;
6673         float f, relativepoint[3], dist, dist2, lightradius2;
6674         vec3_t diffuse, n;
6675         rtlight_t *light;
6676         dlight_t *dlight;
6677
6678         if (r_fullbright.integer)
6679         {
6680                 VectorSet(color, 1, 1, 1);
6681                 return;
6682         }
6683
6684         VectorClear(color);
6685
6686         if (flags & LP_LIGHTMAP)
6687         {
6688                 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6689                 {
6690                         VectorClear(diffuse);
6691                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6692                         VectorAdd(color, diffuse, color);
6693                 }
6694                 else
6695                         VectorSet(color, 1, 1, 1);
6696                 color[0] += r_refdef.scene.ambient;
6697                 color[1] += r_refdef.scene.ambient;
6698                 color[2] += r_refdef.scene.ambient;
6699         }
6700
6701         if (flags & LP_RTWORLD)
6702         {
6703                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6704                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6705                 for (i = 0; i < numlights; i++)
6706                 {
6707                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6708                         if (!dlight)
6709                                 continue;
6710                         light = &dlight->rtlight;
6711                         if (!(light->flags & flag))
6712                                 continue;
6713                         // sample
6714                         lightradius2 = light->radius * light->radius;
6715                         VectorSubtract(light->shadoworigin, p, relativepoint);
6716                         dist2 = VectorLength2(relativepoint);
6717                         if (dist2 >= lightradius2)
6718                                 continue;
6719                         dist = sqrt(dist2) / light->radius;
6720                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6721                         if (f <= 0)
6722                                 continue;
6723                         // todo: add to both ambient and diffuse
6724                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6725                                 VectorMA(color, f, light->currentcolor, color);
6726                 }
6727         }
6728         if (flags & LP_DYNLIGHT)
6729         {
6730                 // sample dlights
6731                 for (i = 0;i < r_refdef.scene.numlights;i++)
6732                 {
6733                         light = r_refdef.scene.lights[i];
6734                         // sample
6735                         lightradius2 = light->radius * light->radius;
6736                         VectorSubtract(light->shadoworigin, p, relativepoint);
6737                         dist2 = VectorLength2(relativepoint);
6738                         if (dist2 >= lightradius2)
6739                                 continue;
6740                         dist = sqrt(dist2) / light->radius;
6741                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6742                         if (f <= 0)
6743                                 continue;
6744                         // todo: add to both ambient and diffuse
6745                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6746                                 VectorMA(color, f, light->color, color);
6747                 }
6748         }
6749 }
6750
6751 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6752 {
6753         int i, numlights, flag;
6754         rtlight_t *light;
6755         dlight_t *dlight;
6756         float relativepoint[3];
6757         float color[3];
6758         float dir[3];
6759         float dist;
6760         float dist2;
6761         float intensity;
6762         float sample[5*3];
6763         float lightradius2;
6764
6765         if (r_fullbright.integer)
6766         {
6767                 VectorSet(ambient, 1, 1, 1);
6768                 VectorClear(diffuse);
6769                 VectorClear(lightdir);
6770                 return;
6771         }
6772
6773         if (flags == LP_LIGHTMAP)
6774         {
6775                 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6776                 VectorClear(diffuse);
6777                 VectorClear(lightdir);
6778                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6779                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6780                 else
6781                         VectorSet(ambient, 1, 1, 1);
6782                 return;
6783         }
6784
6785         memset(sample, 0, sizeof(sample));
6786         VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6787
6788         if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6789         {
6790                 vec3_t tempambient;
6791                 VectorClear(tempambient);
6792                 VectorClear(color);
6793                 VectorClear(relativepoint);
6794                 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6795                 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6796                 VectorScale(color, r_refdef.lightmapintensity, color);
6797                 VectorAdd(sample, tempambient, sample);
6798                 VectorMA(sample    , 0.5f            , color, sample    );
6799                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6800                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6801                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6802                 // calculate a weighted average light direction as well
6803                 intensity = VectorLength(color);
6804                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6805         }
6806
6807         if (flags & LP_RTWORLD)
6808         {
6809                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6810                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6811                 for (i = 0; i < numlights; i++)
6812                 {
6813                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6814                         if (!dlight)
6815                                 continue;
6816                         light = &dlight->rtlight;
6817                         if (!(light->flags & flag))
6818                                 continue;
6819                         // sample
6820                         lightradius2 = light->radius * light->radius;
6821                         VectorSubtract(light->shadoworigin, p, relativepoint);
6822                         dist2 = VectorLength2(relativepoint);
6823                         if (dist2 >= lightradius2)
6824                                 continue;
6825                         dist = sqrt(dist2) / light->radius;
6826                         intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6827                         if (intensity <= 0.0f)
6828                                 continue;
6829                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6830                                 continue;
6831                         // scale down intensity to add to both ambient and diffuse
6832                         //intensity *= 0.5f;
6833                         VectorNormalize(relativepoint);
6834                         VectorScale(light->currentcolor, intensity, color);
6835                         VectorMA(sample    , 0.5f            , color, sample    );
6836                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6837                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6838                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6839                         // calculate a weighted average light direction as well
6840                         intensity *= VectorLength(color);
6841                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6842                 }
6843                 // FIXME: sample bouncegrid too!
6844         }
6845
6846         if (flags & LP_DYNLIGHT)
6847         {
6848                 // sample dlights
6849                 for (i = 0;i < r_refdef.scene.numlights;i++)
6850                 {
6851                         light = r_refdef.scene.lights[i];
6852                         // sample
6853                         lightradius2 = light->radius * light->radius;
6854                         VectorSubtract(light->shadoworigin, p, relativepoint);
6855                         dist2 = VectorLength2(relativepoint);
6856                         if (dist2 >= lightradius2)
6857                                 continue;
6858                         dist = sqrt(dist2) / light->radius;
6859                         intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6860                         if (intensity <= 0.0f)
6861                                 continue;
6862                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6863                                 continue;
6864                         // scale down intensity to add to both ambient and diffuse
6865                         //intensity *= 0.5f;
6866                         VectorNormalize(relativepoint);
6867                         VectorScale(light->currentcolor, intensity, color);
6868                         VectorMA(sample    , 0.5f            , color, sample    );
6869                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6870                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6871                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6872                         // calculate a weighted average light direction as well
6873                         intensity *= VectorLength(color);
6874                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6875                 }
6876         }
6877
6878         // calculate the direction we'll use to reduce the sample to a directional light source
6879         VectorCopy(sample + 12, dir);
6880         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6881         VectorNormalize(dir);
6882         // extract the diffuse color along the chosen direction and scale it
6883         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6884         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6885         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6886         // subtract some of diffuse from ambient
6887         VectorMA(sample, -0.333f, diffuse, ambient);
6888         // store the normalized lightdir
6889         VectorCopy(dir, lightdir);
6890 }