]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
fixed a crash with r_shadow_bouncegrid 2 when also using r_shadow_deferred, made...
[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 static 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 qboolean r_shadow_shadowmapshadowsampler;
200 int r_shadow_shadowmappcf;
201 int r_shadow_shadowmapborder;
202 matrix4x4_t r_shadow_shadowmapmatrix;
203 int r_shadow_lightscissor[4];
204 qboolean r_shadow_usingdeferredprepass;
205
206 int maxshadowtriangles;
207 int *shadowelements;
208
209 int maxshadowvertices;
210 float *shadowvertex3f;
211
212 int maxshadowmark;
213 int numshadowmark;
214 int *shadowmark;
215 int *shadowmarklist;
216 int shadowmarkcount;
217
218 int maxshadowsides;
219 int numshadowsides;
220 unsigned char *shadowsides;
221 int *shadowsideslist;
222
223 int maxvertexupdate;
224 int *vertexupdate;
225 int *vertexremap;
226 int vertexupdatenum;
227
228 int r_shadow_buffer_numleafpvsbytes;
229 unsigned char *r_shadow_buffer_visitingleafpvs;
230 unsigned char *r_shadow_buffer_leafpvs;
231 int *r_shadow_buffer_leaflist;
232
233 int r_shadow_buffer_numsurfacepvsbytes;
234 unsigned char *r_shadow_buffer_surfacepvs;
235 int *r_shadow_buffer_surfacelist;
236 unsigned char *r_shadow_buffer_surfacesides;
237
238 int r_shadow_buffer_numshadowtrispvsbytes;
239 unsigned char *r_shadow_buffer_shadowtrispvs;
240 int r_shadow_buffer_numlighttrispvsbytes;
241 unsigned char *r_shadow_buffer_lighttrispvs;
242
243 rtexturepool_t *r_shadow_texturepool;
244 rtexture_t *r_shadow_attenuationgradienttexture;
245 rtexture_t *r_shadow_attenuation2dtexture;
246 rtexture_t *r_shadow_attenuation3dtexture;
247 skinframe_t *r_shadow_lightcorona;
248 rtexture_t *r_shadow_shadowmap2ddepthbuffer;
249 rtexture_t *r_shadow_shadowmap2ddepthtexture;
250 rtexture_t *r_shadow_shadowmapvsdcttexture;
251 int r_shadow_shadowmapsize; // changes for each light based on distance
252 int r_shadow_shadowmaplod; // changes for each light based on distance
253
254 GLuint r_shadow_prepassgeometryfbo;
255 GLuint r_shadow_prepasslightingdiffusespecularfbo;
256 GLuint r_shadow_prepasslightingdiffusefbo;
257 int r_shadow_prepass_width;
258 int r_shadow_prepass_height;
259 rtexture_t *r_shadow_prepassgeometrydepthbuffer;
260 rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
261 rtexture_t *r_shadow_prepasslightingdiffusetexture;
262 rtexture_t *r_shadow_prepasslightingspeculartexture;
263
264 // keep track of the provided framebuffer info
265 static int r_shadow_fb_fbo;
266 static rtexture_t *r_shadow_fb_depthtexture;
267 static rtexture_t *r_shadow_fb_colortexture;
268
269 // lights are reloaded when this changes
270 char r_shadow_mapname[MAX_QPATH];
271
272 // used only for light filters (cubemaps)
273 rtexturepool_t *r_shadow_filters_texturepool;
274
275 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"};
276 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"};
277 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
278 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"};
279 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)"};
280 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
281 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)"};
282 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"};
283 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
284 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
285 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
286 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
287 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
288 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
289 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
290 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
291 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"};
292 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)"};
293 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
294 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
295 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
296 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
297 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)"};
298 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"};
299 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
300 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
301 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"};
302 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)"};
303 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"};
304 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)"};
305 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"};
306 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)"};
307 cvar_t r_shadow_shadowmapping_useshadowsampler = {CVAR_SAVE, "r_shadow_shadowmapping_useshadowsampler", "1", "whether to use sampler2DShadow if available"};
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 static 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_shadowmapshadowsampler = r_shadow_shadowmapping_useshadowsampler.integer != 0;
433         r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
434         r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
435         r_shadow_shadowmaplod = -1;
436         r_shadow_shadowmapsize = 0;
437         r_shadow_shadowmapsampler = false;
438         r_shadow_shadowmappcf = 0;
439         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
440         if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
441         {
442                 switch(vid.renderpath)
443                 {
444                 case RENDERPATH_GL20:
445                         if(r_shadow_shadowmapfilterquality < 0)
446                         {
447                                 if (!r_fb.usedepthtextures)
448                                         r_shadow_shadowmappcf = 1;
449                                 else if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
450                                         r_shadow_shadowmappcf = 1;
451                                 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) 
452                                 {
453                                         r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
454                                         r_shadow_shadowmappcf = 1;
455                                 }
456                                 else if(strstr(gl_vendor, "ATI")) 
457                                         r_shadow_shadowmappcf = 1;
458                                 else 
459                                         r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
460                         }
461                         else 
462                         {
463                                 switch (r_shadow_shadowmapfilterquality)
464                                 {
465                                 case 1:
466                                         r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
467                                         break;
468                                 case 2:
469                                         r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler;
470                                         r_shadow_shadowmappcf = 1;
471                                         break;
472                                 case 3:
473                                         r_shadow_shadowmappcf = 1;
474                                         break;
475                                 case 4:
476                                         r_shadow_shadowmappcf = 2;
477                                         break;
478                                 }
479                         }
480                         if (!r_fb.usedepthtextures)
481                                 r_shadow_shadowmapsampler = false;
482                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
483                         break;
484                 case RENDERPATH_D3D9:
485                 case RENDERPATH_D3D10:
486                 case RENDERPATH_D3D11:
487                 case RENDERPATH_SOFT:
488                         r_shadow_shadowmapsampler = false;
489                         r_shadow_shadowmappcf = 1;
490                         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
491                         break;
492                 case RENDERPATH_GL11:
493                 case RENDERPATH_GL13:
494                 case RENDERPATH_GLES1:
495                 case RENDERPATH_GLES2:
496                         break;
497                 }
498         }
499 }
500
501 qboolean R_Shadow_ShadowMappingEnabled(void)
502 {
503         switch (r_shadow_shadowmode)
504         {
505         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
506                 return true;
507         default:
508                 return false;
509         }
510 }
511
512 static void R_Shadow_FreeShadowMaps(void)
513 {
514         R_Shadow_SetShadowMode();
515
516         R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
517
518         r_shadow_fbo2d = 0;
519
520         if (r_shadow_shadowmap2ddepthtexture)
521                 R_FreeTexture(r_shadow_shadowmap2ddepthtexture);
522         r_shadow_shadowmap2ddepthtexture = NULL;
523
524         if (r_shadow_shadowmap2ddepthbuffer)
525                 R_FreeTexture(r_shadow_shadowmap2ddepthbuffer);
526         r_shadow_shadowmap2ddepthbuffer = NULL;
527
528         if (r_shadow_shadowmapvsdcttexture)
529                 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
530         r_shadow_shadowmapvsdcttexture = NULL;
531 }
532
533 static void r_shadow_start(void)
534 {
535         // allocate vertex processing arrays
536         r_shadow_bouncegridpixels = NULL;
537         r_shadow_bouncegridhighpixels = NULL;
538         r_shadow_bouncegridnumpixels = 0;
539         r_shadow_bouncegridtexture = NULL;
540         r_shadow_bouncegriddirectional = false;
541         r_shadow_attenuationgradienttexture = NULL;
542         r_shadow_attenuation2dtexture = NULL;
543         r_shadow_attenuation3dtexture = NULL;
544         r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
545         r_shadow_shadowmap2ddepthtexture = NULL;
546         r_shadow_shadowmap2ddepthbuffer = NULL;
547         r_shadow_shadowmapvsdcttexture = NULL;
548         r_shadow_shadowmapmaxsize = 0;
549         r_shadow_shadowmapsize = 0;
550         r_shadow_shadowmaplod = 0;
551         r_shadow_shadowmapfilterquality = -1;
552         r_shadow_shadowmapdepthbits = 0;
553         r_shadow_shadowmapvsdct = false;
554         r_shadow_shadowmapsampler = false;
555         r_shadow_shadowmappcf = 0;
556         r_shadow_fbo2d = 0;
557
558         R_Shadow_FreeShadowMaps();
559
560         r_shadow_texturepool = NULL;
561         r_shadow_filters_texturepool = NULL;
562         R_Shadow_ValidateCvars();
563         R_Shadow_MakeTextures();
564         maxshadowtriangles = 0;
565         shadowelements = NULL;
566         maxshadowvertices = 0;
567         shadowvertex3f = NULL;
568         maxvertexupdate = 0;
569         vertexupdate = NULL;
570         vertexremap = NULL;
571         vertexupdatenum = 0;
572         maxshadowmark = 0;
573         numshadowmark = 0;
574         shadowmark = NULL;
575         shadowmarklist = NULL;
576         shadowmarkcount = 0;
577         maxshadowsides = 0;
578         numshadowsides = 0;
579         shadowsides = NULL;
580         shadowsideslist = NULL;
581         r_shadow_buffer_numleafpvsbytes = 0;
582         r_shadow_buffer_visitingleafpvs = NULL;
583         r_shadow_buffer_leafpvs = NULL;
584         r_shadow_buffer_leaflist = NULL;
585         r_shadow_buffer_numsurfacepvsbytes = 0;
586         r_shadow_buffer_surfacepvs = NULL;
587         r_shadow_buffer_surfacelist = NULL;
588         r_shadow_buffer_surfacesides = NULL;
589         r_shadow_buffer_numshadowtrispvsbytes = 0;
590         r_shadow_buffer_shadowtrispvs = NULL;
591         r_shadow_buffer_numlighttrispvsbytes = 0;
592         r_shadow_buffer_lighttrispvs = NULL;
593
594         r_shadow_usingdeferredprepass = false;
595         r_shadow_prepass_width = r_shadow_prepass_height = 0;
596 }
597
598 static void R_Shadow_FreeDeferred(void);
599 static void r_shadow_shutdown(void)
600 {
601         CHECKGLERROR
602         R_Shadow_UncompileWorldLights();
603
604         R_Shadow_FreeShadowMaps();
605
606         r_shadow_usingdeferredprepass = false;
607         if (r_shadow_prepass_width)
608                 R_Shadow_FreeDeferred();
609         r_shadow_prepass_width = r_shadow_prepass_height = 0;
610
611         CHECKGLERROR
612         r_shadow_bouncegridtexture = NULL;
613         r_shadow_bouncegridpixels = NULL;
614         r_shadow_bouncegridhighpixels = NULL;
615         r_shadow_bouncegridnumpixels = 0;
616         r_shadow_bouncegriddirectional = false;
617         r_shadow_attenuationgradienttexture = NULL;
618         r_shadow_attenuation2dtexture = NULL;
619         r_shadow_attenuation3dtexture = NULL;
620         R_FreeTexturePool(&r_shadow_texturepool);
621         R_FreeTexturePool(&r_shadow_filters_texturepool);
622         maxshadowtriangles = 0;
623         if (shadowelements)
624                 Mem_Free(shadowelements);
625         shadowelements = NULL;
626         if (shadowvertex3f)
627                 Mem_Free(shadowvertex3f);
628         shadowvertex3f = NULL;
629         maxvertexupdate = 0;
630         if (vertexupdate)
631                 Mem_Free(vertexupdate);
632         vertexupdate = NULL;
633         if (vertexremap)
634                 Mem_Free(vertexremap);
635         vertexremap = NULL;
636         vertexupdatenum = 0;
637         maxshadowmark = 0;
638         numshadowmark = 0;
639         if (shadowmark)
640                 Mem_Free(shadowmark);
641         shadowmark = NULL;
642         if (shadowmarklist)
643                 Mem_Free(shadowmarklist);
644         shadowmarklist = NULL;
645         shadowmarkcount = 0;
646         maxshadowsides = 0;
647         numshadowsides = 0;
648         if (shadowsides)
649                 Mem_Free(shadowsides);
650         shadowsides = NULL;
651         if (shadowsideslist)
652                 Mem_Free(shadowsideslist);
653         shadowsideslist = NULL;
654         r_shadow_buffer_numleafpvsbytes = 0;
655         if (r_shadow_buffer_visitingleafpvs)
656                 Mem_Free(r_shadow_buffer_visitingleafpvs);
657         r_shadow_buffer_visitingleafpvs = NULL;
658         if (r_shadow_buffer_leafpvs)
659                 Mem_Free(r_shadow_buffer_leafpvs);
660         r_shadow_buffer_leafpvs = NULL;
661         if (r_shadow_buffer_leaflist)
662                 Mem_Free(r_shadow_buffer_leaflist);
663         r_shadow_buffer_leaflist = NULL;
664         r_shadow_buffer_numsurfacepvsbytes = 0;
665         if (r_shadow_buffer_surfacepvs)
666                 Mem_Free(r_shadow_buffer_surfacepvs);
667         r_shadow_buffer_surfacepvs = NULL;
668         if (r_shadow_buffer_surfacelist)
669                 Mem_Free(r_shadow_buffer_surfacelist);
670         r_shadow_buffer_surfacelist = NULL;
671         if (r_shadow_buffer_surfacesides)
672                 Mem_Free(r_shadow_buffer_surfacesides);
673         r_shadow_buffer_surfacesides = NULL;
674         r_shadow_buffer_numshadowtrispvsbytes = 0;
675         if (r_shadow_buffer_shadowtrispvs)
676                 Mem_Free(r_shadow_buffer_shadowtrispvs);
677         r_shadow_buffer_numlighttrispvsbytes = 0;
678         if (r_shadow_buffer_lighttrispvs)
679                 Mem_Free(r_shadow_buffer_lighttrispvs);
680 }
681
682 static void r_shadow_newmap(void)
683 {
684         if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
685         if (r_shadow_lightcorona)                 R_SkinFrame_MarkUsed(r_shadow_lightcorona);
686         if (r_editlights_sprcursor)               R_SkinFrame_MarkUsed(r_editlights_sprcursor);
687         if (r_editlights_sprlight)                R_SkinFrame_MarkUsed(r_editlights_sprlight);
688         if (r_editlights_sprnoshadowlight)        R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
689         if (r_editlights_sprcubemaplight)         R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
690         if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
691         if (r_editlights_sprselection)            R_SkinFrame_MarkUsed(r_editlights_sprselection);
692         if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
693                 R_Shadow_EditLights_Reload_f();
694 }
695
696 void R_Shadow_Init(void)
697 {
698         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
699         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
700         Cvar_RegisterVariable(&r_shadow_usebihculling);
701         Cvar_RegisterVariable(&r_shadow_usenormalmap);
702         Cvar_RegisterVariable(&r_shadow_debuglight);
703         Cvar_RegisterVariable(&r_shadow_deferred);
704         Cvar_RegisterVariable(&r_shadow_gloss);
705         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
706         Cvar_RegisterVariable(&r_shadow_glossintensity);
707         Cvar_RegisterVariable(&r_shadow_glossexponent);
708         Cvar_RegisterVariable(&r_shadow_gloss2exponent);
709         Cvar_RegisterVariable(&r_shadow_glossexact);
710         Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
711         Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
712         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
713         Cvar_RegisterVariable(&r_shadow_lightradiusscale);
714         Cvar_RegisterVariable(&r_shadow_projectdistance);
715         Cvar_RegisterVariable(&r_shadow_frontsidecasting);
716         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
717         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
718         Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
719         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
720         Cvar_RegisterVariable(&r_shadow_realtime_world);
721         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
722         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
723         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
724         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
725         Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
726         Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
727         Cvar_RegisterVariable(&r_shadow_scissor);
728         Cvar_RegisterVariable(&r_shadow_shadowmapping);
729         Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
730         Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
731         Cvar_RegisterVariable(&r_shadow_shadowmapping_useshadowsampler);
732         Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
733         Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
734         Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
735         Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
736 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
737 //      Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
738         Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
739         Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
740         Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
741         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
742         Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
743         Cvar_RegisterVariable(&r_shadow_sortsurfaces);
744         Cvar_RegisterVariable(&r_shadow_polygonfactor);
745         Cvar_RegisterVariable(&r_shadow_polygonoffset);
746         Cvar_RegisterVariable(&r_shadow_texture3d);
747         Cvar_RegisterVariable(&r_shadow_bouncegrid);
748         Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
749         Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
750         Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
751         Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
752         Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting);
753         Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
754         Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
755         Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
756         Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
757         Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
758         Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
759         Cvar_RegisterVariable(&r_shadow_bouncegrid_spacing);
760         Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
761         Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
762         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
763         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_lightradiusscale);
764         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_maxbounce);
765         Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
766         Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
767         Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
768         Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
769         Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
770         Cvar_RegisterVariable(&r_coronas);
771         Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
772         Cvar_RegisterVariable(&r_coronas_occlusionquery);
773         Cvar_RegisterVariable(&gl_flashblend);
774         Cvar_RegisterVariable(&gl_ext_separatestencil);
775         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
776         R_Shadow_EditLights_Init();
777         Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
778         maxshadowtriangles = 0;
779         shadowelements = NULL;
780         maxshadowvertices = 0;
781         shadowvertex3f = NULL;
782         maxvertexupdate = 0;
783         vertexupdate = NULL;
784         vertexremap = NULL;
785         vertexupdatenum = 0;
786         maxshadowmark = 0;
787         numshadowmark = 0;
788         shadowmark = NULL;
789         shadowmarklist = NULL;
790         shadowmarkcount = 0;
791         maxshadowsides = 0;
792         numshadowsides = 0;
793         shadowsides = NULL;
794         shadowsideslist = NULL;
795         r_shadow_buffer_numleafpvsbytes = 0;
796         r_shadow_buffer_visitingleafpvs = NULL;
797         r_shadow_buffer_leafpvs = NULL;
798         r_shadow_buffer_leaflist = NULL;
799         r_shadow_buffer_numsurfacepvsbytes = 0;
800         r_shadow_buffer_surfacepvs = NULL;
801         r_shadow_buffer_surfacelist = NULL;
802         r_shadow_buffer_surfacesides = NULL;
803         r_shadow_buffer_shadowtrispvs = NULL;
804         r_shadow_buffer_lighttrispvs = NULL;
805         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
806 }
807
808 matrix4x4_t matrix_attenuationxyz =
809 {
810         {
811                 {0.5, 0.0, 0.0, 0.5},
812                 {0.0, 0.5, 0.0, 0.5},
813                 {0.0, 0.0, 0.5, 0.5},
814                 {0.0, 0.0, 0.0, 1.0}
815         }
816 };
817
818 matrix4x4_t matrix_attenuationz =
819 {
820         {
821                 {0.0, 0.0, 0.5, 0.5},
822                 {0.0, 0.0, 0.0, 0.5},
823                 {0.0, 0.0, 0.0, 0.5},
824                 {0.0, 0.0, 0.0, 1.0}
825         }
826 };
827
828 static void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
829 {
830         numvertices = ((numvertices + 255) & ~255) * vertscale;
831         numtriangles = ((numtriangles + 255) & ~255) * triscale;
832         // make sure shadowelements is big enough for this volume
833         if (maxshadowtriangles < numtriangles)
834         {
835                 maxshadowtriangles = numtriangles;
836                 if (shadowelements)
837                         Mem_Free(shadowelements);
838                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
839         }
840         // make sure shadowvertex3f is big enough for this volume
841         if (maxshadowvertices < numvertices)
842         {
843                 maxshadowvertices = numvertices;
844                 if (shadowvertex3f)
845                         Mem_Free(shadowvertex3f);
846                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
847         }
848 }
849
850 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
851 {
852         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
853         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
854         int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
855         int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
856         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
857         {
858                 if (r_shadow_buffer_visitingleafpvs)
859                         Mem_Free(r_shadow_buffer_visitingleafpvs);
860                 if (r_shadow_buffer_leafpvs)
861                         Mem_Free(r_shadow_buffer_leafpvs);
862                 if (r_shadow_buffer_leaflist)
863                         Mem_Free(r_shadow_buffer_leaflist);
864                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
865                 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
866                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
867                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
868         }
869         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
870         {
871                 if (r_shadow_buffer_surfacepvs)
872                         Mem_Free(r_shadow_buffer_surfacepvs);
873                 if (r_shadow_buffer_surfacelist)
874                         Mem_Free(r_shadow_buffer_surfacelist);
875                 if (r_shadow_buffer_surfacesides)
876                         Mem_Free(r_shadow_buffer_surfacesides);
877                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
878                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
879                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
880                 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
881         }
882         if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
883         {
884                 if (r_shadow_buffer_shadowtrispvs)
885                         Mem_Free(r_shadow_buffer_shadowtrispvs);
886                 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
887                 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
888         }
889         if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
890         {
891                 if (r_shadow_buffer_lighttrispvs)
892                         Mem_Free(r_shadow_buffer_lighttrispvs);
893                 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
894                 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
895         }
896 }
897
898 void R_Shadow_PrepareShadowMark(int numtris)
899 {
900         // make sure shadowmark is big enough for this volume
901         if (maxshadowmark < numtris)
902         {
903                 maxshadowmark = numtris;
904                 if (shadowmark)
905                         Mem_Free(shadowmark);
906                 if (shadowmarklist)
907                         Mem_Free(shadowmarklist);
908                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
909                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
910                 shadowmarkcount = 0;
911         }
912         shadowmarkcount++;
913         // if shadowmarkcount wrapped we clear the array and adjust accordingly
914         if (shadowmarkcount == 0)
915         {
916                 shadowmarkcount = 1;
917                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
918         }
919         numshadowmark = 0;
920 }
921
922 void R_Shadow_PrepareShadowSides(int numtris)
923 {
924     if (maxshadowsides < numtris)
925     {
926         maxshadowsides = numtris;
927         if (shadowsides)
928                         Mem_Free(shadowsides);
929                 if (shadowsideslist)
930                         Mem_Free(shadowsideslist);
931                 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
932                 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
933         }
934         numshadowsides = 0;
935 }
936
937 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)
938 {
939         int i, j;
940         int outtriangles = 0, outvertices = 0;
941         const int *element;
942         const float *vertex;
943         float ratio, direction[3], projectvector[3];
944
945         if (projectdirection)
946                 VectorScale(projectdirection, projectdistance, projectvector);
947         else
948                 VectorClear(projectvector);
949
950         // create the vertices
951         if (projectdirection)
952         {
953                 for (i = 0;i < numshadowmarktris;i++)
954                 {
955                         element = inelement3i + shadowmarktris[i] * 3;
956                         for (j = 0;j < 3;j++)
957                         {
958                                 if (vertexupdate[element[j]] != vertexupdatenum)
959                                 {
960                                         vertexupdate[element[j]] = vertexupdatenum;
961                                         vertexremap[element[j]] = outvertices;
962                                         vertex = invertex3f + element[j] * 3;
963                                         // project one copy of the vertex according to projectvector
964                                         VectorCopy(vertex, outvertex3f);
965                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
966                                         outvertex3f += 6;
967                                         outvertices += 2;
968                                 }
969                         }
970                 }
971         }
972         else
973         {
974                 for (i = 0;i < numshadowmarktris;i++)
975                 {
976                         element = inelement3i + shadowmarktris[i] * 3;
977                         for (j = 0;j < 3;j++)
978                         {
979                                 if (vertexupdate[element[j]] != vertexupdatenum)
980                                 {
981                                         vertexupdate[element[j]] = vertexupdatenum;
982                                         vertexremap[element[j]] = outvertices;
983                                         vertex = invertex3f + element[j] * 3;
984                                         // project one copy of the vertex to the sphere radius of the light
985                                         // (FIXME: would projecting it to the light box be better?)
986                                         VectorSubtract(vertex, projectorigin, direction);
987                                         ratio = projectdistance / VectorLength(direction);
988                                         VectorCopy(vertex, outvertex3f);
989                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
990                                         outvertex3f += 6;
991                                         outvertices += 2;
992                                 }
993                         }
994                 }
995         }
996
997         if (r_shadow_frontsidecasting.integer)
998         {
999                 for (i = 0;i < numshadowmarktris;i++)
1000                 {
1001                         int remappedelement[3];
1002                         int markindex;
1003                         const int *neighbortriangle;
1004
1005                         markindex = shadowmarktris[i] * 3;
1006                         element = inelement3i + markindex;
1007                         neighbortriangle = inneighbor3i + markindex;
1008                         // output the front and back triangles
1009                         outelement3i[0] = vertexremap[element[0]];
1010                         outelement3i[1] = vertexremap[element[1]];
1011                         outelement3i[2] = vertexremap[element[2]];
1012                         outelement3i[3] = vertexremap[element[2]] + 1;
1013                         outelement3i[4] = vertexremap[element[1]] + 1;
1014                         outelement3i[5] = vertexremap[element[0]] + 1;
1015
1016                         outelement3i += 6;
1017                         outtriangles += 2;
1018                         // output the sides (facing outward from this triangle)
1019                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1020                         {
1021                                 remappedelement[0] = vertexremap[element[0]];
1022                                 remappedelement[1] = vertexremap[element[1]];
1023                                 outelement3i[0] = remappedelement[1];
1024                                 outelement3i[1] = remappedelement[0];
1025                                 outelement3i[2] = remappedelement[0] + 1;
1026                                 outelement3i[3] = remappedelement[1];
1027                                 outelement3i[4] = remappedelement[0] + 1;
1028                                 outelement3i[5] = remappedelement[1] + 1;
1029
1030                                 outelement3i += 6;
1031                                 outtriangles += 2;
1032                         }
1033                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1034                         {
1035                                 remappedelement[1] = vertexremap[element[1]];
1036                                 remappedelement[2] = vertexremap[element[2]];
1037                                 outelement3i[0] = remappedelement[2];
1038                                 outelement3i[1] = remappedelement[1];
1039                                 outelement3i[2] = remappedelement[1] + 1;
1040                                 outelement3i[3] = remappedelement[2];
1041                                 outelement3i[4] = remappedelement[1] + 1;
1042                                 outelement3i[5] = remappedelement[2] + 1;
1043
1044                                 outelement3i += 6;
1045                                 outtriangles += 2;
1046                         }
1047                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1048                         {
1049                                 remappedelement[0] = vertexremap[element[0]];
1050                                 remappedelement[2] = vertexremap[element[2]];
1051                                 outelement3i[0] = remappedelement[0];
1052                                 outelement3i[1] = remappedelement[2];
1053                                 outelement3i[2] = remappedelement[2] + 1;
1054                                 outelement3i[3] = remappedelement[0];
1055                                 outelement3i[4] = remappedelement[2] + 1;
1056                                 outelement3i[5] = remappedelement[0] + 1;
1057
1058                                 outelement3i += 6;
1059                                 outtriangles += 2;
1060                         }
1061                 }
1062         }
1063         else
1064         {
1065                 for (i = 0;i < numshadowmarktris;i++)
1066                 {
1067                         int remappedelement[3];
1068                         int markindex;
1069                         const int *neighbortriangle;
1070
1071                         markindex = shadowmarktris[i] * 3;
1072                         element = inelement3i + markindex;
1073                         neighbortriangle = inneighbor3i + markindex;
1074                         // output the front and back triangles
1075                         outelement3i[0] = vertexremap[element[2]];
1076                         outelement3i[1] = vertexremap[element[1]];
1077                         outelement3i[2] = vertexremap[element[0]];
1078                         outelement3i[3] = vertexremap[element[0]] + 1;
1079                         outelement3i[4] = vertexremap[element[1]] + 1;
1080                         outelement3i[5] = vertexremap[element[2]] + 1;
1081
1082                         outelement3i += 6;
1083                         outtriangles += 2;
1084                         // output the sides (facing outward from this triangle)
1085                         if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1086                         {
1087                                 remappedelement[0] = vertexremap[element[0]];
1088                                 remappedelement[1] = vertexremap[element[1]];
1089                                 outelement3i[0] = remappedelement[0];
1090                                 outelement3i[1] = remappedelement[1];
1091                                 outelement3i[2] = remappedelement[1] + 1;
1092                                 outelement3i[3] = remappedelement[0];
1093                                 outelement3i[4] = remappedelement[1] + 1;
1094                                 outelement3i[5] = remappedelement[0] + 1;
1095
1096                                 outelement3i += 6;
1097                                 outtriangles += 2;
1098                         }
1099                         if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1100                         {
1101                                 remappedelement[1] = vertexremap[element[1]];
1102                                 remappedelement[2] = vertexremap[element[2]];
1103                                 outelement3i[0] = remappedelement[1];
1104                                 outelement3i[1] = remappedelement[2];
1105                                 outelement3i[2] = remappedelement[2] + 1;
1106                                 outelement3i[3] = remappedelement[1];
1107                                 outelement3i[4] = remappedelement[2] + 1;
1108                                 outelement3i[5] = remappedelement[1] + 1;
1109
1110                                 outelement3i += 6;
1111                                 outtriangles += 2;
1112                         }
1113                         if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1114                         {
1115                                 remappedelement[0] = vertexremap[element[0]];
1116                                 remappedelement[2] = vertexremap[element[2]];
1117                                 outelement3i[0] = remappedelement[2];
1118                                 outelement3i[1] = remappedelement[0];
1119                                 outelement3i[2] = remappedelement[0] + 1;
1120                                 outelement3i[3] = remappedelement[2];
1121                                 outelement3i[4] = remappedelement[0] + 1;
1122                                 outelement3i[5] = remappedelement[2] + 1;
1123
1124                                 outelement3i += 6;
1125                                 outtriangles += 2;
1126                         }
1127                 }
1128         }
1129         if (outnumvertices)
1130                 *outnumvertices = outvertices;
1131         return outtriangles;
1132 }
1133
1134 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)
1135 {
1136         int i, j, k;
1137         int outtriangles = 0, outvertices = 0;
1138         const int *element;
1139         const float *vertex;
1140         float ratio, direction[3], projectvector[3];
1141         qboolean side[4];
1142
1143         if (projectdirection)
1144                 VectorScale(projectdirection, projectdistance, projectvector);
1145         else
1146                 VectorClear(projectvector);
1147
1148         for (i = 0;i < numshadowmarktris;i++)
1149         {
1150                 int remappedelement[3];
1151                 int markindex;
1152                 const int *neighbortriangle;
1153
1154                 markindex = shadowmarktris[i] * 3;
1155                 neighbortriangle = inneighbor3i + markindex;
1156                 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1157                 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1158                 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1159                 if (side[0] + side[1] + side[2] == 0)
1160                         continue;
1161
1162                 side[3] = side[0];
1163                 element = inelement3i + markindex;
1164
1165                 // create the vertices
1166                 for (j = 0;j < 3;j++)
1167                 {
1168                         if (side[j] + side[j+1] == 0)
1169                                 continue;
1170                         k = element[j];
1171                         if (vertexupdate[k] != vertexupdatenum)
1172                         {
1173                                 vertexupdate[k] = vertexupdatenum;
1174                                 vertexremap[k] = outvertices;
1175                                 vertex = invertex3f + k * 3;
1176                                 VectorCopy(vertex, outvertex3f);
1177                                 if (projectdirection)
1178                                 {
1179                                         // project one copy of the vertex according to projectvector
1180                                         VectorAdd(vertex, projectvector, (outvertex3f + 3));
1181                                 }
1182                                 else
1183                                 {
1184                                         // project one copy of the vertex to the sphere radius of the light
1185                                         // (FIXME: would projecting it to the light box be better?)
1186                                         VectorSubtract(vertex, projectorigin, direction);
1187                                         ratio = projectdistance / VectorLength(direction);
1188                                         VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1189                                 }
1190                                 outvertex3f += 6;
1191                                 outvertices += 2;
1192                         }
1193                 }
1194
1195                 // output the sides (facing outward from this triangle)
1196                 if (!side[0])
1197                 {
1198                         remappedelement[0] = vertexremap[element[0]];
1199                         remappedelement[1] = vertexremap[element[1]];
1200                         outelement3i[0] = remappedelement[1];
1201                         outelement3i[1] = remappedelement[0];
1202                         outelement3i[2] = remappedelement[0] + 1;
1203                         outelement3i[3] = remappedelement[1];
1204                         outelement3i[4] = remappedelement[0] + 1;
1205                         outelement3i[5] = remappedelement[1] + 1;
1206
1207                         outelement3i += 6;
1208                         outtriangles += 2;
1209                 }
1210                 if (!side[1])
1211                 {
1212                         remappedelement[1] = vertexremap[element[1]];
1213                         remappedelement[2] = vertexremap[element[2]];
1214                         outelement3i[0] = remappedelement[2];
1215                         outelement3i[1] = remappedelement[1];
1216                         outelement3i[2] = remappedelement[1] + 1;
1217                         outelement3i[3] = remappedelement[2];
1218                         outelement3i[4] = remappedelement[1] + 1;
1219                         outelement3i[5] = remappedelement[2] + 1;
1220
1221                         outelement3i += 6;
1222                         outtriangles += 2;
1223                 }
1224                 if (!side[2])
1225                 {
1226                         remappedelement[0] = vertexremap[element[0]];
1227                         remappedelement[2] = vertexremap[element[2]];
1228                         outelement3i[0] = remappedelement[0];
1229                         outelement3i[1] = remappedelement[2];
1230                         outelement3i[2] = remappedelement[2] + 1;
1231                         outelement3i[3] = remappedelement[0];
1232                         outelement3i[4] = remappedelement[2] + 1;
1233                         outelement3i[5] = remappedelement[0] + 1;
1234
1235                         outelement3i += 6;
1236                         outtriangles += 2;
1237                 }
1238         }
1239         if (outnumvertices)
1240                 *outnumvertices = outvertices;
1241         return outtriangles;
1242 }
1243
1244 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)
1245 {
1246         int t, tend;
1247         const int *e;
1248         const float *v[3];
1249         float normal[3];
1250         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1251                 return;
1252         tend = firsttriangle + numtris;
1253         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1254         {
1255                 // surface box entirely inside light box, no box cull
1256                 if (projectdirection)
1257                 {
1258                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1259                         {
1260                                 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1261                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1262                                         shadowmarklist[numshadowmark++] = t;
1263                         }
1264                 }
1265                 else
1266                 {
1267                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1268                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1269                                         shadowmarklist[numshadowmark++] = t;
1270                 }
1271         }
1272         else
1273         {
1274                 // surface box not entirely inside light box, cull each triangle
1275                 if (projectdirection)
1276                 {
1277                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1278                         {
1279                                 v[0] = invertex3f + e[0] * 3;
1280                                 v[1] = invertex3f + e[1] * 3;
1281                                 v[2] = invertex3f + e[2] * 3;
1282                                 TriangleNormal(v[0], v[1], v[2], normal);
1283                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1284                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1285                                         shadowmarklist[numshadowmark++] = t;
1286                         }
1287                 }
1288                 else
1289                 {
1290                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1291                         {
1292                                 v[0] = invertex3f + e[0] * 3;
1293                                 v[1] = invertex3f + e[1] * 3;
1294                                 v[2] = invertex3f + e[2] * 3;
1295                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1296                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1297                                         shadowmarklist[numshadowmark++] = t;
1298                         }
1299                 }
1300         }
1301 }
1302
1303 static qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1304 {
1305 #if 1
1306         return false;
1307 #else
1308         if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1309                 return false;
1310         // check if the shadow volume intersects the near plane
1311         //
1312         // a ray between the eye and light origin may intersect the caster,
1313         // indicating that the shadow may touch the eye location, however we must
1314         // test the near plane (a polygon), not merely the eye location, so it is
1315         // easiest to enlarge the caster bounding shape slightly for this.
1316         // TODO
1317         return true;
1318 #endif
1319 }
1320
1321 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)
1322 {
1323         int i, tris, outverts;
1324         if (projectdistance < 0.1)
1325         {
1326                 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1327                 return;
1328         }
1329         if (!numverts || !nummarktris)
1330                 return;
1331         // make sure shadowelements is big enough for this volume
1332         if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1333                 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1334
1335         if (maxvertexupdate < numverts)
1336         {
1337                 maxvertexupdate = numverts;
1338                 if (vertexupdate)
1339                         Mem_Free(vertexupdate);
1340                 if (vertexremap)
1341                         Mem_Free(vertexremap);
1342                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1343                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1344                 vertexupdatenum = 0;
1345         }
1346         vertexupdatenum++;
1347         if (vertexupdatenum == 0)
1348         {
1349                 vertexupdatenum = 1;
1350                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1351                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1352         }
1353
1354         for (i = 0;i < nummarktris;i++)
1355                 shadowmark[marktris[i]] = shadowmarkcount;
1356
1357         if (r_shadow_compilingrtlight)
1358         {
1359                 // if we're compiling an rtlight, capture the mesh
1360                 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1361                 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1362                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1363                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1364         }
1365         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1366         {
1367                 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1368                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1369                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1370         }
1371         else
1372         {
1373                 // decide which type of shadow to generate and set stencil mode
1374                 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1375                 // generate the sides or a solid volume, depending on type
1376                 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1377                         tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1378                 else
1379                         tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1380                 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1381                 r_refdef.stats.lights_shadowtriangles += tris;
1382                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1383                 {
1384                         // increment stencil if frontface is infront of depthbuffer
1385                         GL_CullFace(r_refdef.view.cullface_front);
1386                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1387                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1388                         // decrement stencil if backface is infront of depthbuffer
1389                         GL_CullFace(r_refdef.view.cullface_back);
1390                         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1391                 }
1392                 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1393                 {
1394                         // decrement stencil if backface is behind depthbuffer
1395                         GL_CullFace(r_refdef.view.cullface_front);
1396                         R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1397                         R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1398                         // increment stencil if frontface is behind depthbuffer
1399                         GL_CullFace(r_refdef.view.cullface_back);
1400                         R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1401                 }
1402                 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1403                 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1404         }
1405 }
1406
1407 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1408 {
1409     // p1, p2, p3 are in the cubemap's local coordinate system
1410     // bias = border/(size - border)
1411         int mask = 0x3F;
1412
1413     float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1414           dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1415           dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1416         if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1417         mask &= (3<<4)
1418                         | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1419                         | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1420                         | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1421     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1422         mask &= (3<<4)
1423             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1424             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))            
1425             | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1426
1427     dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1428     dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1429     dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1430     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1431         mask &= (3<<0)
1432             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1433             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))            
1434             | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1435     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1436         mask &= (3<<0)
1437             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1438             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1439             | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1440
1441     dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1442     dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1443     dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1444     if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1445         mask &= (3<<2)
1446             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1447             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1448             | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1449     if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1450         mask &= (3<<2)
1451             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1452             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1453             | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1454
1455         return mask;
1456 }
1457
1458 static int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1459 {
1460         vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1461         float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1462         int mask = 0x3F;
1463
1464         VectorSubtract(maxs, mins, radius);
1465     VectorScale(radius, 0.5f, radius);
1466     VectorAdd(mins, radius, center);
1467     Matrix4x4_Transform(worldtolight, center, lightcenter);
1468         Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1469         VectorSubtract(lightcenter, lightradius, pmin);
1470         VectorAdd(lightcenter, lightradius, pmax);
1471
1472     dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1473     dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1474     if(ap1 > bias*an1 && ap2 > bias*an2)
1475         mask &= (3<<4)
1476             | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1477             | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1478     if(an1 > bias*ap1 && an2 > bias*ap2)
1479         mask &= (3<<4)
1480             | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1481             | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1482
1483     dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1484     dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1485     if(ap1 > bias*an1 && ap2 > bias*an2)
1486         mask &= (3<<0)
1487             | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1488             | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1489     if(an1 > bias*ap1 && an2 > bias*ap2)
1490         mask &= (3<<0)
1491             | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1492             | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1493
1494     dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1495     dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1496     if(ap1 > bias*an1 && ap2 > bias*an2)
1497         mask &= (3<<2)
1498             | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1499             | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1500     if(an1 > bias*ap1 && an2 > bias*ap2)
1501         mask &= (3<<2)
1502             | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1503             | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1504
1505     return mask;
1506 }
1507
1508 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1509
1510 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1511 {
1512     // p is in the cubemap's local coordinate system
1513     // bias = border/(size - border)
1514     float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1515     float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1516     float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1517     int mask = 0x3F;
1518     if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1519     if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1520     if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1521     if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1522     if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1523     if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1524     return mask;
1525 }
1526
1527 static int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1528 {
1529         int i;
1530         vec3_t p, n;
1531         int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1532         float scale = (size - 2*border)/size, len;
1533         float bias = border / (float)(size - border), dp, dn, ap, an;
1534         // check if cone enclosing side would cross frustum plane 
1535         scale = 2 / (scale*scale + 2);
1536         for (i = 0;i < 5;i++)
1537         {
1538                 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1539                         continue;
1540                 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1541                 len = scale*VectorLength2(n);
1542                 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1543                 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1544                 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1545         }
1546         if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1547         {
1548         Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1549         len = scale*VectorLength(n);
1550                 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1551                 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1552                 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1553         }
1554         // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1555         // check if frustum corners/origin cross plane sides
1556 #if 1
1557     // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1558     Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1559     dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1560     masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1561     masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1562     dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1563     masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1564     masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1565     dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1566     masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1567     masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1568     for (i = 0;i < 4;i++)
1569     {
1570         Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1571         VectorSubtract(n, p, n);
1572         dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1573         if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1574         if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1575         dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1576         if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1577         if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1578         dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1579         if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1580         if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1581     }
1582 #else
1583     // finite version, assumes corners are a finite distance from origin dependent on far plane
1584         for (i = 0;i < 5;i++)
1585         {
1586                 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1587                 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1588                 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1589                 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1590                 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1591                 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1592                 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1593                 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1594                 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1595                 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1596         }
1597 #endif
1598         return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1599 }
1600
1601 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)
1602 {
1603         int t, tend;
1604         const int *e;
1605         const float *v[3];
1606         float normal[3];
1607         vec3_t p[3];
1608         float bias;
1609         int mask, surfacemask = 0;
1610         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1611                 return 0;
1612         bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1613         tend = firsttriangle + numtris;
1614         if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1615         {
1616                 // surface box entirely inside light box, no box cull
1617                 if (projectdirection)
1618                 {
1619                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1620                         {
1621                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1622                                 TriangleNormal(v[0], v[1], v[2], normal);
1623                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1624                                 {
1625                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1626                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1627                                         surfacemask |= mask;
1628                                         if(totals)
1629                                         {
1630                                                 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;
1631                                                 shadowsides[numshadowsides] = mask;
1632                                                 shadowsideslist[numshadowsides++] = t;
1633                                         }
1634                                 }
1635                         }
1636                 }
1637                 else
1638                 {
1639                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1640                         {
1641                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1642                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1643                                 {
1644                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1645                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1646                                         surfacemask |= mask;
1647                                         if(totals)
1648                                         {
1649                                                 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;
1650                                                 shadowsides[numshadowsides] = mask;
1651                                                 shadowsideslist[numshadowsides++] = t;
1652                                         }
1653                                 }
1654                         }
1655                 }
1656         }
1657         else
1658         {
1659                 // surface box not entirely inside light box, cull each triangle
1660                 if (projectdirection)
1661                 {
1662                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1663                         {
1664                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3,     v[2] = invertex3f + e[2] * 3;
1665                                 TriangleNormal(v[0], v[1], v[2], normal);
1666                                 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1667                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1668                                 {
1669                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1670                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1671                                         surfacemask |= mask;
1672                                         if(totals)
1673                                         {
1674                                                 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;
1675                                                 shadowsides[numshadowsides] = mask;
1676                                                 shadowsideslist[numshadowsides++] = t;
1677                                         }
1678                                 }
1679                         }
1680                 }
1681                 else
1682                 {
1683                         for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1684                         {
1685                                 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1686                                 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1687                                  && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1688                                 {
1689                                         Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1690                                         mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1691                                         surfacemask |= mask;
1692                                         if(totals)
1693                                         {
1694                                                 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;
1695                                                 shadowsides[numshadowsides] = mask;
1696                                                 shadowsideslist[numshadowsides++] = t;
1697                                         }
1698                                 }
1699                         }
1700                 }
1701         }
1702         return surfacemask;
1703 }
1704
1705 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)
1706 {
1707         int i, j, outtriangles = 0;
1708         int *outelement3i[6];
1709         if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1710                 return;
1711         outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1712         // make sure shadowelements is big enough for this mesh
1713         if (maxshadowtriangles < outtriangles)
1714                 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1715
1716         // compute the offset and size of the separate index lists for each cubemap side
1717         outtriangles = 0;
1718         for (i = 0;i < 6;i++)
1719         {
1720                 outelement3i[i] = shadowelements + outtriangles * 3;
1721                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1722                 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1723                 outtriangles += sidetotals[i];
1724         }
1725
1726         // gather up the (sparse) triangles into separate index lists for each cubemap side
1727         for (i = 0;i < numsidetris;i++)
1728         {
1729                 const int *element = elements + sidetris[i] * 3;
1730                 for (j = 0;j < 6;j++)
1731                 {
1732                         if (sides[i] & (1 << j))
1733                         {
1734                                 outelement3i[j][0] = element[0];
1735                                 outelement3i[j][1] = element[1];
1736                                 outelement3i[j][2] = element[2];
1737                                 outelement3i[j] += 3;
1738                         }
1739                 }
1740         }
1741                         
1742         Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1743 }
1744
1745 static void R_Shadow_MakeTextures_MakeCorona(void)
1746 {
1747         float dx, dy;
1748         int x, y, a;
1749         unsigned char pixels[32][32][4];
1750         for (y = 0;y < 32;y++)
1751         {
1752                 dy = (y - 15.5f) * (1.0f / 16.0f);
1753                 for (x = 0;x < 32;x++)
1754                 {
1755                         dx = (x - 15.5f) * (1.0f / 16.0f);
1756                         a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1757                         a = bound(0, a, 255);
1758                         pixels[y][x][0] = a;
1759                         pixels[y][x][1] = a;
1760                         pixels[y][x][2] = a;
1761                         pixels[y][x][3] = 255;
1762                 }
1763         }
1764         r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1765 }
1766
1767 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1768 {
1769         float dist = sqrt(x*x+y*y+z*z);
1770         float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1771         // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1772         return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1773 }
1774
1775 static void R_Shadow_MakeTextures(void)
1776 {
1777         int x, y, z;
1778         float intensity, dist;
1779         unsigned int *data;
1780         R_Shadow_FreeShadowMaps();
1781         R_FreeTexturePool(&r_shadow_texturepool);
1782         r_shadow_texturepool = R_AllocTexturePool();
1783         r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1784         r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1785         data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1786         // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1787         for (x = 0;x <= ATTENTABLESIZE;x++)
1788         {
1789                 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1790                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1791                 r_shadow_attentable[x] = bound(0, intensity, 1);
1792         }
1793         // 1D gradient texture
1794         for (x = 0;x < ATTEN1DSIZE;x++)
1795                 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1796         r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1797         // 2D circle texture
1798         for (y = 0;y < ATTEN2DSIZE;y++)
1799                 for (x = 0;x < ATTEN2DSIZE;x++)
1800                         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);
1801         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1802         // 3D sphere texture
1803         if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1804         {
1805                 for (z = 0;z < ATTEN3DSIZE;z++)
1806                         for (y = 0;y < ATTEN3DSIZE;y++)
1807                                 for (x = 0;x < ATTEN3DSIZE;x++)
1808                                         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));
1809                 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);
1810         }
1811         else
1812                 r_shadow_attenuation3dtexture = NULL;
1813         Mem_Free(data);
1814
1815         R_Shadow_MakeTextures_MakeCorona();
1816
1817         // Editor light sprites
1818         r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1819         "................"
1820         ".3............3."
1821         "..5...2332...5.."
1822         "...7.3....3.7..."
1823         "....7......7...."
1824         "...3.7....7.3..."
1825         "..2...7..7...2.."
1826         "..3..........3.."
1827         "..3..........3.."
1828         "..2...7..7...2.."
1829         "...3.7....7.3..."
1830         "....7......7...."
1831         "...7.3....3.7..."
1832         "..5...2332...5.."
1833         ".3............3."
1834         "................"
1835         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1836         r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1837         "................"
1838         "................"
1839         "......1111......"
1840         "....11233211...."
1841         "...1234554321..."
1842         "...1356776531..."
1843         "..124677776421.."
1844         "..135777777531.."
1845         "..135777777531.."
1846         "..124677776421.."
1847         "...1356776531..."
1848         "...1234554321..."
1849         "....11233211...."
1850         "......1111......"
1851         "................"
1852         "................"
1853         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1854         r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1855         "................"
1856         "................"
1857         "......1111......"
1858         "....11233211...."
1859         "...1234554321..."
1860         "...1356226531..."
1861         "..12462..26421.."
1862         "..1352....2531.."
1863         "..1352....2531.."
1864         "..12462..26421.."
1865         "...1356226531..."
1866         "...1234554321..."
1867         "....11233211...."
1868         "......1111......"
1869         "................"
1870         "................"
1871         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1872         r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1873         "................"
1874         "................"
1875         "......2772......"
1876         "....27755772...."
1877         "..277533335772.."
1878         "..753333333357.."
1879         "..777533335777.."
1880         "..735775577537.."
1881         "..733357753337.."
1882         "..733337733337.."
1883         "..753337733357.."
1884         "..277537735772.."
1885         "....27777772...."
1886         "......2772......"
1887         "................"
1888         "................"
1889         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1890         r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1891         "................"
1892         "................"
1893         "......2772......"
1894         "....27722772...."
1895         "..2772....2772.."
1896         "..72........27.."
1897         "..7772....2777.."
1898         "..7.27722772.7.."
1899         "..7...2772...7.."
1900         "..7....77....7.."
1901         "..72...77...27.."
1902         "..2772.77.2772.."
1903         "....27777772...."
1904         "......2772......"
1905         "................"
1906         "................"
1907         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1908         r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1909         "................"
1910         ".777752..257777."
1911         ".742........247."
1912         ".72..........27."
1913         ".7............7."
1914         ".5............5."
1915         ".2............2."
1916         "................"
1917         "................"
1918         ".2............2."
1919         ".5............5."
1920         ".7............7."
1921         ".72..........27."
1922         ".742........247."
1923         ".777752..257777."
1924         "................"
1925         , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1926 }
1927
1928 void R_Shadow_ValidateCvars(void)
1929 {
1930         if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1931                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1932         if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1933                 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1934         if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1935                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1936 }
1937
1938 void R_Shadow_RenderMode_Begin(void)
1939 {
1940 #if 0
1941         GLint drawbuffer;
1942         GLint readbuffer;
1943 #endif
1944         R_Shadow_ValidateCvars();
1945
1946         if (!r_shadow_attenuation2dtexture
1947          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1948          || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1949          || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1950                 R_Shadow_MakeTextures();
1951
1952         CHECKGLERROR
1953         R_Mesh_ResetTextureState();
1954         GL_BlendFunc(GL_ONE, GL_ZERO);
1955         GL_DepthRange(0, 1);
1956         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1957         GL_DepthTest(true);
1958         GL_DepthMask(false);
1959         GL_Color(0, 0, 0, 1);
1960         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1961         
1962         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1963
1964         if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1965         {
1966                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1967                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1968         }
1969         else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1970         {
1971                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1972                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1973         }
1974         else
1975         {
1976                 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1977                 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1978         }
1979
1980         switch(vid.renderpath)
1981         {
1982         case RENDERPATH_GL20:
1983         case RENDERPATH_D3D9:
1984         case RENDERPATH_D3D10:
1985         case RENDERPATH_D3D11:
1986         case RENDERPATH_SOFT:
1987         case RENDERPATH_GLES2:
1988                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1989                 break;
1990         case RENDERPATH_GL11:
1991         case RENDERPATH_GL13:
1992         case RENDERPATH_GLES1:
1993                 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
1994                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
1995                 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
1996                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
1997                 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
1998                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
1999                 else
2000                         r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2001                 break;
2002         }
2003
2004         CHECKGLERROR
2005 #if 0
2006         qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2007         qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2008         r_shadow_drawbuffer = drawbuffer;
2009         r_shadow_readbuffer = readbuffer;
2010 #endif
2011         r_shadow_cullface_front = r_refdef.view.cullface_front;
2012         r_shadow_cullface_back = r_refdef.view.cullface_back;
2013 }
2014
2015 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2016 {
2017         rsurface.rtlight = rtlight;
2018 }
2019
2020 void R_Shadow_RenderMode_Reset(void)
2021 {
2022         R_Mesh_ResetTextureState();
2023         R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL);
2024         R_SetViewport(&r_refdef.view.viewport);
2025         GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2026         GL_DepthRange(0, 1);
2027         GL_DepthTest(true);
2028         GL_DepthMask(false);
2029         GL_DepthFunc(GL_LEQUAL);
2030         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2031         r_refdef.view.cullface_front = r_shadow_cullface_front;
2032         r_refdef.view.cullface_back = r_shadow_cullface_back;
2033         GL_CullFace(r_refdef.view.cullface_back);
2034         GL_Color(1, 1, 1, 1);
2035         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2036         GL_BlendFunc(GL_ONE, GL_ZERO);
2037         R_SetupShader_Generic_NoTexture(false, false);
2038         r_shadow_usingshadowmap2d = false;
2039         r_shadow_usingshadowmaportho = false;
2040         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2041 }
2042
2043 void R_Shadow_ClearStencil(void)
2044 {
2045         GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2046         r_refdef.stats.lights_clears++;
2047 }
2048
2049 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2050 {
2051         r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2052         if (r_shadow_rendermode == mode)
2053                 return;
2054         R_Shadow_RenderMode_Reset();
2055         GL_DepthFunc(GL_LESS);
2056         GL_ColorMask(0, 0, 0, 0);
2057         GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2058         GL_CullFace(GL_NONE);
2059         R_SetupShader_DepthOrShadow(false, false);
2060         r_shadow_rendermode = mode;
2061         switch(mode)
2062         {
2063         default:
2064                 break;
2065         case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2066         case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2067                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2068                 break;
2069         case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2070         case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2071                 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2072                 break;
2073         }
2074 }
2075
2076 static void R_Shadow_MakeVSDCT(void)
2077 {
2078         // maps to a 2x3 texture rectangle with normalized coordinates
2079         // +-
2080         // XX
2081         // YY
2082         // ZZ
2083         // stores abs(dir.xy), offset.xy/2.5
2084         unsigned char data[4*6] =
2085         {
2086                 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2087                 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2088                 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2089                 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2090                 0,   0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2091                 0,   0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2092         };
2093         r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2094 }
2095
2096 static void R_Shadow_MakeShadowMap(int side, int size)
2097 {
2098         switch (r_shadow_shadowmode)
2099         {
2100         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2101                 if (r_shadow_shadowmap2ddepthtexture) return;
2102                 if (r_fb.usedepthtextures)
2103                 {
2104                         r_shadow_shadowmap2ddepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits >= 24 ? (r_shadow_shadowmapsampler ? TEXTYPE_SHADOWMAP24_COMP : TEXTYPE_SHADOWMAP24_RAW) : (r_shadow_shadowmapsampler ? TEXTYPE_SHADOWMAP16_COMP : TEXTYPE_SHADOWMAP16_RAW), false);
2105                         r_shadow_shadowmap2ddepthbuffer = NULL;
2106                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2107                 }
2108                 else
2109                 {
2110                         r_shadow_shadowmap2ddepthtexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2111                         r_shadow_shadowmap2ddepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits >= 24 ? TEXTYPE_DEPTHBUFFER24 : TEXTYPE_DEPTHBUFFER16);
2112                         r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2113                 }
2114                 break;
2115         default:
2116                 return;
2117         }
2118 }
2119
2120 static void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2121 {
2122         float nearclip, farclip, bias;
2123         r_viewport_t viewport;
2124         int flipped;
2125         GLuint fbo2d = 0;
2126         float clearcolor[4];
2127         nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2128         farclip = 1.0f;
2129         bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2130         r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2131         r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2132         r_shadow_shadowmapside = side;
2133         r_shadow_shadowmapsize = size;
2134
2135         r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2136         r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2137         R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2138         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2139
2140         // complex unrolled cube approach (more flexible)
2141         if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2142                 R_Shadow_MakeVSDCT();
2143         if (!r_shadow_shadowmap2ddepthtexture)
2144                 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2145         fbo2d = r_shadow_fbo2d;
2146         r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
2147         r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
2148         r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2149
2150         R_Mesh_ResetTextureState();
2151         R_Shadow_RenderMode_Reset();
2152         if (r_shadow_shadowmap2ddepthbuffer)
2153                 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
2154         else
2155                 R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
2156         R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL);
2157         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2158         GL_DepthMask(true);
2159         GL_DepthTest(true);
2160
2161 init_done:
2162         R_SetViewport(&viewport);
2163         flipped = (side & 1) ^ (side >> 2);
2164         r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2165         r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2166         if (r_shadow_shadowmap2ddepthbuffer)
2167         {
2168                 // completely different meaning than in depthtexture approach
2169                 r_shadow_shadowmap_parameters[1] = 0;
2170                 r_shadow_shadowmap_parameters[3] = -bias;
2171         }
2172         Vector4Set(clearcolor, 1,1,1,1);
2173         if (r_shadow_shadowmap2ddepthbuffer)
2174                 GL_ColorMask(1,1,1,1);
2175         else
2176                 GL_ColorMask(0,0,0,0);
2177         switch(vid.renderpath)
2178         {
2179         case RENDERPATH_GL11:
2180         case RENDERPATH_GL13:
2181         case RENDERPATH_GL20:
2182         case RENDERPATH_SOFT:
2183         case RENDERPATH_GLES1:
2184         case RENDERPATH_GLES2:
2185                 GL_CullFace(r_refdef.view.cullface_back);
2186                 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2187                 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2188                 {
2189                         // get tightest scissor rectangle that encloses all viewports in the clear mask
2190                         int x1 = clear & 0x15 ? 0 : size;
2191                         int x2 = clear & 0x2A ? 2 * size : size;
2192                         int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2193                         int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2194                         GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2195                         if (clear)
2196                         {
2197                                 if (r_shadow_shadowmap2ddepthbuffer)
2198                                         GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2199                                 else
2200                                         GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2201                         }
2202                 }
2203                 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2204                 break;
2205         case RENDERPATH_D3D9:
2206         case RENDERPATH_D3D10:
2207         case RENDERPATH_D3D11:
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 (clear)
2214                 {
2215                         if (r_shadow_shadowmap2ddepthbuffer)
2216                                 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2217                         else
2218                                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2219                 }
2220                 break;
2221         }
2222 }
2223
2224 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2225 {
2226         R_Mesh_ResetTextureState();
2227         if (transparent)
2228         {
2229                 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2230                 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2231                 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2232                 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2233         }
2234         R_Shadow_RenderMode_Reset();
2235         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2236         if (!transparent)
2237                 GL_DepthFunc(GL_EQUAL);
2238         // do global setup needed for the chosen lighting mode
2239         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2240                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2241         r_shadow_usingshadowmap2d = shadowmapping;
2242         r_shadow_rendermode = r_shadow_lightingrendermode;
2243         // only draw light where this geometry was already rendered AND the
2244         // stencil is 128 (values other than this mean shadow)
2245         if (stenciltest)
2246                 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2247         else
2248                 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2249 }
2250
2251 static const unsigned short bboxelements[36] =
2252 {
2253         5, 1, 3, 5, 3, 7,
2254         6, 2, 0, 6, 0, 4,
2255         7, 3, 2, 7, 2, 6,
2256         4, 0, 1, 4, 1, 5,
2257         4, 5, 7, 4, 7, 6,
2258         1, 0, 2, 1, 2, 3,
2259 };
2260
2261 static const float bboxpoints[8][3] =
2262 {
2263         {-1,-1,-1},
2264         { 1,-1,-1},
2265         {-1, 1,-1},
2266         { 1, 1,-1},
2267         {-1,-1, 1},
2268         { 1,-1, 1},
2269         {-1, 1, 1},
2270         { 1, 1, 1},
2271 };
2272
2273 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2274 {
2275         int i;
2276         float vertex3f[8*3];
2277         const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2278 // do global setup needed for the chosen lighting mode
2279         R_Shadow_RenderMode_Reset();
2280         r_shadow_rendermode = r_shadow_lightingrendermode;
2281         R_EntityMatrix(&identitymatrix);
2282         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2283         // only draw light where this geometry was already rendered AND the
2284         // stencil is 128 (values other than this mean shadow)
2285         R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2286         if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2287                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2288         else
2289                 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2290
2291         r_shadow_usingshadowmap2d = shadowmapping;
2292
2293         // render the lighting
2294         R_SetupShader_DeferredLight(rsurface.rtlight);
2295         for (i = 0;i < 8;i++)
2296                 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2297         GL_ColorMask(1,1,1,1);
2298         GL_DepthMask(false);
2299         GL_DepthRange(0, 1);
2300         GL_PolygonOffset(0, 0);
2301         GL_DepthTest(true);
2302         GL_DepthFunc(GL_GREATER);
2303         GL_CullFace(r_refdef.view.cullface_back);
2304         R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2305         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2306 }
2307
2308 void R_Shadow_UpdateBounceGridTexture(void)
2309 {
2310 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2311         dlight_t *light;
2312         int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2313         int bouncecount;
2314         int hitsupercontentsmask;
2315         int maxbounce;
2316         int numpixels;
2317         int resolution[3];
2318         int shootparticles;
2319         int shotparticles;
2320         int photoncount;
2321         int tex[3];
2322         trace_t cliptrace;
2323         //trace_t cliptrace2;
2324         //trace_t cliptrace3;
2325         unsigned char *pixel;
2326         unsigned char *pixels;
2327         float *highpixel;
2328         float *highpixels;
2329         unsigned int lightindex;
2330         unsigned int range;
2331         unsigned int range1;
2332         unsigned int range2;
2333         unsigned int seed = (unsigned int)(realtime * 1000.0f);
2334         vec3_t shotcolor;
2335         vec3_t baseshotcolor;
2336         vec3_t surfcolor;
2337         vec3_t clipend;
2338         vec3_t clipstart;
2339         vec3_t clipdiff;
2340         vec3_t ispacing;
2341         vec3_t maxs;
2342         vec3_t mins;
2343         vec3_t size;
2344         vec3_t spacing;
2345         vec3_t lightcolor;
2346         vec3_t steppos;
2347         vec3_t stepdelta;
2348         vec3_t cullmins, cullmaxs;
2349         vec_t radius;
2350         vec_t s;
2351         vec_t lightintensity;
2352         vec_t photonscaling;
2353         vec_t photonresidual;
2354         float m[16];
2355         float texlerp[2][3];
2356         float splatcolor[32];
2357         float pixelweight[8];
2358         float w;
2359         int c[4];
2360         int pixelindex[8];
2361         int corner;
2362         int pixelsperband;
2363         int pixelband;
2364         int pixelbands;
2365         int numsteps;
2366         int step;
2367         int x, y, z;
2368         rtlight_t *rtlight;
2369         r_shadow_bouncegrid_settings_t settings;
2370         qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2371         qboolean allowdirectionalshading = false;
2372         switch(vid.renderpath)
2373         {
2374         case RENDERPATH_GL20:
2375                 allowdirectionalshading = true;
2376                 if (!vid.support.ext_texture_3d)
2377                         return;
2378                 break;
2379         case RENDERPATH_GLES2:
2380                 // for performance reasons, do not use directional shading on GLES devices
2381                 if (!vid.support.ext_texture_3d)
2382                         return;
2383                 break;
2384                 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2385         case RENDERPATH_GL11:
2386         case RENDERPATH_GL13:
2387         case RENDERPATH_GLES1:
2388         case RENDERPATH_SOFT:
2389         case RENDERPATH_D3D9:
2390         case RENDERPATH_D3D10:
2391         case RENDERPATH_D3D11:
2392                 return;
2393         }
2394
2395         r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2396
2397         // see if there are really any lights to render...
2398         if (enable && r_shadow_bouncegrid_static.integer)
2399         {
2400                 enable = false;
2401                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2402                 for (lightindex = 0;lightindex < range;lightindex++)
2403                 {
2404                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2405                         if (!light || !(light->flags & flag))
2406                                 continue;
2407                         rtlight = &light->rtlight;
2408                         // when static, we skip styled lights because they tend to change...
2409                         if (rtlight->style > 0)
2410                                 continue;
2411                         VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2412                         if (!VectorLength2(lightcolor))
2413                                 continue;
2414                         enable = true;
2415                         break;
2416                 }
2417         }
2418
2419         if (!enable)
2420         {
2421                 if (r_shadow_bouncegridtexture)
2422                 {
2423                         R_FreeTexture(r_shadow_bouncegridtexture);
2424                         r_shadow_bouncegridtexture = NULL;
2425                 }
2426                 if (r_shadow_bouncegridpixels)
2427                         Mem_Free(r_shadow_bouncegridpixels);
2428                 r_shadow_bouncegridpixels = NULL;
2429                 if (r_shadow_bouncegridhighpixels)
2430                         Mem_Free(r_shadow_bouncegridhighpixels);
2431                 r_shadow_bouncegridhighpixels = NULL;
2432                 r_shadow_bouncegridnumpixels = 0;
2433                 r_shadow_bouncegriddirectional = false;
2434                 return;
2435         }
2436
2437         // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2438         memset(&settings, 0, sizeof(settings));
2439         settings.staticmode                    = r_shadow_bouncegrid_static.integer != 0;
2440         settings.bounceanglediffuse            = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2441         settings.directionalshading            = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2442         settings.dlightparticlemultiplier      = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2443         settings.hitmodels                     = r_shadow_bouncegrid_hitmodels.integer != 0;
2444         settings.includedirectlighting         = r_shadow_bouncegrid_includedirectlighting.integer != 0 || r_shadow_bouncegrid.integer == 2;
2445         settings.lightradiusscale              = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_lightradiusscale.value : r_shadow_bouncegrid_lightradiusscale.value);
2446         settings.maxbounce                     = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_maxbounce.integer : r_shadow_bouncegrid_maxbounce.integer);
2447         settings.particlebounceintensity       = r_shadow_bouncegrid_particlebounceintensity.value;
2448         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);
2449         settings.photons                       = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2450         settings.spacing[0]                    = r_shadow_bouncegrid_spacing.value;
2451         settings.spacing[1]                    = r_shadow_bouncegrid_spacing.value;
2452         settings.spacing[2]                    = r_shadow_bouncegrid_spacing.value;
2453         settings.stablerandom                  = r_shadow_bouncegrid_stablerandom.integer;
2454
2455         // bound the values for sanity
2456         settings.photons = bound(1, settings.photons, 1048576);
2457         settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2458         settings.maxbounce = bound(0, settings.maxbounce, 16);
2459         settings.spacing[0] = bound(1, settings.spacing[0], 512);
2460         settings.spacing[1] = bound(1, settings.spacing[1], 512);
2461         settings.spacing[2] = bound(1, settings.spacing[2], 512);
2462
2463         // get the spacing values
2464         spacing[0] = settings.spacing[0];
2465         spacing[1] = settings.spacing[1];
2466         spacing[2] = settings.spacing[2];
2467         ispacing[0] = 1.0f / spacing[0];
2468         ispacing[1] = 1.0f / spacing[1];
2469         ispacing[2] = 1.0f / spacing[2];
2470
2471         // calculate texture size enclosing entire world bounds at the spacing
2472         VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2473         VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2474         VectorSubtract(maxs, mins, size);
2475         // now we can calculate the resolution we want
2476         c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2477         c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2478         c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2479         // figure out the exact texture size (honoring power of 2 if required)
2480         c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2481         c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2482         c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2483         if (vid.support.arb_texture_non_power_of_two)
2484         {
2485                 resolution[0] = c[0];
2486                 resolution[1] = c[1];
2487                 resolution[2] = c[2];
2488         }
2489         else
2490         {
2491                 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2492                 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2493                 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2494         }
2495         size[0] = spacing[0] * resolution[0];
2496         size[1] = spacing[1] * resolution[1];
2497         size[2] = spacing[2] * resolution[2];
2498
2499         // if dynamic we may or may not want to use the world bounds
2500         // if the dynamic size is smaller than the world bounds, use it instead
2501         if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2502         {
2503                 // we know the resolution we want
2504                 c[0] = r_shadow_bouncegrid_x.integer;
2505                 c[1] = r_shadow_bouncegrid_y.integer;
2506                 c[2] = r_shadow_bouncegrid_z.integer;
2507                 // now we can calculate the texture size (power of 2 if required)
2508                 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2509                 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2510                 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2511                 if (vid.support.arb_texture_non_power_of_two)
2512                 {
2513                         resolution[0] = c[0];
2514                         resolution[1] = c[1];
2515                         resolution[2] = c[2];
2516                 }
2517                 else
2518                 {
2519                         for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2520                         for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2521                         for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2522                 }
2523                 size[0] = spacing[0] * resolution[0];
2524                 size[1] = spacing[1] * resolution[1];
2525                 size[2] = spacing[2] * resolution[2];
2526                 // center the rendering on the view
2527                 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2528                 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2529                 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2530         }
2531
2532         // recalculate the maxs in case the resolution was not satisfactory
2533         VectorAdd(mins, size, maxs);
2534
2535         // if all the settings seem identical to the previous update, return
2536         if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2537                 return;
2538
2539         // store the new settings
2540         r_shadow_bouncegridsettings = settings;
2541
2542         pixelbands = settings.directionalshading ? 8 : 1;
2543         pixelsperband = resolution[0]*resolution[1]*resolution[2];
2544         numpixels = pixelsperband*pixelbands;
2545
2546         // we're going to update the bouncegrid, update the matrix...
2547         memset(m, 0, sizeof(m));
2548         m[0] = 1.0f / size[0];
2549         m[3] = -mins[0] * m[0];
2550         m[5] = 1.0f / size[1];
2551         m[7] = -mins[1] * m[5];
2552         m[10] = 1.0f / size[2];
2553         m[11] = -mins[2] * m[10];
2554         m[15] = 1.0f;
2555         Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2556         // reallocate pixels for this update if needed...
2557         if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2558         {
2559                 if (r_shadow_bouncegridtexture)
2560                 {
2561                         R_FreeTexture(r_shadow_bouncegridtexture);
2562                         r_shadow_bouncegridtexture = NULL;
2563                 }
2564                 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2565                 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2566         }
2567         r_shadow_bouncegridnumpixels = numpixels;
2568         pixels = r_shadow_bouncegridpixels;
2569         highpixels = r_shadow_bouncegridhighpixels;
2570         x = pixelsperband*4;
2571         for (pixelband = 0;pixelband < pixelbands;pixelband++)
2572         {
2573                 if (pixelband == 1)
2574                         memset(pixels + pixelband * x, 128, x);
2575                 else
2576                         memset(pixels + pixelband * x, 0, x);
2577         }
2578         memset(highpixels, 0, numpixels * sizeof(float[4]));
2579         // figure out what we want to interact with
2580         if (settings.hitmodels)
2581                 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2582         else
2583                 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2584         maxbounce = settings.maxbounce;
2585         // clear variables that produce warnings otherwise
2586         memset(splatcolor, 0, sizeof(splatcolor));
2587         // iterate world rtlights
2588         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2589         range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2590         range2 = range + range1;
2591         photoncount = 0;
2592         for (lightindex = 0;lightindex < range2;lightindex++)
2593         {
2594                 if (lightindex < range)
2595                 {
2596                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2597                         if (!light)
2598                                 continue;
2599                         rtlight = &light->rtlight;
2600                         VectorClear(rtlight->photoncolor);
2601                         rtlight->photons = 0;
2602                         if (!(light->flags & flag))
2603                                 continue;
2604                         if (settings.staticmode)
2605                         {
2606                                 // when static, we skip styled lights because they tend to change...
2607                                 if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2)
2608                                         continue;
2609                         }
2610                 }
2611                 else
2612                 {
2613                         rtlight = r_refdef.scene.lights[lightindex - range];
2614                         VectorClear(rtlight->photoncolor);
2615                         rtlight->photons = 0;
2616                 }
2617                 // draw only visible lights (major speedup)
2618                 radius = rtlight->radius * settings.lightradiusscale;
2619                 cullmins[0] = rtlight->shadoworigin[0] - radius;
2620                 cullmins[1] = rtlight->shadoworigin[1] - radius;
2621                 cullmins[2] = rtlight->shadoworigin[2] - radius;
2622                 cullmaxs[0] = rtlight->shadoworigin[0] + radius;
2623                 cullmaxs[1] = rtlight->shadoworigin[1] + radius;
2624                 cullmaxs[2] = rtlight->shadoworigin[2] + radius;
2625                 if (R_CullBox(cullmins, cullmaxs))
2626                         continue;
2627                 if (r_refdef.scene.worldmodel
2628                  && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs
2629                  && !r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, cullmins, cullmaxs))
2630                         continue;
2631                 w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2632                 if (w * VectorLength2(rtlight->color) == 0.0f)
2633                         continue;
2634                 w *= (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1);
2635                 VectorScale(rtlight->color, w, rtlight->photoncolor);
2636                 //if (!VectorLength2(rtlight->photoncolor))
2637                 //      continue;
2638                 // shoot particles from this light
2639                 // use a calculation for the number of particles that will not
2640                 // vary with lightstyle, otherwise we get randomized particle
2641                 // distribution, the seeded random is only consistent for a
2642                 // consistent number of particles on this light...
2643                 s = rtlight->radius;
2644                 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2645                 if (lightindex >= range)
2646                         lightintensity *= settings.dlightparticlemultiplier;
2647                 rtlight->photons = max(0.0f, lightintensity * s * s);
2648                 photoncount += rtlight->photons;
2649         }
2650         photonscaling = (float)settings.photons / max(1, photoncount);
2651         photonresidual = 0.0f;
2652         for (lightindex = 0;lightindex < range2;lightindex++)
2653         {
2654                 if (lightindex < range)
2655                 {
2656                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2657                         if (!light)
2658                                 continue;
2659                         rtlight = &light->rtlight;
2660                 }
2661                 else
2662                         rtlight = r_refdef.scene.lights[lightindex - range];
2663                 // skip a light with no photons
2664                 if (rtlight->photons == 0.0f)
2665                         continue;
2666                 // skip a light with no photon color)
2667                 if (VectorLength2(rtlight->photoncolor) == 0.0f)
2668                         continue;
2669                 photonresidual += rtlight->photons * photonscaling;
2670                 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2671                 if (!shootparticles)
2672                         continue;
2673                 photonresidual -= shootparticles;
2674                 radius = rtlight->radius * settings.lightradiusscale;
2675                 s = settings.particleintensity / shootparticles;
2676                 VectorScale(rtlight->photoncolor, s, baseshotcolor);
2677                 r_refdef.stats.bouncegrid_lights++;
2678                 r_refdef.stats.bouncegrid_particles += shootparticles;
2679                 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2680                 {
2681                         if (settings.stablerandom > 0)
2682                                 seed = lightindex * 11937 + shotparticles;
2683                         VectorCopy(baseshotcolor, shotcolor);
2684                         VectorCopy(rtlight->shadoworigin, clipstart);
2685                         if (settings.stablerandom < 0)
2686                                 VectorRandom(clipend);
2687                         else
2688                                 VectorCheeseRandom(clipend);
2689                         VectorMA(clipstart, radius, clipend, clipend);
2690                         for (bouncecount = 0;;bouncecount++)
2691                         {
2692                                 r_refdef.stats.bouncegrid_traces++;
2693                                 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2694                                 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2695                                 if (settings.staticmode)
2696                                 {
2697                                         // static mode fires a LOT of rays but none of them are identical, so they are not cached
2698                                         cliptrace = CL_TraceLine(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), NULL, hitsupercontentsmask, true, false, NULL, true, true);
2699                                 }
2700                                 else
2701                                 {
2702                                         // dynamic mode fires many rays and most will match the cache from the previous frame
2703                                         cliptrace = CL_Cache_TraceLineSurfaces(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), hitsupercontentsmask);
2704                                 }
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 = 1024;
3175         int newelements[1024*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 static 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 static 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 static 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 static 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 static 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 static 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 static 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         rtlight->cached_numlightentities               = 0;
3925         rtlight->cached_numlightentities_noselfshadow  = 0;
3926         rtlight->cached_numshadowentities              = 0;
3927         rtlight->cached_numshadowentities_noselfshadow = 0;
3928         rtlight->cached_numsurfaces                    = 0;
3929         rtlight->cached_lightentities                  = NULL;
3930         rtlight->cached_lightentities_noselfshadow     = NULL;
3931         rtlight->cached_shadowentities                 = NULL;
3932         rtlight->cached_shadowentities_noselfshadow    = NULL;
3933         rtlight->cached_shadowtrispvs                  = NULL;
3934         rtlight->cached_lighttrispvs                   = NULL;
3935         rtlight->cached_surfacelist                    = NULL;
3936
3937         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3938         // skip lights that are basically invisible (color 0 0 0)
3939         nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3940
3941         // loading is done before visibility checks because loading should happen
3942         // all at once at the start of a level, not when it stalls gameplay.
3943         // (especially important to benchmarks)
3944         // compile light
3945         if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3946         {
3947                 if (rtlight->compiled)
3948                         R_RTLight_Uncompile(rtlight);
3949                 R_RTLight_Compile(rtlight);
3950         }
3951
3952         // load cubemap
3953         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
3954
3955         // look up the light style value at this time
3956         f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3957         VectorScale(rtlight->color, f, rtlight->currentcolor);
3958         /*
3959         if (rtlight->selected)
3960         {
3961                 f = 2 + sin(realtime * M_PI * 4.0);
3962                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
3963         }
3964         */
3965
3966         // if lightstyle is currently off, don't draw the light
3967         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
3968                 return;
3969
3970         // skip processing on corona-only lights
3971         if (nolight)
3972                 return;
3973
3974         // if the light box is offscreen, skip it
3975         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
3976                 return;
3977
3978         VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
3979         VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
3980
3981         R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
3982
3983         // don't allow lights to be drawn if using r_shadow_bouncegrid 2, except if we're using static bouncegrid where dynamic lights still need to draw
3984         if (r_shadow_bouncegrid.integer == 2 && (rtlight->isstatic || !r_shadow_bouncegrid_static.integer))
3985                 return;
3986
3987         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
3988         {
3989                 // compiled light, world available and can receive realtime lighting
3990                 // retrieve leaf information
3991                 numleafs = rtlight->static_numleafs;
3992                 leaflist = rtlight->static_leaflist;
3993                 leafpvs = rtlight->static_leafpvs;
3994                 numsurfaces = rtlight->static_numsurfaces;
3995                 surfacelist = rtlight->static_surfacelist;
3996                 //surfacesides = NULL;
3997                 shadowtrispvs = rtlight->static_shadowtrispvs;
3998                 lighttrispvs = rtlight->static_lighttrispvs;
3999         }
4000         else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4001         {
4002                 // dynamic light, world available and can receive realtime lighting
4003                 // calculate lit surfaces and leafs
4004                 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);
4005                 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4006                 leaflist = r_shadow_buffer_leaflist;
4007                 leafpvs = r_shadow_buffer_leafpvs;
4008                 surfacelist = r_shadow_buffer_surfacelist;
4009                 //surfacesides = r_shadow_buffer_surfacesides;
4010                 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4011                 lighttrispvs = r_shadow_buffer_lighttrispvs;
4012                 // if the reduced leaf bounds are offscreen, skip it
4013                 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4014                         return;
4015         }
4016         else
4017         {
4018                 // no world
4019                 numleafs = 0;
4020                 leaflist = NULL;
4021                 leafpvs = NULL;
4022                 numsurfaces = 0;
4023                 surfacelist = NULL;
4024                 //surfacesides = NULL;
4025                 shadowtrispvs = NULL;
4026                 lighttrispvs = NULL;
4027         }
4028         // check if light is illuminating any visible leafs
4029         if (numleafs)
4030         {
4031                 for (i = 0;i < numleafs;i++)
4032                         if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4033                                 break;
4034                 if (i == numleafs)
4035                         return;
4036         }
4037
4038         // make a list of lit entities and shadow casting entities
4039         numlightentities = 0;
4040         numlightentities_noselfshadow = 0;
4041         numshadowentities = 0;
4042         numshadowentities_noselfshadow = 0;
4043
4044         // add dynamic entities that are lit by the light
4045         for (i = 0;i < r_refdef.scene.numentities;i++)
4046         {
4047                 dp_model_t *model;
4048                 entity_render_t *ent = r_refdef.scene.entities[i];
4049                 vec3_t org;
4050                 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4051                         continue;
4052                 // skip the object entirely if it is not within the valid
4053                 // shadow-casting region (which includes the lit region)
4054                 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4055                         continue;
4056                 if (!(model = ent->model))
4057                         continue;
4058                 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4059                 {
4060                         // this entity wants to receive light, is visible, and is
4061                         // inside the light box
4062                         // TODO: check if the surfaces in the model can receive light
4063                         // so now check if it's in a leaf seen by the light
4064                         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))
4065                                 continue;
4066                         if (ent->flags & RENDER_NOSELFSHADOW)
4067                                 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4068                         else
4069                                 lightentities[numlightentities++] = ent;
4070                         // since it is lit, it probably also casts a shadow...
4071                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4072                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4073                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4074                         {
4075                                 // note: exterior models without the RENDER_NOSELFSHADOW
4076                                 // flag still create a RENDER_NOSELFSHADOW shadow but
4077                                 // are lit normally, this means that they are
4078                                 // self-shadowing but do not shadow other
4079                                 // RENDER_NOSELFSHADOW entities such as the gun
4080                                 // (very weird, but keeps the player shadow off the gun)
4081                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4082                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4083                                 else
4084                                         shadowentities[numshadowentities++] = ent;
4085                         }
4086                 }
4087                 else if (ent->flags & RENDER_SHADOW)
4088                 {
4089                         // this entity is not receiving light, but may still need to
4090                         // cast a shadow...
4091                         // TODO: check if the surfaces in the model can cast shadow
4092                         // now check if it is in a leaf seen by the light
4093                         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))
4094                                 continue;
4095                         // about the VectorDistance2 - light emitting entities should not cast their own shadow
4096                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4097                         if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4098                         {
4099                                 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4100                                         shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4101                                 else
4102                                         shadowentities[numshadowentities++] = ent;
4103                         }
4104                 }
4105         }
4106
4107         // return if there's nothing at all to light
4108         if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4109                 return;
4110
4111         // count this light in the r_speeds
4112         r_refdef.stats.lights++;
4113
4114         // flag it as worth drawing later
4115         rtlight->draw = true;
4116
4117         // cache all the animated entities that cast a shadow but are not visible
4118         for (i = 0;i < numshadowentities;i++)
4119                 if (!shadowentities[i]->animcache_vertex3f)
4120                         R_AnimCache_GetEntity(shadowentities[i], false, false);
4121         for (i = 0;i < numshadowentities_noselfshadow;i++)
4122                 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4123                         R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4124
4125         // allocate some temporary memory for rendering this light later in the frame
4126         // reusable buffers need to be copied, static data can be used as-is
4127         rtlight->cached_numlightentities               = numlightentities;
4128         rtlight->cached_numlightentities_noselfshadow  = numlightentities_noselfshadow;
4129         rtlight->cached_numshadowentities              = numshadowentities;
4130         rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4131         rtlight->cached_numsurfaces                    = numsurfaces;
4132         rtlight->cached_lightentities                  = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4133         rtlight->cached_lightentities_noselfshadow     = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4134         rtlight->cached_shadowentities                 = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4135         rtlight->cached_shadowentities_noselfshadow    = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4136         if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4137         {
4138                 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4139                 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4140                 rtlight->cached_shadowtrispvs                  =   (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4141                 rtlight->cached_lighttrispvs                   =   (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4142                 rtlight->cached_surfacelist                    =              (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4143         }
4144         else
4145         {
4146                 // compiled light data
4147                 rtlight->cached_shadowtrispvs = shadowtrispvs;
4148                 rtlight->cached_lighttrispvs = lighttrispvs;
4149                 rtlight->cached_surfacelist = surfacelist;
4150         }
4151 }
4152
4153 static void R_Shadow_DrawLight(rtlight_t *rtlight)
4154 {
4155         int i;
4156         int numsurfaces;
4157         unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4158         int numlightentities;
4159         int numlightentities_noselfshadow;
4160         int numshadowentities;
4161         int numshadowentities_noselfshadow;
4162         entity_render_t **lightentities;
4163         entity_render_t **lightentities_noselfshadow;
4164         entity_render_t **shadowentities;
4165         entity_render_t **shadowentities_noselfshadow;
4166         int *surfacelist;
4167         static unsigned char entitysides[MAX_EDICTS];
4168         static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4169         vec3_t nearestpoint;
4170         vec_t distance;
4171         qboolean castshadows;
4172         int lodlinear;
4173
4174         // check if we cached this light this frame (meaning it is worth drawing)
4175         if (!rtlight->draw)
4176                 return;
4177
4178         numlightentities = rtlight->cached_numlightentities;
4179         numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4180         numshadowentities = rtlight->cached_numshadowentities;
4181         numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4182         numsurfaces = rtlight->cached_numsurfaces;
4183         lightentities = rtlight->cached_lightentities;
4184         lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4185         shadowentities = rtlight->cached_shadowentities;
4186         shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4187         shadowtrispvs = rtlight->cached_shadowtrispvs;
4188         lighttrispvs = rtlight->cached_lighttrispvs;
4189         surfacelist = rtlight->cached_surfacelist;
4190
4191         // set up a scissor rectangle for this light
4192         if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4193                 return;
4194
4195         // don't let sound skip if going slow
4196         if (r_refdef.scene.extraupdate)
4197                 S_ExtraUpdate ();
4198
4199         // make this the active rtlight for rendering purposes
4200         R_Shadow_RenderMode_ActiveLight(rtlight);
4201
4202         if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4203         {
4204                 // optionally draw visible shape of the shadow volumes
4205                 // for performance analysis by level designers
4206                 R_Shadow_RenderMode_VisibleShadowVolumes();
4207                 if (numsurfaces)
4208                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4209                 for (i = 0;i < numshadowentities;i++)
4210                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4211                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4212                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4213                 R_Shadow_RenderMode_VisibleLighting(false, false);
4214         }
4215
4216         if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4217         {
4218                 // optionally draw the illuminated areas
4219                 // for performance analysis by level designers
4220                 R_Shadow_RenderMode_VisibleLighting(false, false);
4221                 if (numsurfaces)
4222                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4223                 for (i = 0;i < numlightentities;i++)
4224                         R_Shadow_DrawEntityLight(lightentities[i]);
4225                 for (i = 0;i < numlightentities_noselfshadow;i++)
4226                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4227         }
4228
4229         castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4230
4231         nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4232         nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4233         nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4234         distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4235
4236         lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4237         //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4238         lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4239
4240         if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4241         {
4242                 float borderbias;
4243                 int side;
4244                 int size;
4245                 int castermask = 0;
4246                 int receivermask = 0;
4247                 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4248                 Matrix4x4_Abs(&radiustolight);
4249
4250                 r_shadow_shadowmaplod = 0;
4251                 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4252                         if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4253                                 r_shadow_shadowmaplod = i;
4254
4255                 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4256                         
4257                 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4258
4259                 surfacesides = NULL;
4260                 if (numsurfaces)
4261                 {
4262                         if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4263                         {
4264                                 castermask = rtlight->static_shadowmap_casters;
4265                                 receivermask = rtlight->static_shadowmap_receivers;
4266                         }
4267                         else
4268                         {
4269                                 surfacesides = r_shadow_buffer_surfacesides;
4270                                 for(i = 0;i < numsurfaces;i++)
4271                                 {
4272                                         msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4273                                         surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);           
4274                                         castermask |= surfacesides[i];
4275                                         receivermask |= surfacesides[i];
4276                                 }
4277                         }
4278                 }
4279                 if (receivermask < 0x3F) 
4280                 {
4281                         for (i = 0;i < numlightentities;i++)
4282                                 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4283                         if (receivermask < 0x3F)
4284                                 for(i = 0; i < numlightentities_noselfshadow;i++)
4285                                         receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4286                 }
4287
4288                 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4289
4290                 if (receivermask)
4291                 {
4292                         for (i = 0;i < numshadowentities;i++)
4293                                 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4294                         for (i = 0;i < numshadowentities_noselfshadow;i++)
4295                                 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); 
4296                 }
4297
4298                 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4299
4300                 // render shadow casters into 6 sided depth texture
4301                 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4302                 {
4303                         R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4304                         if (! (castermask & (1 << side))) continue;
4305                         if (numsurfaces)
4306                                 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4307                         for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4308                                 R_Shadow_DrawEntityShadow(shadowentities[i]);
4309                 }
4310
4311                 if (numlightentities_noselfshadow)
4312                 {
4313                         // render lighting using the depth texture as shadowmap
4314                         // draw lighting in the unmasked areas
4315                         R_Shadow_RenderMode_Lighting(false, false, true);
4316                         for (i = 0;i < numlightentities_noselfshadow;i++)
4317                                 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4318                 }
4319
4320                 // render shadow casters into 6 sided depth texture
4321                 if (numshadowentities_noselfshadow)
4322                 {
4323                         for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4324                         {
4325                                 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4326                                 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4327                                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4328                         }
4329                 }
4330
4331                 // render lighting using the depth texture as shadowmap
4332                 // draw lighting in the unmasked areas
4333                 R_Shadow_RenderMode_Lighting(false, false, true);
4334                 // draw lighting in the unmasked areas
4335                 if (numsurfaces)
4336                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4337                 for (i = 0;i < numlightentities;i++)
4338                         R_Shadow_DrawEntityLight(lightentities[i]);
4339         }
4340         else if (castshadows && vid.stencil)
4341         {
4342                 // draw stencil shadow volumes to mask off pixels that are in shadow
4343                 // so that they won't receive lighting
4344                 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4345                 R_Shadow_ClearStencil();
4346
4347                 if (numsurfaces)
4348                         R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4349                 for (i = 0;i < numshadowentities;i++)
4350                         R_Shadow_DrawEntityShadow(shadowentities[i]);
4351
4352                 // draw lighting in the unmasked areas
4353                 R_Shadow_RenderMode_Lighting(true, false, false);
4354                 for (i = 0;i < numlightentities_noselfshadow;i++)
4355                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4356
4357                 for (i = 0;i < numshadowentities_noselfshadow;i++)
4358                         R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4359
4360                 // draw lighting in the unmasked areas
4361                 R_Shadow_RenderMode_Lighting(true, false, false);
4362                 if (numsurfaces)
4363                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4364                 for (i = 0;i < numlightentities;i++)
4365                         R_Shadow_DrawEntityLight(lightentities[i]);
4366         }
4367         else
4368         {
4369                 // draw lighting in the unmasked areas
4370                 R_Shadow_RenderMode_Lighting(false, false, false);
4371                 if (numsurfaces)
4372                         R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4373                 for (i = 0;i < numlightentities;i++)
4374                         R_Shadow_DrawEntityLight(lightentities[i]);
4375                 for (i = 0;i < numlightentities_noselfshadow;i++)
4376                         R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4377         }
4378
4379         if (r_shadow_usingdeferredprepass)
4380         {
4381                 // when rendering deferred lighting, we simply rasterize the box
4382                 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4383                         R_Shadow_RenderMode_DrawDeferredLight(false, true);
4384                 else if (castshadows && vid.stencil)
4385                         R_Shadow_RenderMode_DrawDeferredLight(true, false);
4386                 else
4387                         R_Shadow_RenderMode_DrawDeferredLight(false, false);
4388         }
4389 }
4390
4391 static void R_Shadow_FreeDeferred(void)
4392 {
4393         R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4394         r_shadow_prepassgeometryfbo = 0;
4395
4396         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4397         r_shadow_prepasslightingdiffusespecularfbo = 0;
4398
4399         R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4400         r_shadow_prepasslightingdiffusefbo = 0;
4401
4402         if (r_shadow_prepassgeometrydepthbuffer)
4403                 R_FreeTexture(r_shadow_prepassgeometrydepthbuffer);
4404         r_shadow_prepassgeometrydepthbuffer = NULL;
4405
4406         if (r_shadow_prepassgeometrynormalmaptexture)
4407                 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4408         r_shadow_prepassgeometrynormalmaptexture = NULL;
4409
4410         if (r_shadow_prepasslightingdiffusetexture)
4411                 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4412         r_shadow_prepasslightingdiffusetexture = NULL;
4413
4414         if (r_shadow_prepasslightingspeculartexture)
4415                 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4416         r_shadow_prepasslightingspeculartexture = NULL;
4417 }
4418
4419 void R_Shadow_DrawPrepass(void)
4420 {
4421         int i;
4422         int flag;
4423         int lnum;
4424         size_t lightindex;
4425         dlight_t *light;
4426         size_t range;
4427         entity_render_t *ent;
4428         float clearcolor[4];
4429
4430         R_Mesh_ResetTextureState();
4431         GL_DepthMask(true);
4432         GL_ColorMask(1,1,1,1);
4433         GL_BlendFunc(GL_ONE, GL_ZERO);
4434         GL_Color(1,1,1,1);
4435         GL_DepthTest(true);
4436         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4437         Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4438         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4439         if (r_timereport_active)
4440                 R_TimeReport("prepasscleargeom");
4441
4442         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4443                 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4444         if (r_timereport_active)
4445                 R_TimeReport("prepassworld");
4446
4447         for (i = 0;i < r_refdef.scene.numentities;i++)
4448         {
4449                 if (!r_refdef.viewcache.entityvisible[i])
4450                         continue;
4451                 ent = r_refdef.scene.entities[i];
4452                 if (ent->model && ent->model->DrawPrepass != NULL)
4453                         ent->model->DrawPrepass(ent);
4454         }
4455
4456         if (r_timereport_active)
4457                 R_TimeReport("prepassmodels");
4458
4459         GL_DepthMask(false);
4460         GL_ColorMask(1,1,1,1);
4461         GL_Color(1,1,1,1);
4462         GL_DepthTest(true);
4463         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4464         Vector4Set(clearcolor, 0, 0, 0, 0);
4465         GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4466         if (r_timereport_active)
4467                 R_TimeReport("prepassclearlit");
4468
4469         R_Shadow_RenderMode_Begin();
4470
4471         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4472         if (r_shadow_debuglight.integer >= 0)
4473         {
4474                 lightindex = r_shadow_debuglight.integer;
4475                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4476                 if (light && (light->flags & flag) && light->rtlight.draw)
4477                         R_Shadow_DrawLight(&light->rtlight);
4478         }
4479         else
4480         {
4481                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4482                 for (lightindex = 0;lightindex < range;lightindex++)
4483                 {
4484                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4485                         if (light && (light->flags & flag) && light->rtlight.draw)
4486                                 R_Shadow_DrawLight(&light->rtlight);
4487                 }
4488         }
4489         if (r_refdef.scene.rtdlight)
4490                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4491                         if (r_refdef.scene.lights[lnum]->draw)
4492                                 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4493
4494         R_Shadow_RenderMode_End();
4495
4496         if (r_timereport_active)
4497                 R_TimeReport("prepasslights");
4498 }
4499
4500 void R_Shadow_DrawLightSprites(void);
4501 void R_Shadow_PrepareLights(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4502 {
4503         int flag;
4504         int lnum;
4505         size_t lightindex;
4506         dlight_t *light;
4507         size_t range;
4508         float f;
4509
4510         if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4511                 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4512                 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) || 
4513                 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || 
4514                 r_shadow_shadowmapshadowsampler != (vid.support.arb_shadow && r_shadow_shadowmapping_useshadowsampler.integer) || 
4515                 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer || 
4516                 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
4517                 R_Shadow_FreeShadowMaps();
4518
4519         r_shadow_fb_fbo = fbo;
4520         r_shadow_fb_depthtexture = depthtexture;
4521         r_shadow_fb_colortexture = colortexture;
4522
4523         r_shadow_usingshadowmaportho = false;
4524
4525         switch (vid.renderpath)
4526         {
4527         case RENDERPATH_GL20:
4528         case RENDERPATH_D3D9:
4529         case RENDERPATH_D3D10:
4530         case RENDERPATH_D3D11:
4531         case RENDERPATH_SOFT:
4532 #ifndef USE_GLES2
4533                 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4534                 {
4535                         r_shadow_usingdeferredprepass = false;
4536                         if (r_shadow_prepass_width)
4537                                 R_Shadow_FreeDeferred();
4538                         r_shadow_prepass_width = r_shadow_prepass_height = 0;
4539                         break;
4540                 }
4541
4542                 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4543                 {
4544                         R_Shadow_FreeDeferred();
4545
4546                         r_shadow_usingdeferredprepass = true;
4547                         r_shadow_prepass_width = vid.width;
4548                         r_shadow_prepass_height = vid.height;
4549                         r_shadow_prepassgeometrydepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "prepassgeometrydepthbuffer", vid.width, vid.height, TEXTYPE_DEPTHBUFFER24);
4550                         r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4551                         r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4552                         r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4553
4554                         // set up the geometry pass fbo (depth + normalmap)
4555                         r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4556                         R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4557                         // render depth into a renderbuffer and other important properties into the normalmap texture
4558
4559                         // set up the lighting pass fbo (diffuse + specular)
4560                         r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4561                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4562                         // render diffuse into one texture and specular into another,
4563                         // with depth and normalmap bound as textures,
4564                         // with depth bound as attachment as well
4565
4566                         // set up the lighting pass fbo (diffuse)
4567                         r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4568                         R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4569                         // render diffuse into one texture,
4570                         // with depth and normalmap bound as textures,
4571                         // with depth bound as attachment as well
4572                 }
4573 #endif
4574                 break;
4575         case RENDERPATH_GL11:
4576         case RENDERPATH_GL13:
4577         case RENDERPATH_GLES1:
4578         case RENDERPATH_GLES2:
4579                 r_shadow_usingdeferredprepass = false;
4580                 break;
4581         }
4582
4583         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);
4584
4585         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4586         if (r_shadow_debuglight.integer >= 0)
4587         {
4588                 lightindex = r_shadow_debuglight.integer;
4589                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4590                 if (light)
4591                         R_Shadow_PrepareLight(&light->rtlight);
4592         }
4593         else
4594         {
4595                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4596                 for (lightindex = 0;lightindex < range;lightindex++)
4597                 {
4598                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4599                         if (light && (light->flags & flag))
4600                                 R_Shadow_PrepareLight(&light->rtlight);
4601                 }
4602         }
4603         if (r_refdef.scene.rtdlight)
4604         {
4605                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4606                         R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4607         }
4608         else if(gl_flashblend.integer)
4609         {
4610                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4611                 {
4612                         rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4613                         f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4614                         VectorScale(rtlight->color, f, rtlight->currentcolor);
4615                 }
4616         }
4617
4618         if (r_editlights.integer)
4619                 R_Shadow_DrawLightSprites();
4620 }
4621
4622 void R_Shadow_DrawLights(void)
4623 {
4624         int flag;
4625         int lnum;
4626         size_t lightindex;
4627         dlight_t *light;
4628         size_t range;
4629
4630         R_Shadow_RenderMode_Begin();
4631
4632         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4633         if (r_shadow_debuglight.integer >= 0)
4634         {
4635                 lightindex = r_shadow_debuglight.integer;
4636                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4637                 if (light)
4638                         R_Shadow_DrawLight(&light->rtlight);
4639         }
4640         else
4641         {
4642                 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4643                 for (lightindex = 0;lightindex < range;lightindex++)
4644                 {
4645                         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4646                         if (light && (light->flags & flag))
4647                                 R_Shadow_DrawLight(&light->rtlight);
4648                 }
4649         }
4650         if (r_refdef.scene.rtdlight)
4651                 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4652                         R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4653
4654         R_Shadow_RenderMode_End();
4655 }
4656
4657 void R_Shadow_PrepareModelShadows(void)
4658 {
4659         int i;
4660         float scale, size, radius, dot1, dot2;
4661         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4662         entity_render_t *ent;
4663
4664         if (!r_refdef.scene.numentities)
4665                 return;
4666
4667         switch (r_shadow_shadowmode)
4668         {
4669         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4670                 if (r_shadows.integer >= 2) 
4671                         break;
4672                 // fall through
4673         case R_SHADOW_SHADOWMODE_STENCIL:
4674                 for (i = 0;i < r_refdef.scene.numentities;i++)
4675                 {
4676                         ent = r_refdef.scene.entities[i];
4677                         if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4678                                 R_AnimCache_GetEntity(ent, false, false);
4679                 }
4680                 return;
4681         default:
4682                 return;
4683         }
4684
4685         size = 2*r_shadow_shadowmapmaxsize;
4686         scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4687         radius = 0.5f * size / scale;
4688
4689         Math_atov(r_shadows_throwdirection.string, shadowdir);
4690         VectorNormalize(shadowdir);
4691         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4692         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4693         if (fabs(dot1) <= fabs(dot2))
4694                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4695         else
4696                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4697         VectorNormalize(shadowforward);
4698         CrossProduct(shadowdir, shadowforward, shadowright);
4699         Math_atov(r_shadows_focus.string, shadowfocus);
4700         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4701         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4702         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4703         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4704         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4705                 dot1 = 1;
4706         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4707
4708         shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4709         shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4710         shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4711         shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4712         shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4713         shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4714
4715         for (i = 0;i < r_refdef.scene.numentities;i++)
4716         {
4717                 ent = r_refdef.scene.entities[i];
4718                 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4719                         continue;
4720                 // cast shadows from anything of the map (submodels are optional)
4721                 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4722                         R_AnimCache_GetEntity(ent, false, false);
4723         }
4724 }
4725
4726 void R_DrawModelShadowMaps(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4727 {
4728         int i;
4729         float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4730         entity_render_t *ent;
4731         vec3_t relativelightorigin;
4732         vec3_t relativelightdirection, relativeforward, relativeright;
4733         vec3_t relativeshadowmins, relativeshadowmaxs;
4734         vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4735         float m[12];
4736         matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4737         r_viewport_t viewport;
4738         GLuint shadowfbo = 0;
4739         float clearcolor[4];
4740
4741         if (!r_refdef.scene.numentities)
4742                 return;
4743
4744         switch (r_shadow_shadowmode)
4745         {
4746         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4747                 break;
4748         default:
4749                 return;
4750         }
4751
4752         r_shadow_fb_fbo = fbo;
4753         r_shadow_fb_depthtexture = depthtexture;
4754         r_shadow_fb_colortexture = colortexture;
4755
4756         R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4757         R_Shadow_RenderMode_Begin();
4758         R_Shadow_RenderMode_ActiveLight(NULL);
4759
4760         switch (r_shadow_shadowmode)
4761         {
4762         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4763                 if (!r_shadow_shadowmap2ddepthtexture)
4764                         R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4765                 shadowfbo = r_shadow_fbo2d;
4766                 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture);
4767                 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture);
4768                 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4769                 break;
4770         default:
4771                 break;
4772         }
4773
4774         size = 2*r_shadow_shadowmapmaxsize;
4775         scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4776         radius = 0.5f / scale;
4777         nearclip = -r_shadows_throwdistance.value;
4778         farclip = r_shadows_throwdistance.value;
4779         bias = r_shadow_shadowmapping_bias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4780
4781         r_shadow_shadowmap_parameters[0] = size;
4782         r_shadow_shadowmap_parameters[1] = size;
4783         r_shadow_shadowmap_parameters[2] = 1.0;
4784         r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4785
4786         Math_atov(r_shadows_throwdirection.string, shadowdir);
4787         VectorNormalize(shadowdir);
4788         Math_atov(r_shadows_focus.string, shadowfocus);
4789         VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4790         VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4791         VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4792         VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4793         dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4794         dot2 = DotProduct(r_refdef.view.up, shadowdir);
4795         if (fabs(dot1) <= fabs(dot2)) 
4796                 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4797         else
4798                 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4799         VectorNormalize(shadowforward);
4800         VectorM(scale, shadowforward, &m[0]);
4801         if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4802                 dot1 = 1;
4803         m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4804         CrossProduct(shadowdir, shadowforward, shadowright);
4805         VectorM(scale, shadowright, &m[4]);
4806         m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4807         VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4808         m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4809         Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4810         Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4811         R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL); 
4812
4813         VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4814
4815         if (r_shadow_shadowmap2ddepthbuffer)
4816                 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL);
4817         else
4818                 R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL);
4819         R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL);
4820         GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4821         GL_DepthMask(true);
4822         GL_DepthTest(true);
4823         R_SetViewport(&viewport);
4824         GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4825         Vector4Set(clearcolor, 1,1,1,1);
4826         // in D3D9 we have to render to a color texture shadowmap
4827         // in GL we render directly to a depth texture only
4828         if (r_shadow_shadowmap2ddepthbuffer)
4829                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4830         else
4831                 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4832         // render into a slightly restricted region so that the borders of the
4833         // shadowmap area fade away, rather than streaking across everything
4834         // outside the usable area
4835         GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4836
4837 #if 0
4838         // debugging
4839         R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL);
4840         R_SetupShader_ShowDepth(true);
4841         GL_ColorMask(1,1,1,1);
4842         GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4843 #endif
4844
4845         for (i = 0;i < r_refdef.scene.numentities;i++)
4846         {
4847                 ent = r_refdef.scene.entities[i];
4848
4849                 // cast shadows from anything of the map (submodels are optional)
4850                 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4851                 {
4852                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4853                         Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4854                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4855                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4856                         Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4857                         relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4858                         relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4859                         relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4860                         relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4861                         relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4862                         relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4863                         RSurf_ActiveModelEntity(ent, false, false, false);
4864                         ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4865                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4866                 }
4867         }
4868
4869 #if 0
4870         if (r_test.integer)
4871         {
4872                 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4873                 CHECKGLERROR
4874                 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4875                 CHECKGLERROR
4876                 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4877                 Cvar_SetValueQuick(&r_test, 0);
4878                 Z_Free(rawpixels);
4879         }
4880 #endif
4881
4882         R_Shadow_RenderMode_End();
4883
4884         Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4885         Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4886         Matrix4x4_CreateScale3(&scalematrix, size, -size, 1); 
4887         Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4888         Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4889         Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4890
4891         switch (vid.renderpath)
4892         {
4893         case RENDERPATH_GL11:
4894         case RENDERPATH_GL13:
4895         case RENDERPATH_GL20:
4896         case RENDERPATH_SOFT:
4897         case RENDERPATH_GLES1:
4898         case RENDERPATH_GLES2:
4899                 break;
4900         case RENDERPATH_D3D9:
4901         case RENDERPATH_D3D10:
4902         case RENDERPATH_D3D11:
4903 #ifdef OPENGL_ORIENTATION
4904                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4905                 r_shadow_shadowmapmatrix.m[0][1]        *= -1.0f;
4906                 r_shadow_shadowmapmatrix.m[0][2]        *= -1.0f;
4907                 r_shadow_shadowmapmatrix.m[0][3]        *= -1.0f;
4908 #else
4909                 r_shadow_shadowmapmatrix.m[0][0]        *= -1.0f;
4910                 r_shadow_shadowmapmatrix.m[1][0]        *= -1.0f;
4911                 r_shadow_shadowmapmatrix.m[2][0]        *= -1.0f;
4912                 r_shadow_shadowmapmatrix.m[3][0]        *= -1.0f;
4913 #endif
4914                 break;
4915         }
4916
4917         r_shadow_usingshadowmaportho = true;
4918         switch (r_shadow_shadowmode)
4919         {
4920         case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4921                 r_shadow_usingshadowmap2d = true;
4922                 break;
4923         default:
4924                 break;
4925         }
4926 }
4927
4928 void R_DrawModelShadows(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture)
4929 {
4930         int i;
4931         float relativethrowdistance;
4932         entity_render_t *ent;
4933         vec3_t relativelightorigin;
4934         vec3_t relativelightdirection;
4935         vec3_t relativeshadowmins, relativeshadowmaxs;
4936         vec3_t tmp, shadowdir;
4937
4938         if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
4939                 return;
4940
4941         r_shadow_fb_fbo = fbo;
4942         r_shadow_fb_depthtexture = depthtexture;
4943         r_shadow_fb_colortexture = colortexture;
4944
4945         R_ResetViewRendering3D(fbo, depthtexture, colortexture);
4946         //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
4947         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
4948         R_Shadow_RenderMode_Begin();
4949         R_Shadow_RenderMode_ActiveLight(NULL);
4950         r_shadow_lightscissor[0] = r_refdef.view.x;
4951         r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
4952         r_shadow_lightscissor[2] = r_refdef.view.width;
4953         r_shadow_lightscissor[3] = r_refdef.view.height;
4954         R_Shadow_RenderMode_StencilShadowVolumes(false);
4955
4956         // get shadow dir
4957         if (r_shadows.integer == 2)
4958         {
4959                 Math_atov(r_shadows_throwdirection.string, shadowdir);
4960                 VectorNormalize(shadowdir);
4961         }
4962
4963         R_Shadow_ClearStencil();
4964
4965         for (i = 0;i < r_refdef.scene.numentities;i++)
4966         {
4967                 ent = r_refdef.scene.entities[i];
4968
4969                 // cast shadows from anything of the map (submodels are optional)
4970                 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4971                 {
4972                         relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4973                         VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
4974                         VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
4975                         if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
4976                                 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4977                         else
4978                         {
4979                                 if(ent->entitynumber != 0)
4980                                 {
4981                                         if(ent->entitynumber >= MAX_EDICTS) // csqc entity
4982                                         {
4983                                                 // FIXME handle this
4984                                                 VectorNegate(ent->modellight_lightdir, relativelightdirection);
4985                                         }
4986                                         else
4987                                         {
4988                                                 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
4989                                                 int entnum, entnum2, recursion;
4990                                                 entnum = entnum2 = ent->entitynumber;
4991                                                 for(recursion = 32; recursion > 0; --recursion)
4992                                                 {
4993                                                         entnum2 = cl.entities[entnum].state_current.tagentity;
4994                                                         if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
4995                                                                 entnum = entnum2;
4996                                                         else
4997                                                                 break;
4998                                                 }
4999                                                 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5000                                                 {
5001                                                         VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5002                                                         // transform into modelspace of OUR entity
5003                                                         Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5004                                                         Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5005                                                 }
5006                                                 else
5007                                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5008                                         }
5009                                 }
5010                                 else
5011                                         VectorNegate(ent->modellight_lightdir, relativelightdirection);
5012                         }
5013
5014                         VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5015                         RSurf_ActiveModelEntity(ent, false, false, false);
5016                         ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5017                         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5018                 }
5019         }
5020
5021         // not really the right mode, but this will disable any silly stencil features
5022         R_Shadow_RenderMode_End();
5023
5024         // set up ortho view for rendering this pass
5025         //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5026         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5027         //GL_ScissorTest(true);
5028         //R_EntityMatrix(&identitymatrix);
5029         //R_Mesh_ResetTextureState();
5030         R_ResetViewRendering2D(fbo, depthtexture, colortexture);
5031
5032         // set up a darkening blend on shadowed areas
5033         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5034         //GL_DepthRange(0, 1);
5035         //GL_DepthTest(false);
5036         //GL_DepthMask(false);
5037         //GL_PolygonOffset(0, 0);CHECKGLERROR
5038         GL_Color(0, 0, 0, r_shadows_darken.value);
5039         //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5040         //GL_DepthFunc(GL_ALWAYS);
5041         R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5042
5043         // apply the blend to the shadowed areas
5044         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5045         R_SetupShader_Generic_NoTexture(false, true);
5046         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5047
5048         // restore the viewport
5049         R_SetViewport(&r_refdef.view.viewport);
5050
5051         // restore other state to normal
5052         //R_Shadow_RenderMode_End();
5053 }
5054
5055 static void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5056 {
5057         float zdist;
5058         vec3_t centerorigin;
5059         float vertex3f[12];
5060         // if it's too close, skip it
5061         if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5062                 return;
5063         zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5064         if (zdist < 32)
5065                 return;
5066         if (usequery && r_numqueries + 2 <= r_maxqueries)
5067         {
5068                 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5069                 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5070                 // 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
5071                 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5072
5073                 switch(vid.renderpath)
5074                 {
5075                 case RENDERPATH_GL11:
5076                 case RENDERPATH_GL13:
5077                 case RENDERPATH_GL20:
5078                 case RENDERPATH_GLES1:
5079                 case RENDERPATH_GLES2:
5080 #ifdef GL_SAMPLES_PASSED_ARB
5081                         CHECKGLERROR
5082                         // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5083                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5084                         GL_DepthFunc(GL_ALWAYS);
5085                         R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5086                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5087                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5088                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5089                         GL_DepthFunc(GL_LEQUAL);
5090                         qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5091                         R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5092                         R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5093                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5094                         qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5095                         CHECKGLERROR
5096 #endif
5097                         break;
5098                 case RENDERPATH_D3D9:
5099                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5100                         break;
5101                 case RENDERPATH_D3D10:
5102                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5103                         break;
5104                 case RENDERPATH_D3D11:
5105                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5106                         break;
5107                 case RENDERPATH_SOFT:
5108                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5109                         break;
5110                 }
5111         }
5112         rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5113 }
5114
5115 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5116
5117 static void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5118 {
5119         vec3_t color;
5120         GLint allpixels = 0, visiblepixels = 0;
5121         // now we have to check the query result
5122         if (rtlight->corona_queryindex_visiblepixels)
5123         {
5124                 switch(vid.renderpath)
5125                 {
5126                 case RENDERPATH_GL11:
5127                 case RENDERPATH_GL13:
5128                 case RENDERPATH_GL20:
5129                 case RENDERPATH_GLES1:
5130                 case RENDERPATH_GLES2:
5131 #ifdef GL_SAMPLES_PASSED_ARB
5132                         CHECKGLERROR
5133                         qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5134                         qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5135                         CHECKGLERROR
5136 #endif
5137                         break;
5138                 case RENDERPATH_D3D9:
5139                         Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5140                         break;
5141                 case RENDERPATH_D3D10:
5142                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5143                         break;
5144                 case RENDERPATH_D3D11:
5145                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5146                         break;
5147                 case RENDERPATH_SOFT:
5148                         //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5149                         break;
5150                 }
5151                 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5152                 if (visiblepixels < 1 || allpixels < 1)
5153                         return;
5154                 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5155                 cscale *= rtlight->corona_visibility;
5156         }
5157         else
5158         {
5159                 // FIXME: these traces should scan all render entities instead of cl.world
5160                 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5161                         return;
5162         }
5163         VectorScale(rtlight->currentcolor, cscale, color);
5164         if (VectorLength(color) > (1.0f / 256.0f))
5165         {
5166                 float vertex3f[12];
5167                 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5168                 if(negated)
5169                 {
5170                         VectorNegate(color, color);
5171                         GL_BlendEquationSubtract(true);
5172                 }
5173                 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5174                 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);
5175                 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5176                 if(negated)
5177                         GL_BlendEquationSubtract(false);
5178         }
5179 }
5180
5181 void R_Shadow_DrawCoronas(void)
5182 {
5183         int i, flag;
5184         qboolean usequery = false;
5185         size_t lightindex;
5186         dlight_t *light;
5187         rtlight_t *rtlight;
5188         size_t range;
5189         if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5190                 return;
5191         if (r_fb.water.renderingscene)
5192                 return;
5193         flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5194         R_EntityMatrix(&identitymatrix);
5195
5196         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5197
5198         // check occlusion of coronas
5199         // use GL_ARB_occlusion_query if available
5200         // otherwise use raytraces
5201         r_numqueries = 0;
5202         switch (vid.renderpath)
5203         {
5204         case RENDERPATH_GL11:
5205         case RENDERPATH_GL13:
5206         case RENDERPATH_GL20:
5207         case RENDERPATH_GLES1:
5208         case RENDERPATH_GLES2:
5209                 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5210 #ifdef GL_SAMPLES_PASSED_ARB
5211                 if (usequery)
5212                 {
5213                         GL_ColorMask(0,0,0,0);
5214                         if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5215                         if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5216                         {
5217                                 i = r_maxqueries;
5218                                 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5219                                 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5220                                 CHECKGLERROR
5221                                 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5222                                 CHECKGLERROR
5223                         }
5224                         RSurf_ActiveWorldEntity();
5225                         GL_BlendFunc(GL_ONE, GL_ZERO);
5226                         GL_CullFace(GL_NONE);
5227                         GL_DepthMask(false);
5228                         GL_DepthRange(0, 1);
5229                         GL_PolygonOffset(0, 0);
5230                         GL_DepthTest(true);
5231                         R_Mesh_ResetTextureState();
5232                         R_SetupShader_Generic_NoTexture(false, false);
5233                 }
5234 #endif
5235                 break;
5236         case RENDERPATH_D3D9:
5237                 usequery = false;
5238                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5239                 break;
5240         case RENDERPATH_D3D10:
5241                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5242                 break;
5243         case RENDERPATH_D3D11:
5244                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5245                 break;
5246         case RENDERPATH_SOFT:
5247                 usequery = false;
5248                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5249                 break;
5250         }
5251         for (lightindex = 0;lightindex < range;lightindex++)
5252         {
5253                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5254                 if (!light)
5255                         continue;
5256                 rtlight = &light->rtlight;
5257                 rtlight->corona_visibility = 0;
5258                 rtlight->corona_queryindex_visiblepixels = 0;
5259                 rtlight->corona_queryindex_allpixels = 0;
5260                 if (!(rtlight->flags & flag))
5261                         continue;
5262                 if (rtlight->corona <= 0)
5263                         continue;
5264                 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5265                         continue;
5266                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5267         }
5268         for (i = 0;i < r_refdef.scene.numlights;i++)
5269         {
5270                 rtlight = r_refdef.scene.lights[i];
5271                 rtlight->corona_visibility = 0;
5272                 rtlight->corona_queryindex_visiblepixels = 0;
5273                 rtlight->corona_queryindex_allpixels = 0;
5274                 if (!(rtlight->flags & flag))
5275                         continue;
5276                 if (rtlight->corona <= 0)
5277                         continue;
5278                 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5279         }
5280         if (usequery)
5281                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5282
5283         // now draw the coronas using the query data for intensity info
5284         for (lightindex = 0;lightindex < range;lightindex++)
5285         {
5286                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5287                 if (!light)
5288                         continue;
5289                 rtlight = &light->rtlight;
5290                 if (rtlight->corona_visibility <= 0)
5291                         continue;
5292                 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5293         }
5294         for (i = 0;i < r_refdef.scene.numlights;i++)
5295         {
5296                 rtlight = r_refdef.scene.lights[i];
5297                 if (rtlight->corona_visibility <= 0)
5298                         continue;
5299                 if (gl_flashblend.integer)
5300                         R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5301                 else
5302                         R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5303         }
5304 }
5305
5306
5307
5308 static dlight_t *R_Shadow_NewWorldLight(void)
5309 {
5310         return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5311 }
5312
5313 static 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)
5314 {
5315         matrix4x4_t matrix;
5316         // validate parameters
5317         if (style < 0 || style >= MAX_LIGHTSTYLES)
5318         {
5319                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5320                 style = 0;
5321         }
5322         if (!cubemapname)
5323                 cubemapname = "";
5324
5325         // copy to light properties
5326         VectorCopy(origin, light->origin);
5327         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5328         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5329         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5330         /*
5331         light->color[0] = max(color[0], 0);
5332         light->color[1] = max(color[1], 0);
5333         light->color[2] = max(color[2], 0);
5334         */
5335         light->color[0] = color[0];
5336         light->color[1] = color[1];
5337         light->color[2] = color[2];
5338         light->radius = max(radius, 0);
5339         light->style = style;
5340         light->shadow = shadowenable;
5341         light->corona = corona;
5342         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5343         light->coronasizescale = coronasizescale;
5344         light->ambientscale = ambientscale;
5345         light->diffusescale = diffusescale;
5346         light->specularscale = specularscale;
5347         light->flags = flags;
5348
5349         // update renderable light data
5350         Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5351         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);
5352 }
5353
5354 static void R_Shadow_FreeWorldLight(dlight_t *light)
5355 {
5356         if (r_shadow_selectedlight == light)
5357                 r_shadow_selectedlight = NULL;
5358         R_RTLight_Uncompile(&light->rtlight);
5359         Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5360 }
5361
5362 void R_Shadow_ClearWorldLights(void)
5363 {
5364         size_t lightindex;
5365         dlight_t *light;
5366         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5367         for (lightindex = 0;lightindex < range;lightindex++)
5368         {
5369                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5370                 if (light)
5371                         R_Shadow_FreeWorldLight(light);
5372         }
5373         r_shadow_selectedlight = NULL;
5374 }
5375
5376 static void R_Shadow_SelectLight(dlight_t *light)
5377 {
5378         if (r_shadow_selectedlight)
5379                 r_shadow_selectedlight->selected = false;
5380         r_shadow_selectedlight = light;
5381         if (r_shadow_selectedlight)
5382                 r_shadow_selectedlight->selected = true;
5383 }
5384
5385 static void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5386 {
5387         // this is never batched (there can be only one)
5388         float vertex3f[12];
5389         R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5390         RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5391         R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5392 }
5393
5394 static void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5395 {
5396         float intensity;
5397         float s;
5398         vec3_t spritecolor;
5399         skinframe_t *skinframe;
5400         float vertex3f[12];
5401
5402         // this is never batched (due to the ent parameter changing every time)
5403         // so numsurfaces == 1 and surfacelist[0] == lightnumber
5404         const dlight_t *light = (dlight_t *)ent;
5405         s = EDLIGHTSPRSIZE;
5406
5407         R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5408
5409         intensity = 0.5f;
5410         VectorScale(light->color, intensity, spritecolor);
5411         if (VectorLength(spritecolor) < 0.1732f)
5412                 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5413         if (VectorLength(spritecolor) > 1.0f)
5414                 VectorNormalize(spritecolor);
5415
5416         // draw light sprite
5417         if (light->cubemapname[0] && !light->shadow)
5418                 skinframe = r_editlights_sprcubemapnoshadowlight;
5419         else if (light->cubemapname[0])
5420                 skinframe = r_editlights_sprcubemaplight;
5421         else if (!light->shadow)
5422                 skinframe = r_editlights_sprnoshadowlight;
5423         else
5424                 skinframe = r_editlights_sprlight;
5425
5426         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);
5427         R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5428
5429         // draw selection sprite if light is selected
5430         if (light->selected)
5431         {
5432                 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5433                 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5434                 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5435         }
5436 }
5437
5438 void R_Shadow_DrawLightSprites(void)
5439 {
5440         size_t lightindex;
5441         dlight_t *light;
5442         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5443         for (lightindex = 0;lightindex < range;lightindex++)
5444         {
5445                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5446                 if (light)
5447                         R_MeshQueue_AddTransparent(MESHQUEUE_SORT_DISTANCE, light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5448         }
5449         if (!r_editlights_lockcursor)
5450                 R_MeshQueue_AddTransparent(MESHQUEUE_SORT_DISTANCE, r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5451 }
5452
5453 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5454 {
5455         unsigned int range;
5456         dlight_t *light;
5457         rtlight_t *rtlight;
5458         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5459         if (lightindex >= range)
5460                 return -1;
5461         light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5462         if (!light)
5463                 return 0;
5464         rtlight = &light->rtlight;
5465         //if (!(rtlight->flags & flag))
5466         //      return 0;
5467         VectorCopy(rtlight->shadoworigin, origin);
5468         *radius = rtlight->radius;
5469         VectorCopy(rtlight->color, color);
5470         return 1;
5471 }
5472
5473 static void R_Shadow_SelectLightInView(void)
5474 {
5475         float bestrating, rating, temp[3];
5476         dlight_t *best;
5477         size_t lightindex;
5478         dlight_t *light;
5479         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5480         best = NULL;
5481         bestrating = 0;
5482
5483         if (r_editlights_lockcursor)
5484                 return;
5485         for (lightindex = 0;lightindex < range;lightindex++)
5486         {
5487                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5488                 if (!light)
5489                         continue;
5490                 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5491                 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5492                 if (rating >= 0.95)
5493                 {
5494                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5495                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5496                         {
5497                                 bestrating = rating;
5498                                 best = light;
5499                         }
5500                 }
5501         }
5502         R_Shadow_SelectLight(best);
5503 }
5504
5505 void R_Shadow_LoadWorldLights(void)
5506 {
5507         int n, a, style, shadow, flags;
5508         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5509         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5510         if (cl.worldmodel == NULL)
5511         {
5512                 Con_Print("No map loaded.\n");
5513                 return;
5514         }
5515         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5516         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5517         if (lightsstring)
5518         {
5519                 s = lightsstring;
5520                 n = 0;
5521                 while (*s)
5522                 {
5523                         t = s;
5524                         /*
5525                         shadow = true;
5526                         for (;COM_Parse(t, true) && strcmp(
5527                         if (COM_Parse(t, true))
5528                         {
5529                                 if (com_token[0] == '!')
5530                                 {
5531                                         shadow = false;
5532                                         origin[0] = atof(com_token+1);
5533                                 }
5534                                 else
5535                                         origin[0] = atof(com_token);
5536                                 if (Com_Parse(t
5537                         }
5538                         */
5539                         t = s;
5540                         while (*s && *s != '\n' && *s != '\r')
5541                                 s++;
5542                         if (!*s)
5543                                 break;
5544                         tempchar = *s;
5545                         shadow = true;
5546                         // check for modifier flags
5547                         if (*t == '!')
5548                         {
5549                                 shadow = false;
5550                                 t++;
5551                         }
5552                         *s = 0;
5553 #if _MSC_VER >= 1400
5554 #define sscanf sscanf_s
5555 #endif
5556                         cubemapname[sizeof(cubemapname)-1] = 0;
5557 #if MAX_QPATH != 128
5558 #error update this code if MAX_QPATH changes
5559 #endif
5560                         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
5561 #if _MSC_VER >= 1400
5562 , sizeof(cubemapname)
5563 #endif
5564 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5565                         *s = tempchar;
5566                         if (a < 18)
5567                                 flags = LIGHTFLAG_REALTIMEMODE;
5568                         if (a < 17)
5569                                 specularscale = 1;
5570                         if (a < 16)
5571                                 diffusescale = 1;
5572                         if (a < 15)
5573                                 ambientscale = 0;
5574                         if (a < 14)
5575                                 coronasizescale = 0.25f;
5576                         if (a < 13)
5577                                 VectorClear(angles);
5578                         if (a < 10)
5579                                 corona = 0;
5580                         if (a < 9 || !strcmp(cubemapname, "\"\""))
5581                                 cubemapname[0] = 0;
5582                         // remove quotes on cubemapname
5583                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5584                         {
5585                                 size_t namelen;
5586                                 namelen = strlen(cubemapname) - 2;
5587                                 memmove(cubemapname, cubemapname + 1, namelen);
5588                                 cubemapname[namelen] = '\0';
5589                         }
5590                         if (a < 8)
5591                         {
5592                                 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);
5593                                 break;
5594                         }
5595                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5596                         if (*s == '\r')
5597                                 s++;
5598                         if (*s == '\n')
5599                                 s++;
5600                         n++;
5601                 }
5602                 if (*s)
5603                         Con_Printf("invalid rtlights file \"%s\"\n", name);
5604                 Mem_Free(lightsstring);
5605         }
5606 }
5607
5608 void R_Shadow_SaveWorldLights(void)
5609 {
5610         size_t lightindex;
5611         dlight_t *light;
5612         size_t bufchars, bufmaxchars;
5613         char *buf, *oldbuf;
5614         char name[MAX_QPATH];
5615         char line[MAX_INPUTLINE];
5616         size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5617         // I hate lines which are 3 times my screen size :( --blub
5618         if (!range)
5619                 return;
5620         if (cl.worldmodel == NULL)
5621         {
5622                 Con_Print("No map loaded.\n");
5623                 return;
5624         }
5625         dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5626         bufchars = bufmaxchars = 0;
5627         buf = NULL;
5628         for (lightindex = 0;lightindex < range;lightindex++)
5629         {
5630                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5631                 if (!light)
5632                         continue;
5633                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5634                         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);
5635                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5636                         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]);
5637                 else
5638                         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);
5639                 if (bufchars + strlen(line) > bufmaxchars)
5640                 {
5641                         bufmaxchars = bufchars + strlen(line) + 2048;
5642                         oldbuf = buf;
5643                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5644                         if (oldbuf)
5645                         {
5646                                 if (bufchars)
5647                                         memcpy(buf, oldbuf, bufchars);
5648                                 Mem_Free(oldbuf);
5649                         }
5650                 }
5651                 if (strlen(line))
5652                 {
5653                         memcpy(buf + bufchars, line, strlen(line));
5654                         bufchars += strlen(line);
5655                 }
5656         }
5657         if (bufchars)
5658                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5659         if (buf)
5660                 Mem_Free(buf);
5661 }
5662
5663 void R_Shadow_LoadLightsFile(void)
5664 {
5665         int n, a, style;
5666         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5667         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5668         if (cl.worldmodel == NULL)
5669         {
5670                 Con_Print("No map loaded.\n");
5671                 return;
5672         }
5673         dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5674         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5675         if (lightsstring)
5676         {
5677                 s = lightsstring;
5678                 n = 0;
5679                 while (*s)
5680                 {
5681                         t = s;
5682                         while (*s && *s != '\n' && *s != '\r')
5683                                 s++;
5684                         if (!*s)
5685                                 break;
5686                         tempchar = *s;
5687                         *s = 0;
5688                         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);
5689                         *s = tempchar;
5690                         if (a < 14)
5691                         {
5692                                 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);
5693                                 break;
5694                         }
5695                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5696                         radius = bound(15, radius, 4096);
5697                         VectorScale(color, (2.0f / (8388608.0f)), color);
5698                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5699                         if (*s == '\r')
5700                                 s++;
5701                         if (*s == '\n')
5702                                 s++;
5703                         n++;
5704                 }
5705                 if (*s)
5706                         Con_Printf("invalid lights file \"%s\"\n", name);
5707                 Mem_Free(lightsstring);
5708         }
5709 }
5710
5711 // tyrlite/hmap2 light types in the delay field
5712 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5713
5714 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5715 {
5716         int entnum;
5717         int style;
5718         int islight;
5719         int skin;
5720         int pflags;
5721         //int effects;
5722         int type;
5723         int n;
5724         char *entfiledata;
5725         const char *data;
5726         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5727         char key[256], value[MAX_INPUTLINE];
5728         char vabuf[1024];
5729
5730         if (cl.worldmodel == NULL)
5731         {
5732                 Con_Print("No map loaded.\n");
5733                 return;
5734         }
5735         // try to load a .ent file first
5736         dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5737         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5738         // and if that is not found, fall back to the bsp file entity string
5739         if (!data)
5740                 data = cl.worldmodel->brush.entities;
5741         if (!data)
5742                 return;
5743         for (entnum = 0;COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{';entnum++)
5744         {
5745                 type = LIGHTTYPE_MINUSX;
5746                 origin[0] = origin[1] = origin[2] = 0;
5747                 originhack[0] = originhack[1] = originhack[2] = 0;
5748                 angles[0] = angles[1] = angles[2] = 0;
5749                 color[0] = color[1] = color[2] = 1;
5750                 light[0] = light[1] = light[2] = 1;light[3] = 300;
5751                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5752                 fadescale = 1;
5753                 lightscale = 1;
5754                 style = 0;
5755                 skin = 0;
5756                 pflags = 0;
5757                 //effects = 0;
5758                 islight = false;
5759                 while (1)
5760                 {
5761                         if (!COM_ParseToken_Simple(&data, false, false, true))
5762                                 break; // error
5763                         if (com_token[0] == '}')
5764                                 break; // end of entity
5765                         if (com_token[0] == '_')
5766                                 strlcpy(key, com_token + 1, sizeof(key));
5767                         else
5768                                 strlcpy(key, com_token, sizeof(key));
5769                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5770                                 key[strlen(key)-1] = 0;
5771                         if (!COM_ParseToken_Simple(&data, false, false, true))
5772                                 break; // error
5773                         strlcpy(value, com_token, sizeof(value));
5774
5775                         // now that we have the key pair worked out...
5776                         if (!strcmp("light", key))
5777                         {
5778                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5779                                 if (n == 1)
5780                                 {
5781                                         // quake
5782                                         light[0] = vec[0] * (1.0f / 256.0f);
5783                                         light[1] = vec[0] * (1.0f / 256.0f);
5784                                         light[2] = vec[0] * (1.0f / 256.0f);
5785                                         light[3] = vec[0];
5786                                 }
5787                                 else if (n == 4)
5788                                 {
5789                                         // halflife
5790                                         light[0] = vec[0] * (1.0f / 255.0f);
5791                                         light[1] = vec[1] * (1.0f / 255.0f);
5792                                         light[2] = vec[2] * (1.0f / 255.0f);
5793                                         light[3] = vec[3];
5794                                 }
5795                         }
5796                         else if (!strcmp("delay", key))
5797                                 type = atoi(value);
5798                         else if (!strcmp("origin", key))
5799                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5800                         else if (!strcmp("angle", key))
5801                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5802                         else if (!strcmp("angles", key))
5803                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5804                         else if (!strcmp("color", key))
5805                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5806                         else if (!strcmp("wait", key))
5807                                 fadescale = atof(value);
5808                         else if (!strcmp("classname", key))
5809                         {
5810                                 if (!strncmp(value, "light", 5))
5811                                 {
5812                                         islight = true;
5813                                         if (!strcmp(value, "light_fluoro"))
5814                                         {
5815                                                 originhack[0] = 0;
5816                                                 originhack[1] = 0;
5817                                                 originhack[2] = 0;
5818                                                 overridecolor[0] = 1;
5819                                                 overridecolor[1] = 1;
5820                                                 overridecolor[2] = 1;
5821                                         }
5822                                         if (!strcmp(value, "light_fluorospark"))
5823                                         {
5824                                                 originhack[0] = 0;
5825                                                 originhack[1] = 0;
5826                                                 originhack[2] = 0;
5827                                                 overridecolor[0] = 1;
5828                                                 overridecolor[1] = 1;
5829                                                 overridecolor[2] = 1;
5830                                         }
5831                                         if (!strcmp(value, "light_globe"))
5832                                         {
5833                                                 originhack[0] = 0;
5834                                                 originhack[1] = 0;
5835                                                 originhack[2] = 0;
5836                                                 overridecolor[0] = 1;
5837                                                 overridecolor[1] = 0.8;
5838                                                 overridecolor[2] = 0.4;
5839                                         }
5840                                         if (!strcmp(value, "light_flame_large_yellow"))
5841                                         {
5842                                                 originhack[0] = 0;
5843                                                 originhack[1] = 0;
5844                                                 originhack[2] = 0;
5845                                                 overridecolor[0] = 1;
5846                                                 overridecolor[1] = 0.5;
5847                                                 overridecolor[2] = 0.1;
5848                                         }
5849                                         if (!strcmp(value, "light_flame_small_yellow"))
5850                                         {
5851                                                 originhack[0] = 0;
5852                                                 originhack[1] = 0;
5853                                                 originhack[2] = 0;
5854                                                 overridecolor[0] = 1;
5855                                                 overridecolor[1] = 0.5;
5856                                                 overridecolor[2] = 0.1;
5857                                         }
5858                                         if (!strcmp(value, "light_torch_small_white"))
5859                                         {
5860                                                 originhack[0] = 0;
5861                                                 originhack[1] = 0;
5862                                                 originhack[2] = 0;
5863                                                 overridecolor[0] = 1;
5864                                                 overridecolor[1] = 0.5;
5865                                                 overridecolor[2] = 0.1;
5866                                         }
5867                                         if (!strcmp(value, "light_torch_small_walltorch"))
5868                                         {
5869                                                 originhack[0] = 0;
5870                                                 originhack[1] = 0;
5871                                                 originhack[2] = 0;
5872                                                 overridecolor[0] = 1;
5873                                                 overridecolor[1] = 0.5;
5874                                                 overridecolor[2] = 0.1;
5875                                         }
5876                                 }
5877                         }
5878                         else if (!strcmp("style", key))
5879                                 style = atoi(value);
5880                         else if (!strcmp("skin", key))
5881                                 skin = (int)atof(value);
5882                         else if (!strcmp("pflags", key))
5883                                 pflags = (int)atof(value);
5884                         //else if (!strcmp("effects", key))
5885                         //      effects = (int)atof(value);
5886                         else if (cl.worldmodel->type == mod_brushq3)
5887                         {
5888                                 if (!strcmp("scale", key))
5889                                         lightscale = atof(value);
5890                                 if (!strcmp("fade", key))
5891                                         fadescale = atof(value);
5892                         }
5893                 }
5894                 if (!islight)
5895                         continue;
5896                 if (lightscale <= 0)
5897                         lightscale = 1;
5898                 if (fadescale <= 0)
5899                         fadescale = 1;
5900                 if (color[0] == color[1] && color[0] == color[2])
5901                 {
5902                         color[0] *= overridecolor[0];
5903                         color[1] *= overridecolor[1];
5904                         color[2] *= overridecolor[2];
5905                 }
5906                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
5907                 color[0] = color[0] * light[0];
5908                 color[1] = color[1] * light[1];
5909                 color[2] = color[2] * light[2];
5910                 switch (type)
5911                 {
5912                 case LIGHTTYPE_MINUSX:
5913                         break;
5914                 case LIGHTTYPE_RECIPX:
5915                         radius *= 2;
5916                         VectorScale(color, (1.0f / 16.0f), color);
5917                         break;
5918                 case LIGHTTYPE_RECIPXX:
5919                         radius *= 2;
5920                         VectorScale(color, (1.0f / 16.0f), color);
5921                         break;
5922                 default:
5923                 case LIGHTTYPE_NONE:
5924                         break;
5925                 case LIGHTTYPE_SUN:
5926                         break;
5927                 case LIGHTTYPE_MINUSXX:
5928                         break;
5929                 }
5930                 VectorAdd(origin, originhack, origin);
5931                 if (radius >= 1)
5932                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va(vabuf, sizeof(vabuf), "cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5933         }
5934         if (entfiledata)
5935                 Mem_Free(entfiledata);
5936 }
5937
5938
5939 static void R_Shadow_SetCursorLocationForView(void)
5940 {
5941         vec_t dist, push;
5942         vec3_t dest, endpos;
5943         trace_t trace;
5944         VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
5945         trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
5946         if (trace.fraction < 1)
5947         {
5948                 dist = trace.fraction * r_editlights_cursordistance.value;
5949                 push = r_editlights_cursorpushback.value;
5950                 if (push > dist)
5951                         push = dist;
5952                 push = -push;
5953                 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
5954                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
5955         }
5956         else
5957         {
5958                 VectorClear( endpos );
5959         }
5960         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5961         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5962         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
5963 }
5964
5965 void R_Shadow_UpdateWorldLightSelection(void)
5966 {
5967         if (r_editlights.integer)
5968         {
5969                 R_Shadow_SetCursorLocationForView();
5970                 R_Shadow_SelectLightInView();
5971         }
5972         else
5973                 R_Shadow_SelectLight(NULL);
5974 }
5975
5976 static void R_Shadow_EditLights_Clear_f(void)
5977 {
5978         R_Shadow_ClearWorldLights();
5979 }
5980
5981 void R_Shadow_EditLights_Reload_f(void)
5982 {
5983         if (!cl.worldmodel)
5984                 return;
5985         strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
5986         R_Shadow_ClearWorldLights();
5987         R_Shadow_LoadWorldLights();
5988         if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
5989         {
5990                 R_Shadow_LoadLightsFile();
5991                 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
5992                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
5993         }
5994 }
5995
5996 static void R_Shadow_EditLights_Save_f(void)
5997 {
5998         if (!cl.worldmodel)
5999                 return;
6000         R_Shadow_SaveWorldLights();
6001 }
6002
6003 static void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6004 {
6005         R_Shadow_ClearWorldLights();
6006         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6007 }
6008
6009 static void R_Shadow_EditLights_ImportLightsFile_f(void)
6010 {
6011         R_Shadow_ClearWorldLights();
6012         R_Shadow_LoadLightsFile();
6013 }
6014
6015 static void R_Shadow_EditLights_Spawn_f(void)
6016 {
6017         vec3_t color;
6018         if (!r_editlights.integer)
6019         {
6020                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6021                 return;
6022         }
6023         if (Cmd_Argc() != 1)
6024         {
6025                 Con_Print("r_editlights_spawn does not take parameters\n");
6026                 return;
6027         }
6028         color[0] = color[1] = color[2] = 1;
6029         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6030 }
6031
6032 static void R_Shadow_EditLights_Edit_f(void)
6033 {
6034         vec3_t origin, angles, color;
6035         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6036         int style, shadows, flags, normalmode, realtimemode;
6037         char cubemapname[MAX_INPUTLINE];
6038         if (!r_editlights.integer)
6039         {
6040                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6041                 return;
6042         }
6043         if (!r_shadow_selectedlight)
6044         {
6045                 Con_Print("No selected light.\n");
6046                 return;
6047         }
6048         VectorCopy(r_shadow_selectedlight->origin, origin);
6049         VectorCopy(r_shadow_selectedlight->angles, angles);
6050         VectorCopy(r_shadow_selectedlight->color, color);
6051         radius = r_shadow_selectedlight->radius;
6052         style = r_shadow_selectedlight->style;
6053         if (r_shadow_selectedlight->cubemapname)
6054                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6055         else
6056                 cubemapname[0] = 0;
6057         shadows = r_shadow_selectedlight->shadow;
6058         corona = r_shadow_selectedlight->corona;
6059         coronasizescale = r_shadow_selectedlight->coronasizescale;
6060         ambientscale = r_shadow_selectedlight->ambientscale;
6061         diffusescale = r_shadow_selectedlight->diffusescale;
6062         specularscale = r_shadow_selectedlight->specularscale;
6063         flags = r_shadow_selectedlight->flags;
6064         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6065         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6066         if (!strcmp(Cmd_Argv(1), "origin"))
6067         {
6068                 if (Cmd_Argc() != 5)
6069                 {
6070                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6071                         return;
6072                 }
6073                 origin[0] = atof(Cmd_Argv(2));
6074                 origin[1] = atof(Cmd_Argv(3));
6075                 origin[2] = atof(Cmd_Argv(4));
6076         }
6077         else if (!strcmp(Cmd_Argv(1), "originscale"))
6078         {
6079                 if (Cmd_Argc() != 5)
6080                 {
6081                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6082                         return;
6083                 }
6084                 origin[0] *= atof(Cmd_Argv(2));
6085                 origin[1] *= atof(Cmd_Argv(3));
6086                 origin[2] *= atof(Cmd_Argv(4));
6087         }
6088         else if (!strcmp(Cmd_Argv(1), "originx"))
6089         {
6090                 if (Cmd_Argc() != 3)
6091                 {
6092                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6093                         return;
6094                 }
6095                 origin[0] = atof(Cmd_Argv(2));
6096         }
6097         else if (!strcmp(Cmd_Argv(1), "originy"))
6098         {
6099                 if (Cmd_Argc() != 3)
6100                 {
6101                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6102                         return;
6103                 }
6104                 origin[1] = atof(Cmd_Argv(2));
6105         }
6106         else if (!strcmp(Cmd_Argv(1), "originz"))
6107         {
6108                 if (Cmd_Argc() != 3)
6109                 {
6110                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6111                         return;
6112                 }
6113                 origin[2] = atof(Cmd_Argv(2));
6114         }
6115         else if (!strcmp(Cmd_Argv(1), "move"))
6116         {
6117                 if (Cmd_Argc() != 5)
6118                 {
6119                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6120                         return;
6121                 }
6122                 origin[0] += atof(Cmd_Argv(2));
6123                 origin[1] += atof(Cmd_Argv(3));
6124                 origin[2] += atof(Cmd_Argv(4));
6125         }
6126         else if (!strcmp(Cmd_Argv(1), "movex"))
6127         {
6128                 if (Cmd_Argc() != 3)
6129                 {
6130                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6131                         return;
6132                 }
6133                 origin[0] += atof(Cmd_Argv(2));
6134         }
6135         else if (!strcmp(Cmd_Argv(1), "movey"))
6136         {
6137                 if (Cmd_Argc() != 3)
6138                 {
6139                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6140                         return;
6141                 }
6142                 origin[1] += atof(Cmd_Argv(2));
6143         }
6144         else if (!strcmp(Cmd_Argv(1), "movez"))
6145         {
6146                 if (Cmd_Argc() != 3)
6147                 {
6148                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6149                         return;
6150                 }
6151                 origin[2] += atof(Cmd_Argv(2));
6152         }
6153         else if (!strcmp(Cmd_Argv(1), "angles"))
6154         {
6155                 if (Cmd_Argc() != 5)
6156                 {
6157                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6158                         return;
6159                 }
6160                 angles[0] = atof(Cmd_Argv(2));
6161                 angles[1] = atof(Cmd_Argv(3));
6162                 angles[2] = atof(Cmd_Argv(4));
6163         }
6164         else if (!strcmp(Cmd_Argv(1), "anglesx"))
6165         {
6166                 if (Cmd_Argc() != 3)
6167                 {
6168                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6169                         return;
6170                 }
6171                 angles[0] = atof(Cmd_Argv(2));
6172         }
6173         else if (!strcmp(Cmd_Argv(1), "anglesy"))
6174         {
6175                 if (Cmd_Argc() != 3)
6176                 {
6177                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6178                         return;
6179                 }
6180                 angles[1] = atof(Cmd_Argv(2));
6181         }
6182         else if (!strcmp(Cmd_Argv(1), "anglesz"))
6183         {
6184                 if (Cmd_Argc() != 3)
6185                 {
6186                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6187                         return;
6188                 }
6189                 angles[2] = atof(Cmd_Argv(2));
6190         }
6191         else if (!strcmp(Cmd_Argv(1), "color"))
6192         {
6193                 if (Cmd_Argc() != 5)
6194                 {
6195                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6196                         return;
6197                 }
6198                 color[0] = atof(Cmd_Argv(2));
6199                 color[1] = atof(Cmd_Argv(3));
6200                 color[2] = atof(Cmd_Argv(4));
6201         }
6202         else if (!strcmp(Cmd_Argv(1), "radius"))
6203         {
6204                 if (Cmd_Argc() != 3)
6205                 {
6206                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6207                         return;
6208                 }
6209                 radius = atof(Cmd_Argv(2));
6210         }
6211         else if (!strcmp(Cmd_Argv(1), "colorscale"))
6212         {
6213                 if (Cmd_Argc() == 3)
6214                 {
6215                         double scale = atof(Cmd_Argv(2));
6216                         color[0] *= scale;
6217                         color[1] *= scale;
6218                         color[2] *= scale;
6219                 }
6220                 else
6221                 {
6222                         if (Cmd_Argc() != 5)
6223                         {
6224                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
6225                                 return;
6226                         }
6227                         color[0] *= atof(Cmd_Argv(2));
6228                         color[1] *= atof(Cmd_Argv(3));
6229                         color[2] *= atof(Cmd_Argv(4));
6230                 }
6231         }
6232         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6233         {
6234                 if (Cmd_Argc() != 3)
6235                 {
6236                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6237                         return;
6238                 }
6239                 radius *= atof(Cmd_Argv(2));
6240         }
6241         else if (!strcmp(Cmd_Argv(1), "style"))
6242         {
6243                 if (Cmd_Argc() != 3)
6244                 {
6245                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6246                         return;
6247                 }
6248                 style = atoi(Cmd_Argv(2));
6249         }
6250         else if (!strcmp(Cmd_Argv(1), "cubemap"))
6251         {
6252                 if (Cmd_Argc() > 3)
6253                 {
6254                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6255                         return;
6256                 }
6257                 if (Cmd_Argc() == 3)
6258                         strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6259                 else
6260                         cubemapname[0] = 0;
6261         }
6262         else if (!strcmp(Cmd_Argv(1), "shadows"))
6263         {
6264                 if (Cmd_Argc() != 3)
6265                 {
6266                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6267                         return;
6268                 }
6269                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6270         }
6271         else if (!strcmp(Cmd_Argv(1), "corona"))
6272         {
6273                 if (Cmd_Argc() != 3)
6274                 {
6275                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6276                         return;
6277                 }
6278                 corona = atof(Cmd_Argv(2));
6279         }
6280         else if (!strcmp(Cmd_Argv(1), "coronasize"))
6281         {
6282                 if (Cmd_Argc() != 3)
6283                 {
6284                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6285                         return;
6286                 }
6287                 coronasizescale = atof(Cmd_Argv(2));
6288         }
6289         else if (!strcmp(Cmd_Argv(1), "ambient"))
6290         {
6291                 if (Cmd_Argc() != 3)
6292                 {
6293                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6294                         return;
6295                 }
6296                 ambientscale = atof(Cmd_Argv(2));
6297         }
6298         else if (!strcmp(Cmd_Argv(1), "diffuse"))
6299         {
6300                 if (Cmd_Argc() != 3)
6301                 {
6302                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6303                         return;
6304                 }
6305                 diffusescale = atof(Cmd_Argv(2));
6306         }
6307         else if (!strcmp(Cmd_Argv(1), "specular"))
6308         {
6309                 if (Cmd_Argc() != 3)
6310                 {
6311                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6312                         return;
6313                 }
6314                 specularscale = atof(Cmd_Argv(2));
6315         }
6316         else if (!strcmp(Cmd_Argv(1), "normalmode"))
6317         {
6318                 if (Cmd_Argc() != 3)
6319                 {
6320                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6321                         return;
6322                 }
6323                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6324         }
6325         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6326         {
6327                 if (Cmd_Argc() != 3)
6328                 {
6329                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6330                         return;
6331                 }
6332                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6333         }
6334         else
6335         {
6336                 Con_Print("usage: r_editlights_edit [property] [value]\n");
6337                 Con_Print("Selected light's properties:\n");
6338                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6339                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6340                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6341                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
6342                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
6343                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
6344                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6345                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
6346                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
6347                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
6348                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
6349                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
6350                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6351                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6352                 return;
6353         }
6354         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6355         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6356 }
6357
6358 static void R_Shadow_EditLights_EditAll_f(void)
6359 {
6360         size_t lightindex;
6361         dlight_t *light, *oldselected;
6362         size_t range;
6363
6364         if (!r_editlights.integer)
6365         {
6366                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6367                 return;
6368         }
6369
6370         oldselected = r_shadow_selectedlight;
6371         // EditLights doesn't seem to have a "remove" command or something so:
6372         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6373         for (lightindex = 0;lightindex < range;lightindex++)
6374         {
6375                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6376                 if (!light)
6377                         continue;
6378                 R_Shadow_SelectLight(light);
6379                 R_Shadow_EditLights_Edit_f();
6380         }
6381         // return to old selected (to not mess editing once selection is locked)
6382         R_Shadow_SelectLight(oldselected);
6383 }
6384
6385 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6386 {
6387         int lightnumber, lightcount;
6388         size_t lightindex, range;
6389         dlight_t *light;
6390         float x, y;
6391         char temp[256];
6392         if (!r_editlights.integer)
6393                 return;
6394         x = vid_conwidth.value - 240;
6395         y = 5;
6396         DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6397         lightnumber = -1;
6398         lightcount = 0;
6399         range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6400         for (lightindex = 0;lightindex < range;lightindex++)
6401         {
6402                 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6403                 if (!light)
6404                         continue;
6405                 if (light == r_shadow_selectedlight)
6406                         lightnumber = lightindex;
6407                 lightcount++;
6408         }
6409         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;
6410         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;
6411         y += 8;
6412         if (r_shadow_selectedlight == NULL)
6413                 return;
6414         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;
6415         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;
6416         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;
6417         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;
6418         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;
6419         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;
6420         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;
6421         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;
6422         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;
6423         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;
6424         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;
6425         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;
6426         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;
6427         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;
6428         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;
6429 }
6430
6431 static void R_Shadow_EditLights_ToggleShadow_f(void)
6432 {
6433         if (!r_editlights.integer)
6434         {
6435                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6436                 return;
6437         }
6438         if (!r_shadow_selectedlight)
6439         {
6440                 Con_Print("No selected light.\n");
6441                 return;
6442         }
6443         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);
6444 }
6445
6446 static void R_Shadow_EditLights_ToggleCorona_f(void)
6447 {
6448         if (!r_editlights.integer)
6449         {
6450                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
6451                 return;
6452         }
6453         if (!r_shadow_selectedlight)
6454         {
6455                 Con_Print("No selected light.\n");
6456                 return;
6457         }
6458         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);
6459 }
6460
6461 static void R_Shadow_EditLights_Remove_f(void)
6462 {
6463         if (!r_editlights.integer)
6464         {
6465                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
6466                 return;
6467         }
6468         if (!r_shadow_selectedlight)
6469         {
6470                 Con_Print("No selected light.\n");
6471                 return;
6472         }
6473         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6474         r_shadow_selectedlight = NULL;
6475 }
6476
6477 static void R_Shadow_EditLights_Help_f(void)
6478 {
6479         Con_Print(
6480 "Documentation on r_editlights system:\n"
6481 "Settings:\n"
6482 "r_editlights : enable/disable editing mode\n"
6483 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6484 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6485 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6486 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6487 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6488 "Commands:\n"
6489 "r_editlights_help : this help\n"
6490 "r_editlights_clear : remove all lights\n"
6491 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6492 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6493 "r_editlights_save : save to .rtlights file\n"
6494 "r_editlights_spawn : create a light with default settings\n"
6495 "r_editlights_edit command : edit selected light - more documentation below\n"
6496 "r_editlights_remove : remove selected light\n"
6497 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6498 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6499 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6500 "Edit commands:\n"
6501 "origin x y z : set light location\n"
6502 "originx x: set x component of light location\n"
6503 "originy y: set y component of light location\n"
6504 "originz z: set z component of light location\n"
6505 "move x y z : adjust light location\n"
6506 "movex x: adjust x component of light location\n"
6507 "movey y: adjust y component of light location\n"
6508 "movez z: adjust z component of light location\n"
6509 "angles x y z : set light angles\n"
6510 "anglesx x: set x component of light angles\n"
6511 "anglesy y: set y component of light angles\n"
6512 "anglesz z: set z component of light angles\n"
6513 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6514 "radius radius : set radius (size) of light\n"
6515 "colorscale grey : multiply color of light (1 does nothing)\n"
6516 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6517 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6518 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6519 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6520 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6521 "cubemap basename : set filter cubemap of light (not yet supported)\n"
6522 "shadows 1/0 : turn on/off shadows\n"
6523 "corona n : set corona intensity\n"
6524 "coronasize n : set corona size (0-1)\n"
6525 "ambient n : set ambient intensity (0-1)\n"
6526 "diffuse n : set diffuse intensity (0-1)\n"
6527 "specular n : set specular intensity (0-1)\n"
6528 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6529 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6530 "<nothing> : print light properties to console\n"
6531         );
6532 }
6533
6534 static void R_Shadow_EditLights_CopyInfo_f(void)
6535 {
6536         if (!r_editlights.integer)
6537         {
6538                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
6539                 return;
6540         }
6541         if (!r_shadow_selectedlight)
6542         {
6543                 Con_Print("No selected light.\n");
6544                 return;
6545         }
6546         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6547         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6548         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6549         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6550         if (r_shadow_selectedlight->cubemapname)
6551                 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6552         else
6553                 r_shadow_bufferlight.cubemapname[0] = 0;
6554         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6555         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6556         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6557         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6558         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6559         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6560         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6561 }
6562
6563 static void R_Shadow_EditLights_PasteInfo_f(void)
6564 {
6565         if (!r_editlights.integer)
6566         {
6567                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
6568                 return;
6569         }
6570         if (!r_shadow_selectedlight)
6571         {
6572                 Con_Print("No selected light.\n");
6573                 return;
6574         }
6575         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);
6576 }
6577
6578 static void R_Shadow_EditLights_Lock_f(void)
6579 {
6580         if (!r_editlights.integer)
6581         {
6582                 Con_Print("Cannot lock on light when not in editing mode.  Set r_editlights to 1.\n");
6583                 return;
6584         }
6585         if (r_editlights_lockcursor)
6586         {
6587                 r_editlights_lockcursor = false;
6588                 return;
6589         }
6590         if (!r_shadow_selectedlight)
6591         {
6592                 Con_Print("No selected light to lock on.\n");
6593                 return;
6594         }
6595         r_editlights_lockcursor = true;
6596 }
6597
6598 static void R_Shadow_EditLights_Init(void)
6599 {
6600         Cvar_RegisterVariable(&r_editlights);
6601         Cvar_RegisterVariable(&r_editlights_cursordistance);
6602         Cvar_RegisterVariable(&r_editlights_cursorpushback);
6603         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6604         Cvar_RegisterVariable(&r_editlights_cursorgrid);
6605         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6606         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6607         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6608         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)");
6609         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6610         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6611         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6612         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)");
6613         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6614         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6615         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6616         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6617         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6618         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6619         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)");
6620         Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6621 }
6622
6623
6624
6625 /*
6626 =============================================================================
6627
6628 LIGHT SAMPLING
6629
6630 =============================================================================
6631 */
6632
6633 void R_LightPoint(vec3_t color, const vec3_t p, const int flags)
6634 {
6635         int i, numlights, flag;
6636         float f, relativepoint[3], dist, dist2, lightradius2;
6637         vec3_t diffuse, n;
6638         rtlight_t *light;
6639         dlight_t *dlight;
6640
6641         if (r_fullbright.integer)
6642         {
6643                 VectorSet(color, 1, 1, 1);
6644                 return;
6645         }
6646
6647         VectorClear(color);
6648
6649         if (flags & LP_LIGHTMAP)
6650         {
6651                 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6652                 {
6653                         VectorClear(diffuse);
6654                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6655                         VectorAdd(color, diffuse, color);
6656                 }
6657                 else
6658                         VectorSet(color, 1, 1, 1);
6659                 color[0] += r_refdef.scene.ambient;
6660                 color[1] += r_refdef.scene.ambient;
6661                 color[2] += r_refdef.scene.ambient;
6662         }
6663
6664         if (flags & LP_RTWORLD)
6665         {
6666                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6667                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6668                 for (i = 0; i < numlights; i++)
6669                 {
6670                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6671                         if (!dlight)
6672                                 continue;
6673                         light = &dlight->rtlight;
6674                         if (!(light->flags & flag))
6675                                 continue;
6676                         // sample
6677                         lightradius2 = light->radius * light->radius;
6678                         VectorSubtract(light->shadoworigin, p, relativepoint);
6679                         dist2 = VectorLength2(relativepoint);
6680                         if (dist2 >= lightradius2)
6681                                 continue;
6682                         dist = sqrt(dist2) / light->radius;
6683                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6684                         if (f <= 0)
6685                                 continue;
6686                         // todo: add to both ambient and diffuse
6687                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6688                                 VectorMA(color, f, light->currentcolor, color);
6689                 }
6690         }
6691         if (flags & LP_DYNLIGHT)
6692         {
6693                 // sample dlights
6694                 for (i = 0;i < r_refdef.scene.numlights;i++)
6695                 {
6696                         light = r_refdef.scene.lights[i];
6697                         // sample
6698                         lightradius2 = light->radius * light->radius;
6699                         VectorSubtract(light->shadoworigin, p, relativepoint);
6700                         dist2 = VectorLength2(relativepoint);
6701                         if (dist2 >= lightradius2)
6702                                 continue;
6703                         dist = sqrt(dist2) / light->radius;
6704                         f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6705                         if (f <= 0)
6706                                 continue;
6707                         // todo: add to both ambient and diffuse
6708                         if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6709                                 VectorMA(color, f, light->color, color);
6710                 }
6711         }
6712 }
6713
6714 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6715 {
6716         int i, numlights, flag;
6717         rtlight_t *light;
6718         dlight_t *dlight;
6719         float relativepoint[3];
6720         float color[3];
6721         float dir[3];
6722         float dist;
6723         float dist2;
6724         float intensity;
6725         float sample[5*3];
6726         float lightradius2;
6727
6728         if (r_fullbright.integer)
6729         {
6730                 VectorSet(ambient, 1, 1, 1);
6731                 VectorClear(diffuse);
6732                 VectorClear(lightdir);
6733                 return;
6734         }
6735
6736         if (flags == LP_LIGHTMAP)
6737         {
6738                 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6739                 VectorClear(diffuse);
6740                 VectorClear(lightdir);
6741                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6742                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6743                 else
6744                         VectorSet(ambient, 1, 1, 1);
6745                 return;
6746         }
6747
6748         memset(sample, 0, sizeof(sample));
6749         VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6750
6751         if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6752         {
6753                 vec3_t tempambient;
6754                 VectorClear(tempambient);
6755                 VectorClear(color);
6756                 VectorClear(relativepoint);
6757                 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6758                 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6759                 VectorScale(color, r_refdef.lightmapintensity, color);
6760                 VectorAdd(sample, tempambient, sample);
6761                 VectorMA(sample    , 0.5f            , color, sample    );
6762                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6763                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6764                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6765                 // calculate a weighted average light direction as well
6766                 intensity = VectorLength(color);
6767                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6768         }
6769
6770         if (flags & LP_RTWORLD)
6771         {
6772                 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6773                 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6774                 for (i = 0; i < numlights; i++)
6775                 {
6776                         dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6777                         if (!dlight)
6778                                 continue;
6779                         light = &dlight->rtlight;
6780                         if (!(light->flags & flag))
6781                                 continue;
6782                         // sample
6783                         lightradius2 = light->radius * light->radius;
6784                         VectorSubtract(light->shadoworigin, p, relativepoint);
6785                         dist2 = VectorLength2(relativepoint);
6786                         if (dist2 >= lightradius2)
6787                                 continue;
6788                         dist = sqrt(dist2) / light->radius;
6789                         intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6790                         if (intensity <= 0.0f)
6791                                 continue;
6792                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6793                                 continue;
6794                         // scale down intensity to add to both ambient and diffuse
6795                         //intensity *= 0.5f;
6796                         VectorNormalize(relativepoint);
6797                         VectorScale(light->currentcolor, intensity, color);
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                 // FIXME: sample bouncegrid too!
6807         }
6808
6809         if (flags & LP_DYNLIGHT)
6810         {
6811                 // sample dlights
6812                 for (i = 0;i < r_refdef.scene.numlights;i++)
6813                 {
6814                         light = r_refdef.scene.lights[i];
6815                         // sample
6816                         lightradius2 = light->radius * light->radius;
6817                         VectorSubtract(light->shadoworigin, p, relativepoint);
6818                         dist2 = VectorLength2(relativepoint);
6819                         if (dist2 >= lightradius2)
6820                                 continue;
6821                         dist = sqrt(dist2) / light->radius;
6822                         intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6823                         if (intensity <= 0.0f)
6824                                 continue;
6825                         if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6826                                 continue;
6827                         // scale down intensity to add to both ambient and diffuse
6828                         //intensity *= 0.5f;
6829                         VectorNormalize(relativepoint);
6830                         VectorScale(light->currentcolor, intensity, color);
6831                         VectorMA(sample    , 0.5f            , color, sample    );
6832                         VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6833                         VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6834                         VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6835                         // calculate a weighted average light direction as well
6836                         intensity *= VectorLength(color);
6837                         VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6838                 }
6839         }
6840
6841         // calculate the direction we'll use to reduce the sample to a directional light source
6842         VectorCopy(sample + 12, dir);
6843         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6844         VectorNormalize(dir);
6845         // extract the diffuse color along the chosen direction and scale it
6846         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6847         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6848         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6849         // subtract some of diffuse from ambient
6850         VectorMA(sample, -0.333f, diffuse, ambient);
6851         // store the normalized lightdir
6852         VectorCopy(dir, lightdir);
6853 }