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)
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.
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).
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).
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).
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
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.
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.
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.
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
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).
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.
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
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
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.
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
142 #include "dpsoftrast.h"
146 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
149 extern void R_Shadow_EditLights_Init(void);
151 typedef enum r_shadow_rendermode_e
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
169 r_shadow_rendermode_t;
171 typedef enum r_shadow_shadowmode_e
173 R_SHADOW_SHADOWMODE_STENCIL,
174 R_SHADOW_SHADOWMODE_SHADOWMAP2D
176 r_shadow_shadowmode_t;
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];
188 int r_shadow_drawbuffer;
189 int r_shadow_readbuffer;
191 int r_shadow_cullface_front, r_shadow_cullface_back;
192 GLuint r_shadow_fbo2d;
193 r_shadow_shadowmode_t r_shadow_shadowmode;
194 int r_shadow_shadowmapfilterquality;
195 int r_shadow_shadowmapdepthbits;
196 int r_shadow_shadowmapmaxsize;
197 qboolean r_shadow_shadowmapvsdct;
198 qboolean r_shadow_shadowmapsampler;
199 int r_shadow_shadowmappcf;
200 int r_shadow_shadowmapborder;
201 matrix4x4_t r_shadow_shadowmapmatrix;
202 int r_shadow_lightscissor[4];
203 qboolean r_shadow_usingdeferredprepass;
205 int maxshadowtriangles;
208 int maxshadowvertices;
209 float *shadowvertex3f;
219 unsigned char *shadowsides;
220 int *shadowsideslist;
227 int r_shadow_buffer_numleafpvsbytes;
228 unsigned char *r_shadow_buffer_visitingleafpvs;
229 unsigned char *r_shadow_buffer_leafpvs;
230 int *r_shadow_buffer_leaflist;
232 int r_shadow_buffer_numsurfacepvsbytes;
233 unsigned char *r_shadow_buffer_surfacepvs;
234 int *r_shadow_buffer_surfacelist;
235 unsigned char *r_shadow_buffer_surfacesides;
237 int r_shadow_buffer_numshadowtrispvsbytes;
238 unsigned char *r_shadow_buffer_shadowtrispvs;
239 int r_shadow_buffer_numlighttrispvsbytes;
240 unsigned char *r_shadow_buffer_lighttrispvs;
242 rtexturepool_t *r_shadow_texturepool;
243 rtexture_t *r_shadow_attenuationgradienttexture;
244 rtexture_t *r_shadow_attenuation2dtexture;
245 rtexture_t *r_shadow_attenuation3dtexture;
246 skinframe_t *r_shadow_lightcorona;
247 rtexture_t *r_shadow_shadowmap2dtexture;
248 rtexture_t *r_shadow_shadowmap2dcolortexture;
249 rtexture_t *r_shadow_shadowmapvsdcttexture;
250 int r_shadow_shadowmapsize; // changes for each light based on distance
251 int r_shadow_shadowmaplod; // changes for each light based on distance
253 GLuint r_shadow_prepassgeometryfbo;
254 GLuint r_shadow_prepasslightingdiffusespecularfbo;
255 GLuint r_shadow_prepasslightingdiffusefbo;
256 int r_shadow_prepass_width;
257 int r_shadow_prepass_height;
258 rtexture_t *r_shadow_prepassgeometrydepthtexture;
259 rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
260 rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
261 rtexture_t *r_shadow_prepasslightingdiffusetexture;
262 rtexture_t *r_shadow_prepasslightingspeculartexture;
264 // lights are reloaded when this changes
265 char r_shadow_mapname[MAX_QPATH];
267 // used only for light filters (cubemaps)
268 rtexturepool_t *r_shadow_filters_texturepool;
270 static const GLenum r_shadow_prepasslightingdrawbuffers[2] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT};
272 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"};
273 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"};
274 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
275 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"};
276 cvar_t r_shadow_deferred_8bitrange = {CVAR_SAVE, "r_shadow_deferred_8bitrange", "4", "dynamic range of image-based lighting when using 32bit color (does not apply to fp)"};
277 //cvar_t r_shadow_deferred_fp = {CVAR_SAVE, "r_shadow_deferred_fp", "0", "use 16bit (1) or 32bit (2) floating point for accumulation of image-based lighting"};
278 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)"};
279 cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"};
280 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)"};
281 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"};
282 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
283 cvar_t r_shadow_glossexponent = {0, "r_shadow_glossexponent", "32", "how 'sharp' the gloss should appear (specular power)"};
284 cvar_t r_shadow_gloss2exponent = {0, "r_shadow_gloss2exponent", "32", "same as r_shadow_glossexponent but for forced gloss (gloss 2) surfaces"};
285 cvar_t r_shadow_glossexact = {0, "r_shadow_glossexact", "0", "use exact reflection math for gloss (slightly slower, but should look a tad better)"};
286 cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdividebias", "1", "changes attenuation texture generation"};
287 cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"};
288 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
289 cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"};
290 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"};
291 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)"};
292 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
293 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
294 cvar_t r_shadow_realtime_dlight_svbspculling = {0, "r_shadow_realtime_dlight_svbspculling", "0", "enables svbsp optimization on dynamic lights (very slow!)"};
295 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal optimization on dynamic lights (slow!)"};
296 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)"};
297 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"};
298 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
299 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
300 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"};
301 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)"};
302 cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"};
303 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)"};
304 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"};
305 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)"};
306 cvar_t r_shadow_shadowmapping_depthbits = {CVAR_SAVE, "r_shadow_shadowmapping_depthbits", "24", "requested minimum shadowmap texture depth bits"};
307 cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"};
308 cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"};
309 cvar_t r_shadow_shadowmapping_maxsize = {CVAR_SAVE, "r_shadow_shadowmapping_maxsize", "512", "shadowmap size limit"};
310 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"};
311 //cvar_t r_shadow_shadowmapping_lod_bias = {CVAR_SAVE, "r_shadow_shadowmapping_lod_bias", "16", "shadowmap size bias"};
312 //cvar_t r_shadow_shadowmapping_lod_scale = {CVAR_SAVE, "r_shadow_shadowmapping_lod_scale", "128", "shadowmap size scaling parameter"};
313 cvar_t r_shadow_shadowmapping_bordersize = {CVAR_SAVE, "r_shadow_shadowmapping_bordersize", "4", "shadowmap size bias for filtering"};
314 cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nearclip", "1", "shadowmap nearclip in world units"};
315 cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"};
316 cvar_t r_shadow_shadowmapping_polygonfactor = {CVAR_SAVE, "r_shadow_shadowmapping_polygonfactor", "2", "slope-dependent shadowmapping bias"};
317 cvar_t r_shadow_shadowmapping_polygonoffset = {CVAR_SAVE, "r_shadow_shadowmapping_polygonoffset", "0", "constant shadowmapping bias"};
318 cvar_t r_shadow_sortsurfaces = {0, "r_shadow_sortsurfaces", "1", "improve performance by sorting illuminated surfaces by texture"};
319 cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
320 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)"};
321 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)"};
322 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)"};
323 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"};
324 cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 4x as many pixels to hold the additional data"};
325 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"};
326 cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"};
327 cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"};
328 cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1)"};
329 cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "5", "maximum number of bounces for a particle (minimum is 1)"};
330 cvar_t r_shadow_bouncegrid_particlebounceintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particlebounceintensity", "4", "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"};
331 cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"};
332 cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"};
333 cvar_t r_shadow_bouncegrid_spacingx = {CVAR_SAVE, "r_shadow_bouncegrid_spacingx", "64", "unit size of bouncegrid pixel on X axis"};
334 cvar_t r_shadow_bouncegrid_spacingy = {CVAR_SAVE, "r_shadow_bouncegrid_spacingy", "64", "unit size of bouncegrid pixel on Y axis"};
335 cvar_t r_shadow_bouncegrid_spacingz = {CVAR_SAVE, "r_shadow_bouncegrid_spacingz", "64", "unit size of bouncegrid pixel on Z axis"};
336 cvar_t r_shadow_bouncegrid_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"};
337 cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"};
338 cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"};
339 cvar_t r_shadow_bouncegrid_stablerandom = {CVAR_SAVE, "r_shadow_bouncegrid_stablerandom", "1", "make particle distribution consistent from frame to frame"};
340 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"};
341 cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"};
342 cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"};
343 cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"};
344 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
345 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"};
346 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
347 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
348 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
349 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
350 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
351 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
352 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
353 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
354 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
355 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
357 typedef struct r_shadow_bouncegrid_settings_s
360 qboolean bounceanglediffuse;
361 qboolean directionalshading;
362 float dlightparticlemultiplier;
364 float lightradiusscale;
366 float particlebounceintensity;
367 float particleintensity;
372 r_shadow_bouncegrid_settings_t;
374 r_shadow_bouncegrid_settings_t r_shadow_bouncegridsettings;
375 rtexture_t *r_shadow_bouncegridtexture;
376 matrix4x4_t r_shadow_bouncegridmatrix;
377 vec_t r_shadow_bouncegridintensity;
378 qboolean r_shadow_bouncegriddirectional;
379 static double r_shadow_bouncegridtime;
380 static int r_shadow_bouncegridresolution[3];
381 static int r_shadow_bouncegridnumpixels;
382 static unsigned char *r_shadow_bouncegridpixels;
383 static float *r_shadow_bouncegridhighpixels;
385 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
386 #define ATTENTABLESIZE 256
387 // 1D gradient, 2D circle and 3D sphere attenuation textures
388 #define ATTEN1DSIZE 32
389 #define ATTEN2DSIZE 64
390 #define ATTEN3DSIZE 32
392 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
393 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
394 static float r_shadow_attentable[ATTENTABLESIZE+1];
396 rtlight_t *r_shadow_compilingrtlight;
397 static memexpandablearray_t r_shadow_worldlightsarray;
398 dlight_t *r_shadow_selectedlight;
399 dlight_t r_shadow_bufferlight;
400 vec3_t r_editlights_cursorlocation;
401 qboolean r_editlights_lockcursor;
403 extern int con_vislines;
405 void R_Shadow_UncompileWorldLights(void);
406 void R_Shadow_ClearWorldLights(void);
407 void R_Shadow_SaveWorldLights(void);
408 void R_Shadow_LoadWorldLights(void);
409 void R_Shadow_LoadLightsFile(void);
410 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
411 void R_Shadow_EditLights_Reload_f(void);
412 void R_Shadow_ValidateCvars(void);
413 static void R_Shadow_MakeTextures(void);
415 #define EDLIGHTSPRSIZE 8
416 skinframe_t *r_editlights_sprcursor;
417 skinframe_t *r_editlights_sprlight;
418 skinframe_t *r_editlights_sprnoshadowlight;
419 skinframe_t *r_editlights_sprcubemaplight;
420 skinframe_t *r_editlights_sprcubemapnoshadowlight;
421 skinframe_t *r_editlights_sprselection;
423 void R_Shadow_SetShadowMode(void)
425 r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4);
426 r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20;
427 r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
428 r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
429 r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
430 r_shadow_shadowmaplod = -1;
431 r_shadow_shadowmapsize = 0;
432 r_shadow_shadowmapsampler = false;
433 r_shadow_shadowmappcf = 0;
434 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
435 if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
437 switch(vid.renderpath)
439 case RENDERPATH_GL20:
440 if(r_shadow_shadowmapfilterquality < 0)
442 if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
443 r_shadow_shadowmappcf = 1;
444 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD"))
446 r_shadow_shadowmapsampler = vid.support.arb_shadow;
447 r_shadow_shadowmappcf = 1;
449 else if(strstr(gl_vendor, "ATI"))
450 r_shadow_shadowmappcf = 1;
452 r_shadow_shadowmapsampler = vid.support.arb_shadow;
456 switch (r_shadow_shadowmapfilterquality)
459 r_shadow_shadowmapsampler = vid.support.arb_shadow;
462 r_shadow_shadowmapsampler = vid.support.arb_shadow;
463 r_shadow_shadowmappcf = 1;
466 r_shadow_shadowmappcf = 1;
469 r_shadow_shadowmappcf = 2;
473 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
475 case RENDERPATH_D3D9:
476 case RENDERPATH_D3D10:
477 case RENDERPATH_D3D11:
478 case RENDERPATH_SOFT:
479 r_shadow_shadowmapsampler = false;
480 r_shadow_shadowmappcf = 1;
481 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
483 case RENDERPATH_GL13:
485 case RENDERPATH_GL11:
487 case RENDERPATH_GLES2:
493 qboolean R_Shadow_ShadowMappingEnabled(void)
495 switch (r_shadow_shadowmode)
497 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
504 void R_Shadow_FreeShadowMaps(void)
506 R_Shadow_SetShadowMode();
508 R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
512 if (r_shadow_shadowmap2dtexture)
513 R_FreeTexture(r_shadow_shadowmap2dtexture);
514 r_shadow_shadowmap2dtexture = NULL;
516 if (r_shadow_shadowmap2dcolortexture)
517 R_FreeTexture(r_shadow_shadowmap2dcolortexture);
518 r_shadow_shadowmap2dcolortexture = NULL;
520 if (r_shadow_shadowmapvsdcttexture)
521 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
522 r_shadow_shadowmapvsdcttexture = NULL;
525 void r_shadow_start(void)
527 // allocate vertex processing arrays
528 r_shadow_bouncegridpixels = NULL;
529 r_shadow_bouncegridhighpixels = NULL;
530 r_shadow_bouncegridnumpixels = 0;
531 r_shadow_bouncegridtexture = NULL;
532 r_shadow_bouncegriddirectional = false;
533 r_shadow_attenuationgradienttexture = NULL;
534 r_shadow_attenuation2dtexture = NULL;
535 r_shadow_attenuation3dtexture = NULL;
536 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
537 r_shadow_shadowmap2dtexture = NULL;
538 r_shadow_shadowmap2dcolortexture = NULL;
539 r_shadow_shadowmapvsdcttexture = NULL;
540 r_shadow_shadowmapmaxsize = 0;
541 r_shadow_shadowmapsize = 0;
542 r_shadow_shadowmaplod = 0;
543 r_shadow_shadowmapfilterquality = -1;
544 r_shadow_shadowmapdepthbits = 0;
545 r_shadow_shadowmapvsdct = false;
546 r_shadow_shadowmapsampler = false;
547 r_shadow_shadowmappcf = 0;
550 R_Shadow_FreeShadowMaps();
552 r_shadow_texturepool = NULL;
553 r_shadow_filters_texturepool = NULL;
554 R_Shadow_ValidateCvars();
555 R_Shadow_MakeTextures();
556 maxshadowtriangles = 0;
557 shadowelements = NULL;
558 maxshadowvertices = 0;
559 shadowvertex3f = NULL;
567 shadowmarklist = NULL;
572 shadowsideslist = NULL;
573 r_shadow_buffer_numleafpvsbytes = 0;
574 r_shadow_buffer_visitingleafpvs = NULL;
575 r_shadow_buffer_leafpvs = NULL;
576 r_shadow_buffer_leaflist = NULL;
577 r_shadow_buffer_numsurfacepvsbytes = 0;
578 r_shadow_buffer_surfacepvs = NULL;
579 r_shadow_buffer_surfacelist = NULL;
580 r_shadow_buffer_surfacesides = NULL;
581 r_shadow_buffer_numshadowtrispvsbytes = 0;
582 r_shadow_buffer_shadowtrispvs = NULL;
583 r_shadow_buffer_numlighttrispvsbytes = 0;
584 r_shadow_buffer_lighttrispvs = NULL;
586 r_shadow_usingdeferredprepass = false;
587 r_shadow_prepass_width = r_shadow_prepass_height = 0;
590 static void R_Shadow_FreeDeferred(void);
591 void r_shadow_shutdown(void)
594 R_Shadow_UncompileWorldLights();
596 R_Shadow_FreeShadowMaps();
598 r_shadow_usingdeferredprepass = false;
599 if (r_shadow_prepass_width)
600 R_Shadow_FreeDeferred();
601 r_shadow_prepass_width = r_shadow_prepass_height = 0;
604 r_shadow_bouncegridtexture = NULL;
605 r_shadow_bouncegridpixels = NULL;
606 r_shadow_bouncegridhighpixels = NULL;
607 r_shadow_bouncegridnumpixels = 0;
608 r_shadow_bouncegriddirectional = false;
609 r_shadow_attenuationgradienttexture = NULL;
610 r_shadow_attenuation2dtexture = NULL;
611 r_shadow_attenuation3dtexture = NULL;
612 R_FreeTexturePool(&r_shadow_texturepool);
613 R_FreeTexturePool(&r_shadow_filters_texturepool);
614 maxshadowtriangles = 0;
616 Mem_Free(shadowelements);
617 shadowelements = NULL;
619 Mem_Free(shadowvertex3f);
620 shadowvertex3f = NULL;
623 Mem_Free(vertexupdate);
626 Mem_Free(vertexremap);
632 Mem_Free(shadowmark);
635 Mem_Free(shadowmarklist);
636 shadowmarklist = NULL;
641 Mem_Free(shadowsides);
644 Mem_Free(shadowsideslist);
645 shadowsideslist = NULL;
646 r_shadow_buffer_numleafpvsbytes = 0;
647 if (r_shadow_buffer_visitingleafpvs)
648 Mem_Free(r_shadow_buffer_visitingleafpvs);
649 r_shadow_buffer_visitingleafpvs = NULL;
650 if (r_shadow_buffer_leafpvs)
651 Mem_Free(r_shadow_buffer_leafpvs);
652 r_shadow_buffer_leafpvs = NULL;
653 if (r_shadow_buffer_leaflist)
654 Mem_Free(r_shadow_buffer_leaflist);
655 r_shadow_buffer_leaflist = NULL;
656 r_shadow_buffer_numsurfacepvsbytes = 0;
657 if (r_shadow_buffer_surfacepvs)
658 Mem_Free(r_shadow_buffer_surfacepvs);
659 r_shadow_buffer_surfacepvs = NULL;
660 if (r_shadow_buffer_surfacelist)
661 Mem_Free(r_shadow_buffer_surfacelist);
662 r_shadow_buffer_surfacelist = NULL;
663 if (r_shadow_buffer_surfacesides)
664 Mem_Free(r_shadow_buffer_surfacesides);
665 r_shadow_buffer_surfacesides = NULL;
666 r_shadow_buffer_numshadowtrispvsbytes = 0;
667 if (r_shadow_buffer_shadowtrispvs)
668 Mem_Free(r_shadow_buffer_shadowtrispvs);
669 r_shadow_buffer_numlighttrispvsbytes = 0;
670 if (r_shadow_buffer_lighttrispvs)
671 Mem_Free(r_shadow_buffer_lighttrispvs);
674 void r_shadow_newmap(void)
676 if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
677 if (r_shadow_lightcorona) R_SkinFrame_MarkUsed(r_shadow_lightcorona);
678 if (r_editlights_sprcursor) R_SkinFrame_MarkUsed(r_editlights_sprcursor);
679 if (r_editlights_sprlight) R_SkinFrame_MarkUsed(r_editlights_sprlight);
680 if (r_editlights_sprnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
681 if (r_editlights_sprcubemaplight) R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
682 if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
683 if (r_editlights_sprselection) R_SkinFrame_MarkUsed(r_editlights_sprselection);
684 if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
685 R_Shadow_EditLights_Reload_f();
688 void R_Shadow_Init(void)
690 Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
691 Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
692 Cvar_RegisterVariable(&r_shadow_usebihculling);
693 Cvar_RegisterVariable(&r_shadow_usenormalmap);
694 Cvar_RegisterVariable(&r_shadow_debuglight);
695 Cvar_RegisterVariable(&r_shadow_deferred);
696 Cvar_RegisterVariable(&r_shadow_deferred_8bitrange);
697 // Cvar_RegisterVariable(&r_shadow_deferred_fp);
698 Cvar_RegisterVariable(&r_shadow_gloss);
699 Cvar_RegisterVariable(&r_shadow_gloss2intensity);
700 Cvar_RegisterVariable(&r_shadow_glossintensity);
701 Cvar_RegisterVariable(&r_shadow_glossexponent);
702 Cvar_RegisterVariable(&r_shadow_gloss2exponent);
703 Cvar_RegisterVariable(&r_shadow_glossexact);
704 Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
705 Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
706 Cvar_RegisterVariable(&r_shadow_lightintensityscale);
707 Cvar_RegisterVariable(&r_shadow_lightradiusscale);
708 Cvar_RegisterVariable(&r_shadow_projectdistance);
709 Cvar_RegisterVariable(&r_shadow_frontsidecasting);
710 Cvar_RegisterVariable(&r_shadow_realtime_dlight);
711 Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
712 Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
713 Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
714 Cvar_RegisterVariable(&r_shadow_realtime_world);
715 Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
716 Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
717 Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
718 Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
719 Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
720 Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
721 Cvar_RegisterVariable(&r_shadow_scissor);
722 Cvar_RegisterVariable(&r_shadow_shadowmapping);
723 Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
724 Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
725 Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
726 Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
727 Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
728 Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
729 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
730 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
731 Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
732 Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
733 Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
734 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
735 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
736 Cvar_RegisterVariable(&r_shadow_sortsurfaces);
737 Cvar_RegisterVariable(&r_shadow_polygonfactor);
738 Cvar_RegisterVariable(&r_shadow_polygonoffset);
739 Cvar_RegisterVariable(&r_shadow_texture3d);
740 Cvar_RegisterVariable(&r_shadow_bouncegrid);
741 Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
742 Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
743 Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
744 Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
745 Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
746 Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
747 Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
748 Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
749 Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
750 Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
751 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingx);
752 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingy);
753 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingz);
754 Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
755 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
756 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
757 Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
758 Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
759 Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
760 Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
761 Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
762 Cvar_RegisterVariable(&r_coronas);
763 Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
764 Cvar_RegisterVariable(&r_coronas_occlusionquery);
765 Cvar_RegisterVariable(&gl_flashblend);
766 Cvar_RegisterVariable(&gl_ext_separatestencil);
767 Cvar_RegisterVariable(&gl_ext_stenciltwoside);
768 R_Shadow_EditLights_Init();
769 Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
770 maxshadowtriangles = 0;
771 shadowelements = NULL;
772 maxshadowvertices = 0;
773 shadowvertex3f = NULL;
781 shadowmarklist = NULL;
786 shadowsideslist = NULL;
787 r_shadow_buffer_numleafpvsbytes = 0;
788 r_shadow_buffer_visitingleafpvs = NULL;
789 r_shadow_buffer_leafpvs = NULL;
790 r_shadow_buffer_leaflist = NULL;
791 r_shadow_buffer_numsurfacepvsbytes = 0;
792 r_shadow_buffer_surfacepvs = NULL;
793 r_shadow_buffer_surfacelist = NULL;
794 r_shadow_buffer_surfacesides = NULL;
795 r_shadow_buffer_shadowtrispvs = NULL;
796 r_shadow_buffer_lighttrispvs = NULL;
797 R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
800 matrix4x4_t matrix_attenuationxyz =
803 {0.5, 0.0, 0.0, 0.5},
804 {0.0, 0.5, 0.0, 0.5},
805 {0.0, 0.0, 0.5, 0.5},
810 matrix4x4_t matrix_attenuationz =
813 {0.0, 0.0, 0.5, 0.5},
814 {0.0, 0.0, 0.0, 0.5},
815 {0.0, 0.0, 0.0, 0.5},
820 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
822 numvertices = ((numvertices + 255) & ~255) * vertscale;
823 numtriangles = ((numtriangles + 255) & ~255) * triscale;
824 // make sure shadowelements is big enough for this volume
825 if (maxshadowtriangles < numtriangles)
827 maxshadowtriangles = numtriangles;
829 Mem_Free(shadowelements);
830 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
832 // make sure shadowvertex3f is big enough for this volume
833 if (maxshadowvertices < numvertices)
835 maxshadowvertices = numvertices;
837 Mem_Free(shadowvertex3f);
838 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
842 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
844 int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
845 int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
846 int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
847 int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
848 if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
850 if (r_shadow_buffer_visitingleafpvs)
851 Mem_Free(r_shadow_buffer_visitingleafpvs);
852 if (r_shadow_buffer_leafpvs)
853 Mem_Free(r_shadow_buffer_leafpvs);
854 if (r_shadow_buffer_leaflist)
855 Mem_Free(r_shadow_buffer_leaflist);
856 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
857 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
858 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
859 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
861 if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
863 if (r_shadow_buffer_surfacepvs)
864 Mem_Free(r_shadow_buffer_surfacepvs);
865 if (r_shadow_buffer_surfacelist)
866 Mem_Free(r_shadow_buffer_surfacelist);
867 if (r_shadow_buffer_surfacesides)
868 Mem_Free(r_shadow_buffer_surfacesides);
869 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
870 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
871 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
872 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
874 if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
876 if (r_shadow_buffer_shadowtrispvs)
877 Mem_Free(r_shadow_buffer_shadowtrispvs);
878 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
879 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
881 if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
883 if (r_shadow_buffer_lighttrispvs)
884 Mem_Free(r_shadow_buffer_lighttrispvs);
885 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
886 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
890 void R_Shadow_PrepareShadowMark(int numtris)
892 // make sure shadowmark is big enough for this volume
893 if (maxshadowmark < numtris)
895 maxshadowmark = numtris;
897 Mem_Free(shadowmark);
899 Mem_Free(shadowmarklist);
900 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
901 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
905 // if shadowmarkcount wrapped we clear the array and adjust accordingly
906 if (shadowmarkcount == 0)
909 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
914 void R_Shadow_PrepareShadowSides(int numtris)
916 if (maxshadowsides < numtris)
918 maxshadowsides = numtris;
920 Mem_Free(shadowsides);
922 Mem_Free(shadowsideslist);
923 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
924 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
929 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)
932 int outtriangles = 0, outvertices = 0;
935 float ratio, direction[3], projectvector[3];
937 if (projectdirection)
938 VectorScale(projectdirection, projectdistance, projectvector);
940 VectorClear(projectvector);
942 // create the vertices
943 if (projectdirection)
945 for (i = 0;i < numshadowmarktris;i++)
947 element = inelement3i + shadowmarktris[i] * 3;
948 for (j = 0;j < 3;j++)
950 if (vertexupdate[element[j]] != vertexupdatenum)
952 vertexupdate[element[j]] = vertexupdatenum;
953 vertexremap[element[j]] = outvertices;
954 vertex = invertex3f + element[j] * 3;
955 // project one copy of the vertex according to projectvector
956 VectorCopy(vertex, outvertex3f);
957 VectorAdd(vertex, projectvector, (outvertex3f + 3));
966 for (i = 0;i < numshadowmarktris;i++)
968 element = inelement3i + shadowmarktris[i] * 3;
969 for (j = 0;j < 3;j++)
971 if (vertexupdate[element[j]] != vertexupdatenum)
973 vertexupdate[element[j]] = vertexupdatenum;
974 vertexremap[element[j]] = outvertices;
975 vertex = invertex3f + element[j] * 3;
976 // project one copy of the vertex to the sphere radius of the light
977 // (FIXME: would projecting it to the light box be better?)
978 VectorSubtract(vertex, projectorigin, direction);
979 ratio = projectdistance / VectorLength(direction);
980 VectorCopy(vertex, outvertex3f);
981 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
989 if (r_shadow_frontsidecasting.integer)
991 for (i = 0;i < numshadowmarktris;i++)
993 int remappedelement[3];
995 const int *neighbortriangle;
997 markindex = shadowmarktris[i] * 3;
998 element = inelement3i + markindex;
999 neighbortriangle = inneighbor3i + markindex;
1000 // output the front and back triangles
1001 outelement3i[0] = vertexremap[element[0]];
1002 outelement3i[1] = vertexremap[element[1]];
1003 outelement3i[2] = vertexremap[element[2]];
1004 outelement3i[3] = vertexremap[element[2]] + 1;
1005 outelement3i[4] = vertexremap[element[1]] + 1;
1006 outelement3i[5] = vertexremap[element[0]] + 1;
1010 // output the sides (facing outward from this triangle)
1011 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1013 remappedelement[0] = vertexremap[element[0]];
1014 remappedelement[1] = vertexremap[element[1]];
1015 outelement3i[0] = remappedelement[1];
1016 outelement3i[1] = remappedelement[0];
1017 outelement3i[2] = remappedelement[0] + 1;
1018 outelement3i[3] = remappedelement[1];
1019 outelement3i[4] = remappedelement[0] + 1;
1020 outelement3i[5] = remappedelement[1] + 1;
1025 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1027 remappedelement[1] = vertexremap[element[1]];
1028 remappedelement[2] = vertexremap[element[2]];
1029 outelement3i[0] = remappedelement[2];
1030 outelement3i[1] = remappedelement[1];
1031 outelement3i[2] = remappedelement[1] + 1;
1032 outelement3i[3] = remappedelement[2];
1033 outelement3i[4] = remappedelement[1] + 1;
1034 outelement3i[5] = remappedelement[2] + 1;
1039 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1041 remappedelement[0] = vertexremap[element[0]];
1042 remappedelement[2] = vertexremap[element[2]];
1043 outelement3i[0] = remappedelement[0];
1044 outelement3i[1] = remappedelement[2];
1045 outelement3i[2] = remappedelement[2] + 1;
1046 outelement3i[3] = remappedelement[0];
1047 outelement3i[4] = remappedelement[2] + 1;
1048 outelement3i[5] = remappedelement[0] + 1;
1057 for (i = 0;i < numshadowmarktris;i++)
1059 int remappedelement[3];
1061 const int *neighbortriangle;
1063 markindex = shadowmarktris[i] * 3;
1064 element = inelement3i + markindex;
1065 neighbortriangle = inneighbor3i + markindex;
1066 // output the front and back triangles
1067 outelement3i[0] = vertexremap[element[2]];
1068 outelement3i[1] = vertexremap[element[1]];
1069 outelement3i[2] = vertexremap[element[0]];
1070 outelement3i[3] = vertexremap[element[0]] + 1;
1071 outelement3i[4] = vertexremap[element[1]] + 1;
1072 outelement3i[5] = vertexremap[element[2]] + 1;
1076 // output the sides (facing outward from this triangle)
1077 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1079 remappedelement[0] = vertexremap[element[0]];
1080 remappedelement[1] = vertexremap[element[1]];
1081 outelement3i[0] = remappedelement[0];
1082 outelement3i[1] = remappedelement[1];
1083 outelement3i[2] = remappedelement[1] + 1;
1084 outelement3i[3] = remappedelement[0];
1085 outelement3i[4] = remappedelement[1] + 1;
1086 outelement3i[5] = remappedelement[0] + 1;
1091 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1093 remappedelement[1] = vertexremap[element[1]];
1094 remappedelement[2] = vertexremap[element[2]];
1095 outelement3i[0] = remappedelement[1];
1096 outelement3i[1] = remappedelement[2];
1097 outelement3i[2] = remappedelement[2] + 1;
1098 outelement3i[3] = remappedelement[1];
1099 outelement3i[4] = remappedelement[2] + 1;
1100 outelement3i[5] = remappedelement[1] + 1;
1105 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1107 remappedelement[0] = vertexremap[element[0]];
1108 remappedelement[2] = vertexremap[element[2]];
1109 outelement3i[0] = remappedelement[2];
1110 outelement3i[1] = remappedelement[0];
1111 outelement3i[2] = remappedelement[0] + 1;
1112 outelement3i[3] = remappedelement[2];
1113 outelement3i[4] = remappedelement[0] + 1;
1114 outelement3i[5] = remappedelement[2] + 1;
1122 *outnumvertices = outvertices;
1123 return outtriangles;
1126 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)
1129 int outtriangles = 0, outvertices = 0;
1131 const float *vertex;
1132 float ratio, direction[3], projectvector[3];
1135 if (projectdirection)
1136 VectorScale(projectdirection, projectdistance, projectvector);
1138 VectorClear(projectvector);
1140 for (i = 0;i < numshadowmarktris;i++)
1142 int remappedelement[3];
1144 const int *neighbortriangle;
1146 markindex = shadowmarktris[i] * 3;
1147 neighbortriangle = inneighbor3i + markindex;
1148 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1149 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1150 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1151 if (side[0] + side[1] + side[2] == 0)
1155 element = inelement3i + markindex;
1157 // create the vertices
1158 for (j = 0;j < 3;j++)
1160 if (side[j] + side[j+1] == 0)
1163 if (vertexupdate[k] != vertexupdatenum)
1165 vertexupdate[k] = vertexupdatenum;
1166 vertexremap[k] = outvertices;
1167 vertex = invertex3f + k * 3;
1168 VectorCopy(vertex, outvertex3f);
1169 if (projectdirection)
1171 // project one copy of the vertex according to projectvector
1172 VectorAdd(vertex, projectvector, (outvertex3f + 3));
1176 // project one copy of the vertex to the sphere radius of the light
1177 // (FIXME: would projecting it to the light box be better?)
1178 VectorSubtract(vertex, projectorigin, direction);
1179 ratio = projectdistance / VectorLength(direction);
1180 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1187 // output the sides (facing outward from this triangle)
1190 remappedelement[0] = vertexremap[element[0]];
1191 remappedelement[1] = vertexremap[element[1]];
1192 outelement3i[0] = remappedelement[1];
1193 outelement3i[1] = remappedelement[0];
1194 outelement3i[2] = remappedelement[0] + 1;
1195 outelement3i[3] = remappedelement[1];
1196 outelement3i[4] = remappedelement[0] + 1;
1197 outelement3i[5] = remappedelement[1] + 1;
1204 remappedelement[1] = vertexremap[element[1]];
1205 remappedelement[2] = vertexremap[element[2]];
1206 outelement3i[0] = remappedelement[2];
1207 outelement3i[1] = remappedelement[1];
1208 outelement3i[2] = remappedelement[1] + 1;
1209 outelement3i[3] = remappedelement[2];
1210 outelement3i[4] = remappedelement[1] + 1;
1211 outelement3i[5] = remappedelement[2] + 1;
1218 remappedelement[0] = vertexremap[element[0]];
1219 remappedelement[2] = vertexremap[element[2]];
1220 outelement3i[0] = remappedelement[0];
1221 outelement3i[1] = remappedelement[2];
1222 outelement3i[2] = remappedelement[2] + 1;
1223 outelement3i[3] = remappedelement[0];
1224 outelement3i[4] = remappedelement[2] + 1;
1225 outelement3i[5] = remappedelement[0] + 1;
1232 *outnumvertices = outvertices;
1233 return outtriangles;
1236 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)
1242 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1244 tend = firsttriangle + numtris;
1245 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1247 // surface box entirely inside light box, no box cull
1248 if (projectdirection)
1250 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1252 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1253 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1254 shadowmarklist[numshadowmark++] = t;
1259 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1260 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1261 shadowmarklist[numshadowmark++] = t;
1266 // surface box not entirely inside light box, cull each triangle
1267 if (projectdirection)
1269 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1271 v[0] = invertex3f + e[0] * 3;
1272 v[1] = invertex3f + e[1] * 3;
1273 v[2] = invertex3f + e[2] * 3;
1274 TriangleNormal(v[0], v[1], v[2], normal);
1275 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1276 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1277 shadowmarklist[numshadowmark++] = t;
1282 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1284 v[0] = invertex3f + e[0] * 3;
1285 v[1] = invertex3f + e[1] * 3;
1286 v[2] = invertex3f + e[2] * 3;
1287 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1288 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1289 shadowmarklist[numshadowmark++] = t;
1295 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1300 if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1302 // check if the shadow volume intersects the near plane
1304 // a ray between the eye and light origin may intersect the caster,
1305 // indicating that the shadow may touch the eye location, however we must
1306 // test the near plane (a polygon), not merely the eye location, so it is
1307 // easiest to enlarge the caster bounding shape slightly for this.
1313 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)
1315 int i, tris, outverts;
1316 if (projectdistance < 0.1)
1318 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1321 if (!numverts || !nummarktris)
1323 // make sure shadowelements is big enough for this volume
1324 if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1325 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1327 if (maxvertexupdate < numverts)
1329 maxvertexupdate = numverts;
1331 Mem_Free(vertexupdate);
1333 Mem_Free(vertexremap);
1334 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1335 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1336 vertexupdatenum = 0;
1339 if (vertexupdatenum == 0)
1341 vertexupdatenum = 1;
1342 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1343 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1346 for (i = 0;i < nummarktris;i++)
1347 shadowmark[marktris[i]] = shadowmarkcount;
1349 if (r_shadow_compilingrtlight)
1351 // if we're compiling an rtlight, capture the mesh
1352 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1353 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1354 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1355 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1357 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1359 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1360 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1361 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1365 // decide which type of shadow to generate and set stencil mode
1366 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1367 // generate the sides or a solid volume, depending on type
1368 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1369 tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1371 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1372 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1373 r_refdef.stats.lights_shadowtriangles += tris;
1374 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1376 // increment stencil if frontface is infront of depthbuffer
1377 GL_CullFace(r_refdef.view.cullface_front);
1378 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1379 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1380 // decrement stencil if backface is infront of depthbuffer
1381 GL_CullFace(r_refdef.view.cullface_back);
1382 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1384 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1386 // decrement stencil if backface is behind depthbuffer
1387 GL_CullFace(r_refdef.view.cullface_front);
1388 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1389 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1390 // increment stencil if frontface is behind depthbuffer
1391 GL_CullFace(r_refdef.view.cullface_back);
1392 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1394 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1395 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1399 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1401 // p1, p2, p3 are in the cubemap's local coordinate system
1402 // bias = border/(size - border)
1405 float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1406 dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1407 dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1408 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1410 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1411 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1412 | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1413 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1415 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1416 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1417 | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1419 dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1420 dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1421 dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1422 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1424 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1425 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1426 | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1427 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1429 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1430 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1431 | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1433 dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1434 dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1435 dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1436 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1438 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1439 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1440 | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1441 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1443 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1444 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1445 | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1450 int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1452 vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1453 float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1456 VectorSubtract(maxs, mins, radius);
1457 VectorScale(radius, 0.5f, radius);
1458 VectorAdd(mins, radius, center);
1459 Matrix4x4_Transform(worldtolight, center, lightcenter);
1460 Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1461 VectorSubtract(lightcenter, lightradius, pmin);
1462 VectorAdd(lightcenter, lightradius, pmax);
1464 dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1465 dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1466 if(ap1 > bias*an1 && ap2 > bias*an2)
1468 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1469 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1470 if(an1 > bias*ap1 && an2 > bias*ap2)
1472 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1473 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1475 dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1476 dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1477 if(ap1 > bias*an1 && ap2 > bias*an2)
1479 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1480 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1481 if(an1 > bias*ap1 && an2 > bias*ap2)
1483 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1484 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1486 dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1487 dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1488 if(ap1 > bias*an1 && ap2 > bias*an2)
1490 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1491 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1492 if(an1 > bias*ap1 && an2 > bias*ap2)
1494 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1495 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1500 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1502 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1504 // p is in the cubemap's local coordinate system
1505 // bias = border/(size - border)
1506 float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1507 float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1508 float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1510 if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1511 if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1512 if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1513 if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1514 if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1515 if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1519 int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1523 int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1524 float scale = (size - 2*border)/size, len;
1525 float bias = border / (float)(size - border), dp, dn, ap, an;
1526 // check if cone enclosing side would cross frustum plane
1527 scale = 2 / (scale*scale + 2);
1528 for (i = 0;i < 5;i++)
1530 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1532 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1533 len = scale*VectorLength2(n);
1534 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1535 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1536 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1538 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1540 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1541 len = scale*VectorLength(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);
1546 // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1547 // check if frustum corners/origin cross plane sides
1549 // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1550 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1551 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1552 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1553 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1554 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1555 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1556 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1557 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1558 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1559 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1560 for (i = 0;i < 4;i++)
1562 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1563 VectorSubtract(n, p, n);
1564 dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1565 if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1566 if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1567 dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1568 if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1569 if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1570 dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1571 if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1572 if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1575 // finite version, assumes corners are a finite distance from origin dependent on far plane
1576 for (i = 0;i < 5;i++)
1578 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1579 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1580 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1581 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1582 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1583 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1584 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1585 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1586 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1587 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1590 return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1593 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)
1601 int mask, surfacemask = 0;
1602 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1604 bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1605 tend = firsttriangle + numtris;
1606 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1608 // surface box entirely inside light box, no box cull
1609 if (projectdirection)
1611 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1613 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1614 TriangleNormal(v[0], v[1], v[2], normal);
1615 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1617 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1618 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1619 surfacemask |= mask;
1622 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;
1623 shadowsides[numshadowsides] = mask;
1624 shadowsideslist[numshadowsides++] = t;
1631 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1633 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1634 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1636 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1637 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1638 surfacemask |= mask;
1641 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;
1642 shadowsides[numshadowsides] = mask;
1643 shadowsideslist[numshadowsides++] = t;
1651 // surface box not entirely inside light box, cull each triangle
1652 if (projectdirection)
1654 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1656 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1657 TriangleNormal(v[0], v[1], v[2], normal);
1658 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1659 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1661 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1662 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1663 surfacemask |= mask;
1666 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;
1667 shadowsides[numshadowsides] = mask;
1668 shadowsideslist[numshadowsides++] = t;
1675 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1677 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1678 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1679 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1681 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1682 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1683 surfacemask |= mask;
1686 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;
1687 shadowsides[numshadowsides] = mask;
1688 shadowsideslist[numshadowsides++] = t;
1697 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)
1699 int i, j, outtriangles = 0;
1700 int *outelement3i[6];
1701 if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1703 outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1704 // make sure shadowelements is big enough for this mesh
1705 if (maxshadowtriangles < outtriangles)
1706 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1708 // compute the offset and size of the separate index lists for each cubemap side
1710 for (i = 0;i < 6;i++)
1712 outelement3i[i] = shadowelements + outtriangles * 3;
1713 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1714 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1715 outtriangles += sidetotals[i];
1718 // gather up the (sparse) triangles into separate index lists for each cubemap side
1719 for (i = 0;i < numsidetris;i++)
1721 const int *element = elements + sidetris[i] * 3;
1722 for (j = 0;j < 6;j++)
1724 if (sides[i] & (1 << j))
1726 outelement3i[j][0] = element[0];
1727 outelement3i[j][1] = element[1];
1728 outelement3i[j][2] = element[2];
1729 outelement3i[j] += 3;
1734 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1737 static void R_Shadow_MakeTextures_MakeCorona(void)
1741 unsigned char pixels[32][32][4];
1742 for (y = 0;y < 32;y++)
1744 dy = (y - 15.5f) * (1.0f / 16.0f);
1745 for (x = 0;x < 32;x++)
1747 dx = (x - 15.5f) * (1.0f / 16.0f);
1748 a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1749 a = bound(0, a, 255);
1750 pixels[y][x][0] = a;
1751 pixels[y][x][1] = a;
1752 pixels[y][x][2] = a;
1753 pixels[y][x][3] = 255;
1756 r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32);
1759 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1761 float dist = sqrt(x*x+y*y+z*z);
1762 float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1763 // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1764 return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1767 static void R_Shadow_MakeTextures(void)
1770 float intensity, dist;
1772 R_Shadow_FreeShadowMaps();
1773 R_FreeTexturePool(&r_shadow_texturepool);
1774 r_shadow_texturepool = R_AllocTexturePool();
1775 r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1776 r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1777 data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1778 // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1779 for (x = 0;x <= ATTENTABLESIZE;x++)
1781 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1782 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1783 r_shadow_attentable[x] = bound(0, intensity, 1);
1785 // 1D gradient texture
1786 for (x = 0;x < ATTEN1DSIZE;x++)
1787 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1788 r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1789 // 2D circle texture
1790 for (y = 0;y < ATTEN2DSIZE;y++)
1791 for (x = 0;x < ATTEN2DSIZE;x++)
1792 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);
1793 r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1794 // 3D sphere texture
1795 if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1797 for (z = 0;z < ATTEN3DSIZE;z++)
1798 for (y = 0;y < ATTEN3DSIZE;y++)
1799 for (x = 0;x < ATTEN3DSIZE;x++)
1800 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));
1801 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);
1804 r_shadow_attenuation3dtexture = NULL;
1807 R_Shadow_MakeTextures_MakeCorona();
1809 // Editor light sprites
1810 r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1827 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1828 r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1845 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1846 r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1863 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1864 r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1881 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1882 r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1899 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1900 r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1917 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1920 void R_Shadow_ValidateCvars(void)
1922 if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1923 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1924 if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1925 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1926 if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1927 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1930 void R_Shadow_RenderMode_Begin(void)
1936 R_Shadow_ValidateCvars();
1938 if (!r_shadow_attenuation2dtexture
1939 || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1940 || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1941 || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1942 R_Shadow_MakeTextures();
1945 R_Mesh_ResetTextureState();
1946 GL_BlendFunc(GL_ONE, GL_ZERO);
1947 GL_DepthRange(0, 1);
1948 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1950 GL_DepthMask(false);
1951 GL_Color(0, 0, 0, 1);
1952 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1954 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1956 if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1958 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1959 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1961 else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1963 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1964 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1968 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1969 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1972 switch(vid.renderpath)
1974 case RENDERPATH_GL20:
1975 case RENDERPATH_D3D9:
1976 case RENDERPATH_D3D10:
1977 case RENDERPATH_D3D11:
1978 case RENDERPATH_SOFT:
1979 case RENDERPATH_GLES2:
1980 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1982 case RENDERPATH_GL13:
1983 case RENDERPATH_GL11:
1984 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
1985 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
1986 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
1987 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
1988 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
1989 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
1991 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
1997 qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
1998 qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
1999 r_shadow_drawbuffer = drawbuffer;
2000 r_shadow_readbuffer = readbuffer;
2002 r_shadow_cullface_front = r_refdef.view.cullface_front;
2003 r_shadow_cullface_back = r_refdef.view.cullface_back;
2006 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2008 rsurface.rtlight = rtlight;
2011 void R_Shadow_RenderMode_Reset(void)
2013 R_Mesh_ResetRenderTargets();
2014 R_SetViewport(&r_refdef.view.viewport);
2015 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2016 R_Mesh_ResetTextureState();
2017 GL_DepthRange(0, 1);
2019 GL_DepthMask(false);
2020 GL_DepthFunc(GL_LEQUAL);
2021 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2022 r_refdef.view.cullface_front = r_shadow_cullface_front;
2023 r_refdef.view.cullface_back = r_shadow_cullface_back;
2024 GL_CullFace(r_refdef.view.cullface_back);
2025 GL_Color(1, 1, 1, 1);
2026 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2027 GL_BlendFunc(GL_ONE, GL_ZERO);
2028 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
2029 r_shadow_usingshadowmap2d = false;
2030 r_shadow_usingshadowmaportho = false;
2031 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2034 void R_Shadow_ClearStencil(void)
2036 GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2037 r_refdef.stats.lights_clears++;
2040 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2042 r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2043 if (r_shadow_rendermode == mode)
2045 R_Shadow_RenderMode_Reset();
2046 GL_DepthFunc(GL_LESS);
2047 GL_ColorMask(0, 0, 0, 0);
2048 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2049 GL_CullFace(GL_NONE);
2050 R_SetupShader_DepthOrShadow();
2051 r_shadow_rendermode = mode;
2056 case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2057 case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2058 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2060 case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2061 case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2062 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2067 static void R_Shadow_MakeVSDCT(void)
2069 // maps to a 2x3 texture rectangle with normalized coordinates
2074 // stores abs(dir.xy), offset.xy/2.5
2075 unsigned char data[4*6] =
2077 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2078 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2079 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2080 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2081 0, 0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2082 0, 0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2084 r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2087 static void R_Shadow_MakeShadowMap(int side, int size)
2089 switch (r_shadow_shadowmode)
2091 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2092 if (r_shadow_shadowmap2dtexture) return;
2093 r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
2094 r_shadow_shadowmap2dcolortexture = NULL;
2095 switch(vid.renderpath)
2098 case RENDERPATH_D3D9:
2099 r_shadow_shadowmap2dcolortexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_BGRA, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2100 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2104 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
2112 // render depth into the fbo, do not render color at all
2113 // validate the fbo now
2117 qglDrawBuffer(GL_NONE);CHECKGLERROR
2118 qglReadBuffer(GL_NONE);CHECKGLERROR
2119 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
2120 if (status != GL_FRAMEBUFFER_COMPLETE_EXT && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
2122 Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
2123 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
2124 Cvar_SetValueQuick(&r_shadow_deferred, 0);
2129 void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2131 float nearclip, farclip, bias;
2132 r_viewport_t viewport;
2135 float clearcolor[4];
2136 nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2138 bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2139 r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2140 r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2141 r_shadow_shadowmapside = side;
2142 r_shadow_shadowmapsize = size;
2144 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2145 r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2146 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2147 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2149 // complex unrolled cube approach (more flexible)
2150 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2151 R_Shadow_MakeVSDCT();
2152 if (!r_shadow_shadowmap2dtexture)
2153 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2154 if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d;
2155 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
2156 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
2157 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2159 R_Mesh_ResetTextureState();
2160 R_Mesh_ResetRenderTargets();
2161 R_Shadow_RenderMode_Reset();
2164 R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2165 R_SetupShader_DepthOrShadow();
2168 R_SetupShader_ShowDepth();
2169 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2174 R_SetViewport(&viewport);
2175 flipped = (side & 1) ^ (side >> 2);
2176 r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2177 r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2178 switch(vid.renderpath)
2180 case RENDERPATH_GL11:
2181 case RENDERPATH_GL13:
2182 case RENDERPATH_GL20:
2183 case RENDERPATH_SOFT:
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
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 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
2197 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2199 case RENDERPATH_D3D9:
2200 case RENDERPATH_D3D10:
2201 case RENDERPATH_D3D11:
2202 Vector4Set(clearcolor, 1,1,1,1);
2203 // completely different meaning than in OpenGL path
2204 r_shadow_shadowmap_parameters[1] = 0;
2205 r_shadow_shadowmap_parameters[3] = -bias;
2206 // we invert the cull mode because we flip the projection matrix
2207 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2208 GL_CullFace(r_refdef.view.cullface_front);
2209 // D3D considers it an error to use a scissor larger than the viewport... clear just this view
2210 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2211 if (r_shadow_shadowmapsampler)
2213 GL_ColorMask(0,0,0,0);
2215 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2219 GL_ColorMask(1,1,1,1);
2221 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2227 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2229 R_Mesh_ResetTextureState();
2230 R_Mesh_ResetRenderTargets();
2233 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2234 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2235 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2236 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2238 R_Shadow_RenderMode_Reset();
2239 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2241 GL_DepthFunc(GL_EQUAL);
2242 // do global setup needed for the chosen lighting mode
2243 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2244 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2245 r_shadow_usingshadowmap2d = shadowmapping;
2246 r_shadow_rendermode = r_shadow_lightingrendermode;
2247 // only draw light where this geometry was already rendered AND the
2248 // stencil is 128 (values other than this mean shadow)
2250 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2252 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2255 static const unsigned short bboxelements[36] =
2265 static const float bboxpoints[8][3] =
2277 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2280 float vertex3f[8*3];
2281 const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2282 // do global setup needed for the chosen lighting mode
2283 R_Shadow_RenderMode_Reset();
2284 r_shadow_rendermode = r_shadow_lightingrendermode;
2285 R_EntityMatrix(&identitymatrix);
2286 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2287 // only draw light where this geometry was already rendered AND the
2288 // stencil is 128 (values other than this mean shadow)
2289 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2290 if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2291 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2293 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2295 r_shadow_usingshadowmap2d = shadowmapping;
2297 // render the lighting
2298 R_SetupShader_DeferredLight(rsurface.rtlight);
2299 for (i = 0;i < 8;i++)
2300 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2301 GL_ColorMask(1,1,1,1);
2302 GL_DepthMask(false);
2303 GL_DepthRange(0, 1);
2304 GL_PolygonOffset(0, 0);
2306 GL_DepthFunc(GL_GREATER);
2307 GL_CullFace(r_refdef.view.cullface_back);
2308 R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2309 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2312 static void R_Shadow_UpdateBounceGridTexture(void)
2314 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2316 int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2318 int hitsupercontentsmask;
2327 //trace_t cliptrace2;
2328 //trace_t cliptrace3;
2329 unsigned char *pixel;
2330 unsigned char *pixels;
2333 unsigned int lightindex;
2335 unsigned int range1;
2336 unsigned int range2;
2337 unsigned int seed = (unsigned int)(realtime * 1000.0f);
2339 vec3_t baseshotcolor;
2352 vec_t lightintensity;
2353 vec_t photonscaling;
2354 vec_t photonresidual;
2356 float texlerp[2][3];
2357 float splatcolor[16];
2358 float pixelweight[8];
2365 r_shadow_bouncegrid_settings_t settings;
2366 qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2367 qboolean allowdirectionalshading = false;
2368 switch(vid.renderpath)
2370 case RENDERPATH_GL20:
2371 allowdirectionalshading = true;
2372 if (!vid.support.ext_texture_3d)
2375 case RENDERPATH_GLES2:
2376 // for performance reasons, do not use directional shading on GLES devices
2377 if (!vid.support.ext_texture_3d)
2380 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2381 case RENDERPATH_GL11:
2382 case RENDERPATH_GL13:
2383 case RENDERPATH_SOFT:
2384 case RENDERPATH_D3D9:
2385 case RENDERPATH_D3D10:
2386 case RENDERPATH_D3D11:
2390 r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2392 // see if there are really any lights to render...
2393 if (enable && r_shadow_bouncegrid_static.integer)
2396 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2397 for (lightindex = 0;lightindex < range;lightindex++)
2399 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2400 if (!light || !(light->flags & flag))
2402 rtlight = &light->rtlight;
2403 // when static, we skip styled lights because they tend to change...
2404 if (rtlight->style > 0)
2406 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2407 if (!VectorLength2(lightcolor))
2416 if (r_shadow_bouncegridtexture)
2418 R_FreeTexture(r_shadow_bouncegridtexture);
2419 r_shadow_bouncegridtexture = NULL;
2421 if (r_shadow_bouncegridpixels)
2422 Mem_Free(r_shadow_bouncegridpixels);
2423 r_shadow_bouncegridpixels = NULL;
2424 if (r_shadow_bouncegridhighpixels)
2425 Mem_Free(r_shadow_bouncegridhighpixels);
2426 r_shadow_bouncegridhighpixels = NULL;
2427 r_shadow_bouncegridnumpixels = 0;
2428 r_shadow_bouncegriddirectional = false;
2432 // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2433 memset(&settings, 0, sizeof(settings));
2434 settings.staticmode = r_shadow_bouncegrid_static.integer != 0;
2435 settings.bounceanglediffuse = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2436 settings.directionalshading = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2437 settings.dlightparticlemultiplier = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2438 settings.hitmodels = r_shadow_bouncegrid_hitmodels.integer != 0;
2439 settings.lightradiusscale = r_shadow_bouncegrid_lightradiusscale.value;
2440 settings.maxbounce = r_shadow_bouncegrid_maxbounce.integer;
2441 settings.particlebounceintensity = r_shadow_bouncegrid_particlebounceintensity.value;
2442 settings.particleintensity = r_shadow_bouncegrid_particleintensity.value;
2443 settings.photons = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2444 settings.spacing[0] = r_shadow_bouncegrid_spacingx.value;
2445 settings.spacing[1] = r_shadow_bouncegrid_spacingy.value;
2446 settings.spacing[2] = r_shadow_bouncegrid_spacingz.value;
2447 settings.stablerandom = r_shadow_bouncegrid_stablerandom.integer;
2449 // bound the values for sanity
2450 settings.photons = bound(1, settings.photons, 1048576);
2451 settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2452 settings.maxbounce = bound(1, settings.maxbounce, 16);
2453 settings.spacing[0] = bound(1, settings.spacing[0], 512);
2454 settings.spacing[1] = bound(1, settings.spacing[1], 512);
2455 settings.spacing[2] = bound(1, settings.spacing[2], 512);
2457 // get the spacing values
2458 spacing[0] = settings.spacing[0];
2459 spacing[1] = settings.spacing[1];
2460 spacing[2] = settings.spacing[2];
2461 ispacing[0] = 1.0f / spacing[0];
2462 ispacing[1] = 1.0f / spacing[1];
2463 ispacing[2] = 1.0f / spacing[2];
2465 // calculate texture size enclosing entire world bounds at the spacing
2466 VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2467 VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2468 VectorSubtract(maxs, mins, size);
2469 // now we can calculate the resolution we want
2470 c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2471 c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2472 c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2473 // figure out the exact texture size (honoring power of 2 if required)
2474 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2475 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2476 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2477 if (vid.support.arb_texture_non_power_of_two)
2479 resolution[0] = c[0];
2480 resolution[1] = c[1];
2481 resolution[2] = c[2];
2485 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2486 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2487 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2489 size[0] = spacing[0] * resolution[0];
2490 size[1] = spacing[1] * resolution[1];
2491 size[2] = spacing[2] * resolution[2];
2493 // if dynamic we may or may not want to use the world bounds
2494 // if the dynamic size is smaller than the world bounds, use it instead
2495 if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2497 // we know the resolution we want
2498 c[0] = r_shadow_bouncegrid_x.integer;
2499 c[1] = r_shadow_bouncegrid_y.integer;
2500 c[2] = r_shadow_bouncegrid_z.integer;
2501 // now we can calculate the texture size (power of 2 if required)
2502 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2503 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2504 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2505 if (vid.support.arb_texture_non_power_of_two)
2507 resolution[0] = c[0];
2508 resolution[1] = c[1];
2509 resolution[2] = c[2];
2513 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2514 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2515 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2517 size[0] = spacing[0] * resolution[0];
2518 size[1] = spacing[1] * resolution[1];
2519 size[2] = spacing[2] * resolution[2];
2520 // center the rendering on the view
2521 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2522 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2523 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2526 // recalculate the maxs in case the resolution was not satisfactory
2527 VectorAdd(mins, size, maxs);
2529 // if all the settings seem identical to the previous update, return
2530 if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2533 // store the new settings
2534 r_shadow_bouncegridsettings = settings;
2536 // we're going to update the bouncegrid, update the matrix...
2537 memset(m, 0, sizeof(m));
2538 m[0] = 1.0f / size[0];
2539 m[3] = -mins[0] * m[0];
2540 m[5] = 1.0f / size[1];
2541 m[7] = -mins[1] * m[5];
2542 m[10] = 1.0f / size[2];
2543 m[11] = -mins[2] * m[10];
2545 if (settings.directionalshading)
2550 Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2551 numpixels = resolution[0]*resolution[1]*resolution[2];
2552 if (settings.directionalshading)
2554 r_shadow_bouncegriddirectional = settings.directionalshading;
2555 // reallocate pixels for this update if needed...
2556 if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2558 if (r_shadow_bouncegridtexture)
2560 R_FreeTexture(r_shadow_bouncegridtexture);
2561 r_shadow_bouncegridtexture = NULL;
2563 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2564 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2566 r_shadow_bouncegridnumpixels = numpixels;
2567 pixels = r_shadow_bouncegridpixels;
2568 highpixels = r_shadow_bouncegridhighpixels;
2569 if (settings.directionalshading)
2570 memset(pixels, 128, numpixels * sizeof(unsigned char[4]));
2572 memset(pixels, 0, numpixels * sizeof(unsigned char[4]));
2573 memset(highpixels, 0, numpixels * sizeof(float[4]));
2574 // figure out what we want to interact with
2575 if (settings.hitmodels)
2576 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_LIQUIDSMASK;
2578 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_LIQUIDSMASK;
2579 maxbounce = settings.maxbounce;
2580 // clear variables that produce warnings otherwise
2581 memset(splatcolor, 0, sizeof(splatcolor));
2582 // iterate world rtlights
2583 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2584 range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2585 range2 = range + range1;
2587 for (lightindex = 0;lightindex < range2;lightindex++)
2589 if (settings.staticmode)
2591 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2592 if (!light || !(light->flags & flag))
2594 rtlight = &light->rtlight;
2595 // when static, we skip styled lights because they tend to change...
2596 if (rtlight->style > 0)
2598 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2602 if (lightindex < range)
2604 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2605 rtlight = &light->rtlight;
2608 rtlight = r_refdef.scene.lights[lightindex - range];
2609 // draw only visible lights (major speedup)
2612 VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2614 if (!VectorLength2(lightcolor))
2616 // shoot particles from this light
2617 // use a calculation for the number of particles that will not
2618 // vary with lightstyle, otherwise we get randomized particle
2619 // distribution, the seeded random is only consistent for a
2620 // consistent number of particles on this light...
2621 radius = rtlight->radius * settings.lightradiusscale;
2622 s = rtlight->radius;
2623 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2624 if (lightindex >= range)
2625 lightintensity *= settings.dlightparticlemultiplier;
2626 photoncount += max(0.0f, lightintensity * s * s);
2628 photonscaling = (float)settings.photons / max(1, photoncount);
2629 photonresidual = 0.0f;
2630 for (lightindex = 0;lightindex < range2;lightindex++)
2632 if (settings.staticmode)
2634 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2635 if (!light || !(light->flags & flag))
2637 rtlight = &light->rtlight;
2638 // when static, we skip styled lights because they tend to change...
2639 if (rtlight->style > 0)
2641 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2645 if (lightindex < range)
2647 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2648 rtlight = &light->rtlight;
2651 rtlight = r_refdef.scene.lights[lightindex - range];
2652 // draw only visible lights (major speedup)
2655 VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2657 if (!VectorLength2(lightcolor))
2659 // shoot particles from this light
2660 // use a calculation for the number of particles that will not
2661 // vary with lightstyle, otherwise we get randomized particle
2662 // distribution, the seeded random is only consistent for a
2663 // consistent number of particles on this light...
2664 radius = rtlight->radius * settings.lightradiusscale;
2665 s = rtlight->radius;
2666 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2667 if (lightindex >= range)
2668 lightintensity *= settings.dlightparticlemultiplier;
2669 photonresidual += lightintensity * s * s * photonscaling;
2670 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2671 if (!shootparticles)
2673 photonresidual -= shootparticles;
2674 s = settings.particleintensity / shootparticles;
2675 VectorScale(lightcolor, s, baseshotcolor);
2676 if (VectorLength2(baseshotcolor) == 0.0f)
2678 r_refdef.stats.bouncegrid_lights++;
2679 r_refdef.stats.bouncegrid_particles += shootparticles;
2680 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2682 if (settings.stablerandom > 0)
2683 seed = lightindex * 11937 + shotparticles;
2684 VectorCopy(baseshotcolor, shotcolor);
2685 VectorCopy(rtlight->shadoworigin, clipstart);
2686 if (settings.stablerandom < 0)
2687 VectorRandom(clipend);
2689 VectorCheeseRandom(clipend);
2690 VectorMA(clipstart, radius, clipend, clipend);
2691 for (bouncecount = 0;;bouncecount++)
2693 r_refdef.stats.bouncegrid_traces++;
2694 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2695 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2696 if (settings.staticmode)
2697 Collision_ClipLineToWorld(&cliptrace, cl.worldmodel, clipstart, clipend, hitsupercontentsmask, true);
2699 cliptrace = CL_TraceLine(clipstart, clipend, settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS, NULL, hitsupercontentsmask, true, false, NULL, true, true);
2700 if (cliptrace.fraction >= 1.0f)
2702 r_refdef.stats.bouncegrid_hits++;
2703 if (bouncecount > 0)
2705 r_refdef.stats.bouncegrid_splats++;
2706 // figure out which texture pixel this is in
2707 texlerp[1][0] = ((cliptrace.endpos[0] - mins[0]) * ispacing[0]);
2708 texlerp[1][1] = ((cliptrace.endpos[1] - mins[1]) * ispacing[1]);
2709 texlerp[1][2] = ((cliptrace.endpos[2] - mins[2]) * ispacing[2]);
2710 tex[0] = (int)floor(texlerp[1][0]);
2711 tex[1] = (int)floor(texlerp[1][1]);
2712 tex[2] = (int)floor(texlerp[1][2]);
2713 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)
2715 // it is within bounds... do the real work now
2716 // calculate first order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2717 if (settings.directionalshading)
2719 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2720 VectorNormalize(clipdiff);
2721 splatcolor[ 0] = shotcolor[0] * clipdiff[2];
2722 splatcolor[ 1] = shotcolor[0] * clipdiff[1];
2723 splatcolor[ 2] = shotcolor[0] * clipdiff[0];
2724 splatcolor[ 3] = shotcolor[0];
2725 splatcolor[ 4] = shotcolor[1] * clipdiff[2];
2726 splatcolor[ 5] = shotcolor[1] * clipdiff[1];
2727 splatcolor[ 6] = shotcolor[1] * clipdiff[0];
2728 splatcolor[ 7] = shotcolor[1];
2729 splatcolor[ 8] = shotcolor[2] * clipdiff[2];
2730 splatcolor[ 9] = shotcolor[2] * clipdiff[1];
2731 splatcolor[10] = shotcolor[2] * clipdiff[0];
2732 splatcolor[11] = shotcolor[2];
2733 w = VectorLength(shotcolor);
2734 splatcolor[12] = clipdiff[2] * w;
2735 splatcolor[13] = clipdiff[1] * w;
2736 splatcolor[14] = clipdiff[0] * w;
2737 splatcolor[15] = 1.0f;
2741 splatcolor[ 0] = shotcolor[2];
2742 splatcolor[ 1] = shotcolor[1];
2743 splatcolor[ 2] = shotcolor[0];
2744 splatcolor[ 3] = 1.0f;
2746 // calculate the lerp factors
2747 texlerp[1][0] -= tex[0];
2748 texlerp[1][1] -= tex[1];
2749 texlerp[1][2] -= tex[2];
2750 texlerp[0][0] = 1.0f - texlerp[1][0];
2751 texlerp[0][1] = 1.0f - texlerp[1][1];
2752 texlerp[0][2] = 1.0f - texlerp[1][2];
2753 // calculate individual pixel indexes and weights
2754 pixelindex[0] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2755 pixelindex[1] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2756 pixelindex[2] = (((tex[2] )*resolution[1]+tex[1]+1)*resolution[0]+tex[0] );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2757 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]);
2758 pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2759 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]);
2760 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]);
2761 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]);
2762 // update the 8 pixels...
2763 for (corner = 0;corner < 8;corner++)
2765 // calculate address for first set of coefficients
2766 w = pixelweight[corner];
2767 pixel = pixels + 4 * pixelindex[corner];
2768 highpixel = highpixels + 4 * pixelindex[corner];
2769 // add to the high precision pixel color
2770 highpixel[0] += (splatcolor[ 0]*w);
2771 highpixel[1] += (splatcolor[ 1]*w);
2772 highpixel[2] += (splatcolor[ 2]*w);
2773 highpixel[3] += (splatcolor[ 3]*w);
2774 // flag the low precision pixel as needing to be updated
2776 if (settings.directionalshading)
2778 // advance to second set of coefficients
2780 highpixel += numpixels;
2781 // add to the high precision pixel color
2782 highpixel[0] += (splatcolor[ 4]*w);
2783 highpixel[1] += (splatcolor[ 5]*w);
2784 highpixel[2] += (splatcolor[ 6]*w);
2785 highpixel[3] += (splatcolor[ 7]*w);
2786 // flag the low precision pixel as needing to be updated
2788 // advance to third set of coefficients
2790 highpixel += numpixels;
2791 // add to the high precision pixel color
2792 highpixel[0] += (splatcolor[ 8]*w);
2793 highpixel[1] += (splatcolor[ 9]*w);
2794 highpixel[2] += (splatcolor[10]*w);
2795 highpixel[3] += (splatcolor[11]*w);
2796 // flag the low precision pixel as needing to be updated
2798 // advance to fourth set of coefficients
2800 highpixel += numpixels;
2801 // add to the high precision pixel color
2802 highpixel[0] += (splatcolor[12]*w);
2803 highpixel[1] += (splatcolor[13]*w);
2804 highpixel[2] += (splatcolor[14]*w);
2805 highpixel[3] += (splatcolor[15]*w);
2806 // flag the low precision pixel as needing to be updated
2812 if (bouncecount >= maxbounce)
2814 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2815 // also clamp the resulting color to never add energy, even if the user requests extreme values
2816 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2817 VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2819 VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2820 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2821 surfcolor[0] = min(surfcolor[0], 1.0f);
2822 surfcolor[1] = min(surfcolor[1], 1.0f);
2823 surfcolor[2] = min(surfcolor[2], 1.0f);
2824 VectorMultiply(shotcolor, surfcolor, shotcolor);
2825 if (VectorLength2(baseshotcolor) == 0.0f)
2827 r_refdef.stats.bouncegrid_bounces++;
2828 if (settings.bounceanglediffuse)
2830 // random direction, primarily along plane normal
2831 s = VectorDistance(cliptrace.endpos, clipend);
2832 if (settings.stablerandom < 0)
2833 VectorRandom(clipend);
2835 VectorCheeseRandom(clipend);
2836 VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2837 VectorNormalize(clipend);
2838 VectorScale(clipend, s, clipend);
2842 // reflect the remaining portion of the line across plane normal
2843 VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2844 VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2846 // calculate the new line start and end
2847 VectorCopy(cliptrace.endpos, clipstart);
2848 VectorAdd(clipstart, clipend, clipend);
2852 // generate pixels array from highpixels array
2853 // skip first and last columns, rows, and layers as these are blank
2854 // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2855 for (d = 0;d < 4;d++)
2857 for (z = 1;z < resolution[2]-1;z++)
2859 for (y = 1;y < resolution[1]-1;y++)
2861 for (x = 1, pixelindex[0] = ((d*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 // only convert pixels that were hit by photons
2864 if (pixel[3] == 255)
2866 // normalize the bentnormal...
2867 if (settings.directionalshading)
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);
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);
2883 pixel[0] = (unsigned char)bound(0, c[0], 255);
2884 pixel[1] = (unsigned char)bound(0, c[1], 255);
2885 pixel[2] = (unsigned char)bound(0, c[2], 255);
2886 pixel[3] = (unsigned char)bound(0, c[3], 255);
2891 if (!settings.directionalshading)
2894 if (r_shadow_bouncegridtexture && r_shadow_bouncegridresolution[0] == resolution[0] && r_shadow_bouncegridresolution[1] == resolution[1] && r_shadow_bouncegridresolution[2] == resolution[2])
2895 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*(settings.directionalshading ? 4 : 1));
2898 VectorCopy(resolution, r_shadow_bouncegridresolution);
2899 if (r_shadow_bouncegridtexture)
2900 R_FreeTexture(r_shadow_bouncegridtexture);
2901 r_shadow_bouncegridtexture = R_LoadTexture3D(r_shadow_texturepool, "bouncegrid", resolution[0], resolution[1], resolution[2]*(settings.directionalshading ? 4 : 1), pixels, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, 0, NULL);
2903 r_shadow_bouncegridtime = realtime;
2906 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2908 R_Shadow_RenderMode_Reset();
2909 GL_BlendFunc(GL_ONE, GL_ONE);
2910 GL_DepthRange(0, 1);
2911 GL_DepthTest(r_showshadowvolumes.integer < 2);
2912 GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2913 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2914 GL_CullFace(GL_NONE);
2915 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2918 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2920 R_Shadow_RenderMode_Reset();
2921 GL_BlendFunc(GL_ONE, GL_ONE);
2922 GL_DepthRange(0, 1);
2923 GL_DepthTest(r_showlighting.integer < 2);
2924 GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2926 GL_DepthFunc(GL_EQUAL);
2927 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2928 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2931 void R_Shadow_RenderMode_End(void)
2933 R_Shadow_RenderMode_Reset();
2934 R_Shadow_RenderMode_ActiveLight(NULL);
2936 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2937 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2940 int bboxedges[12][2] =
2959 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2961 if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass)
2963 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2964 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2965 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2966 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2969 if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2970 return true; // invisible
2971 if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2972 || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2973 || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2974 || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2975 r_refdef.stats.lights_scissored++;
2979 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
2982 const float *vertex3f;
2983 const float *normal3f;
2985 float dist, dot, distintensity, shadeintensity, v[3], n[3];
2986 switch (r_shadow_rendermode)
2988 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
2989 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
2990 if (VectorLength2(diffusecolor) > 0)
2992 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)
2994 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
2995 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
2996 if ((dot = DotProduct(n, v)) < 0)
2998 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
2999 VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
3002 VectorCopy(ambientcolor, color4f);
3003 if (r_refdef.fogenabled)
3006 f = RSurf_FogVertex(vertex3f);
3007 VectorScale(color4f, f, color4f);
3014 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3016 VectorCopy(ambientcolor, color4f);
3017 if (r_refdef.fogenabled)
3020 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3021 f = RSurf_FogVertex(vertex3f);
3022 VectorScale(color4f + 4*i, f, color4f);
3028 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3029 if (VectorLength2(diffusecolor) > 0)
3031 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)
3033 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3034 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3036 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3037 if ((dot = DotProduct(n, v)) < 0)
3039 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3040 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3041 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3042 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3046 color4f[0] = ambientcolor[0] * distintensity;
3047 color4f[1] = ambientcolor[1] * distintensity;
3048 color4f[2] = ambientcolor[2] * distintensity;
3050 if (r_refdef.fogenabled)
3053 f = RSurf_FogVertex(vertex3f);
3054 VectorScale(color4f, f, color4f);
3058 VectorClear(color4f);
3064 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3066 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3067 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3069 color4f[0] = ambientcolor[0] * distintensity;
3070 color4f[1] = ambientcolor[1] * distintensity;
3071 color4f[2] = ambientcolor[2] * distintensity;
3072 if (r_refdef.fogenabled)
3075 f = RSurf_FogVertex(vertex3f);
3076 VectorScale(color4f, f, color4f);
3080 VectorClear(color4f);
3085 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3086 if (VectorLength2(diffusecolor) > 0)
3088 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)
3090 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3091 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3093 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3094 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3095 if ((dot = DotProduct(n, v)) < 0)
3097 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3098 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3099 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3100 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3104 color4f[0] = ambientcolor[0] * distintensity;
3105 color4f[1] = ambientcolor[1] * distintensity;
3106 color4f[2] = ambientcolor[2] * distintensity;
3108 if (r_refdef.fogenabled)
3111 f = RSurf_FogVertex(vertex3f);
3112 VectorScale(color4f, f, color4f);
3116 VectorClear(color4f);
3122 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3124 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3125 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3127 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3128 color4f[0] = ambientcolor[0] * distintensity;
3129 color4f[1] = ambientcolor[1] * distintensity;
3130 color4f[2] = ambientcolor[2] * distintensity;
3131 if (r_refdef.fogenabled)
3134 f = RSurf_FogVertex(vertex3f);
3135 VectorScale(color4f, f, color4f);
3139 VectorClear(color4f);
3149 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3151 // used to display how many times a surface is lit for level design purposes
3152 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3153 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3157 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3159 // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3160 R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL);
3161 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3162 GL_DepthFunc(GL_EQUAL);
3164 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3165 GL_DepthFunc(GL_LEQUAL);
3168 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3175 int newnumtriangles;
3179 int maxtriangles = 4096;
3180 static int newelements[4096*3];
3181 R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3182 for (renders = 0;renders < 4;renders++)
3187 newnumtriangles = 0;
3189 // due to low fillrate on the cards this vertex lighting path is
3190 // designed for, we manually cull all triangles that do not
3191 // contain a lit vertex
3192 // this builds batches of triangles from multiple surfaces and
3193 // renders them at once
3194 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3196 if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3198 if (newnumtriangles)
3200 newfirstvertex = min(newfirstvertex, e[0]);
3201 newlastvertex = max(newlastvertex, e[0]);
3205 newfirstvertex = e[0];
3206 newlastvertex = e[0];
3208 newfirstvertex = min(newfirstvertex, e[1]);
3209 newlastvertex = max(newlastvertex, e[1]);
3210 newfirstvertex = min(newfirstvertex, e[2]);
3211 newlastvertex = max(newlastvertex, e[2]);
3217 if (newnumtriangles >= maxtriangles)
3219 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3220 newnumtriangles = 0;
3226 if (newnumtriangles >= 1)
3228 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3231 // if we couldn't find any lit triangles, exit early
3234 // now reduce the intensity for the next overbright pass
3235 // we have to clamp to 0 here incase the drivers have improper
3236 // handling of negative colors
3237 // (some old drivers even have improper handling of >1 color)
3239 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3241 if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3243 c[0] = max(0, c[0] - 1);
3244 c[1] = max(0, c[1] - 1);
3245 c[2] = max(0, c[2] - 1);
3257 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3259 // OpenGL 1.1 path (anything)
3260 float ambientcolorbase[3], diffusecolorbase[3];
3261 float ambientcolorpants[3], diffusecolorpants[3];
3262 float ambientcolorshirt[3], diffusecolorshirt[3];
3263 const float *surfacecolor = rsurface.texture->dlightcolor;
3264 const float *surfacepants = rsurface.colormap_pantscolor;
3265 const float *surfaceshirt = rsurface.colormap_shirtcolor;
3266 rtexture_t *basetexture = rsurface.texture->basetexture;
3267 rtexture_t *pantstexture = rsurface.texture->pantstexture;
3268 rtexture_t *shirttexture = rsurface.texture->shirttexture;
3269 qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3270 qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3271 ambientscale *= 2 * r_refdef.view.colorscale;
3272 diffusescale *= 2 * r_refdef.view.colorscale;
3273 ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3274 diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3275 ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3276 diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3277 ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3278 diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3279 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3280 rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3281 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3282 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3283 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3284 R_Mesh_TexBind(0, basetexture);
3285 R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3286 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3287 switch(r_shadow_rendermode)
3289 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3290 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3291 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3292 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3293 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3295 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3296 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3297 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3298 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3299 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3301 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3302 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3303 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3304 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3305 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3307 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3312 //R_Mesh_TexBind(0, basetexture);
3313 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3316 R_Mesh_TexBind(0, pantstexture);
3317 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3321 R_Mesh_TexBind(0, shirttexture);
3322 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3326 extern cvar_t gl_lightmaps;
3327 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3329 float ambientscale, diffusescale, specularscale;
3331 float lightcolor[3];
3332 VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3333 ambientscale = rsurface.rtlight->ambientscale;
3334 diffusescale = rsurface.rtlight->diffusescale;
3335 specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3336 if (!r_shadow_usenormalmap.integer)
3338 ambientscale += 1.0f * diffusescale;
3342 if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3344 negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3347 VectorNegate(lightcolor, lightcolor);
3348 switch(vid.renderpath)
3350 case RENDERPATH_GL11:
3351 case RENDERPATH_GL13:
3352 case RENDERPATH_GL20:
3353 case RENDERPATH_GLES2:
3354 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
3356 case RENDERPATH_D3D9:
3358 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
3361 case RENDERPATH_D3D10:
3362 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3364 case RENDERPATH_D3D11:
3365 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3367 case RENDERPATH_SOFT:
3368 DPSOFTRAST_BlendSubtract(true);
3372 RSurf_SetupDepthAndCulling();
3373 switch (r_shadow_rendermode)
3375 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3376 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3377 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3379 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3380 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3382 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3383 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3384 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3385 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3386 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3389 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3394 switch(vid.renderpath)
3396 case RENDERPATH_GL11:
3397 case RENDERPATH_GL13:
3398 case RENDERPATH_GL20:
3399 case RENDERPATH_GLES2:
3400 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
3402 case RENDERPATH_D3D9:
3404 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
3407 case RENDERPATH_D3D10:
3408 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3410 case RENDERPATH_D3D11:
3411 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3413 case RENDERPATH_SOFT:
3414 DPSOFTRAST_BlendSubtract(false);
3420 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)
3422 matrix4x4_t tempmatrix = *matrix;
3423 Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3425 // if this light has been compiled before, free the associated data
3426 R_RTLight_Uncompile(rtlight);
3428 // clear it completely to avoid any lingering data
3429 memset(rtlight, 0, sizeof(*rtlight));
3431 // copy the properties
3432 rtlight->matrix_lighttoworld = tempmatrix;
3433 Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3434 Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3435 rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3436 VectorCopy(color, rtlight->color);
3437 rtlight->cubemapname[0] = 0;
3438 if (cubemapname && cubemapname[0])
3439 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3440 rtlight->shadow = shadow;
3441 rtlight->corona = corona;
3442 rtlight->style = style;
3443 rtlight->isstatic = isstatic;
3444 rtlight->coronasizescale = coronasizescale;
3445 rtlight->ambientscale = ambientscale;
3446 rtlight->diffusescale = diffusescale;
3447 rtlight->specularscale = specularscale;
3448 rtlight->flags = flags;
3450 // compute derived data
3451 //rtlight->cullradius = rtlight->radius;
3452 //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3453 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3454 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3455 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3456 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3457 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3458 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3461 // compiles rtlight geometry
3462 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3463 void R_RTLight_Compile(rtlight_t *rtlight)
3466 int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3467 int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3468 entity_render_t *ent = r_refdef.scene.worldentity;
3469 dp_model_t *model = r_refdef.scene.worldmodel;
3470 unsigned char *data;
3473 // compile the light
3474 rtlight->compiled = true;
3475 rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3476 rtlight->static_numleafs = 0;
3477 rtlight->static_numleafpvsbytes = 0;
3478 rtlight->static_leaflist = NULL;
3479 rtlight->static_leafpvs = NULL;
3480 rtlight->static_numsurfaces = 0;
3481 rtlight->static_surfacelist = NULL;
3482 rtlight->static_shadowmap_receivers = 0x3F;
3483 rtlight->static_shadowmap_casters = 0x3F;
3484 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3485 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3486 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3487 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3488 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3489 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3491 if (model && model->GetLightInfo)
3493 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3494 r_shadow_compilingrtlight = rtlight;
3495 R_FrameData_SetMark();
3496 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);
3497 R_FrameData_ReturnToMark();
3498 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3499 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3500 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3501 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3502 rtlight->static_numsurfaces = numsurfaces;
3503 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3504 rtlight->static_numleafs = numleafs;
3505 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3506 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3507 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3508 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3509 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3510 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3511 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3512 if (rtlight->static_numsurfaces)
3513 memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3514 if (rtlight->static_numleafs)
3515 memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3516 if (rtlight->static_numleafpvsbytes)
3517 memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3518 if (rtlight->static_numshadowtrispvsbytes)
3519 memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3520 if (rtlight->static_numlighttrispvsbytes)
3521 memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3522 R_FrameData_SetMark();
3523 switch (rtlight->shadowmode)
3525 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3526 if (model->CompileShadowMap && rtlight->shadow)
3527 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3530 if (model->CompileShadowVolume && rtlight->shadow)
3531 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3534 R_FrameData_ReturnToMark();
3535 // now we're done compiling the rtlight
3536 r_shadow_compilingrtlight = NULL;
3540 // use smallest available cullradius - box radius or light radius
3541 //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3542 //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3544 shadowzpasstris = 0;
3545 if (rtlight->static_meshchain_shadow_zpass)
3546 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3547 shadowzpasstris += mesh->numtriangles;
3549 shadowzfailtris = 0;
3550 if (rtlight->static_meshchain_shadow_zfail)
3551 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3552 shadowzfailtris += mesh->numtriangles;
3555 if (rtlight->static_numlighttrispvsbytes)
3556 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3557 if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3561 if (rtlight->static_numlighttrispvsbytes)
3562 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3563 if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3566 if (developer_extra.integer)
3567 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);
3570 void R_RTLight_Uncompile(rtlight_t *rtlight)
3572 if (rtlight->compiled)
3574 if (rtlight->static_meshchain_shadow_zpass)
3575 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3576 rtlight->static_meshchain_shadow_zpass = NULL;
3577 if (rtlight->static_meshchain_shadow_zfail)
3578 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3579 rtlight->static_meshchain_shadow_zfail = NULL;
3580 if (rtlight->static_meshchain_shadow_shadowmap)
3581 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3582 rtlight->static_meshchain_shadow_shadowmap = NULL;
3583 // these allocations are grouped
3584 if (rtlight->static_surfacelist)
3585 Mem_Free(rtlight->static_surfacelist);
3586 rtlight->static_numleafs = 0;
3587 rtlight->static_numleafpvsbytes = 0;
3588 rtlight->static_leaflist = NULL;
3589 rtlight->static_leafpvs = NULL;
3590 rtlight->static_numsurfaces = 0;
3591 rtlight->static_surfacelist = NULL;
3592 rtlight->static_numshadowtrispvsbytes = 0;
3593 rtlight->static_shadowtrispvs = NULL;
3594 rtlight->static_numlighttrispvsbytes = 0;
3595 rtlight->static_lighttrispvs = NULL;
3596 rtlight->compiled = false;
3600 void R_Shadow_UncompileWorldLights(void)
3604 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3605 for (lightindex = 0;lightindex < range;lightindex++)
3607 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3610 R_RTLight_Uncompile(&light->rtlight);
3614 void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3618 // reset the count of frustum planes
3619 // see rtlight->cached_frustumplanes definition for how much this array
3621 rtlight->cached_numfrustumplanes = 0;
3623 // haven't implemented a culling path for ortho rendering
3624 if (!r_refdef.view.useperspective)
3626 // check if the light is on screen and copy the 4 planes if it is
3627 for (i = 0;i < 4;i++)
3628 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3631 for (i = 0;i < 4;i++)
3632 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3637 // generate a deformed frustum that includes the light origin, this is
3638 // used to cull shadow casting surfaces that can not possibly cast a
3639 // shadow onto the visible light-receiving surfaces, which can be a
3642 // if the light origin is onscreen the result will be 4 planes exactly
3643 // if the light origin is offscreen on only one axis the result will
3644 // be exactly 5 planes (split-side case)
3645 // if the light origin is offscreen on two axes the result will be
3646 // exactly 4 planes (stretched corner case)
3647 for (i = 0;i < 4;i++)
3649 // quickly reject standard frustum planes that put the light
3650 // origin outside the frustum
3651 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3654 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3656 // if all the standard frustum planes were accepted, the light is onscreen
3657 // otherwise we need to generate some more planes below...
3658 if (rtlight->cached_numfrustumplanes < 4)
3660 // at least one of the stock frustum planes failed, so we need to
3661 // create one or two custom planes to enclose the light origin
3662 for (i = 0;i < 4;i++)
3664 // create a plane using the view origin and light origin, and a
3665 // single point from the frustum corner set
3666 TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3667 VectorNormalize(plane.normal);
3668 plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3669 // see if this plane is backwards and flip it if so
3670 for (j = 0;j < 4;j++)
3671 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3675 VectorNegate(plane.normal, plane.normal);
3677 // flipped plane, test again to see if it is now valid
3678 for (j = 0;j < 4;j++)
3679 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3681 // if the plane is still not valid, then it is dividing the
3682 // frustum and has to be rejected
3686 // we have created a valid plane, compute extra info
3687 PlaneClassify(&plane);
3689 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3691 // if we've found 5 frustum planes then we have constructed a
3692 // proper split-side case and do not need to keep searching for
3693 // planes to enclose the light origin
3694 if (rtlight->cached_numfrustumplanes == 5)
3702 for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3704 plane = rtlight->cached_frustumplanes[i];
3705 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));
3710 // now add the light-space box planes if the light box is rotated, as any
3711 // caster outside the oriented light box is irrelevant (even if it passed
3712 // the worldspace light box, which is axial)
3713 if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3715 for (i = 0;i < 6;i++)
3719 v[i >> 1] = (i & 1) ? -1 : 1;
3720 Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3721 VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3722 plane.dist = VectorNormalizeLength(plane.normal);
3723 plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3724 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3730 // add the world-space reduced box planes
3731 for (i = 0;i < 6;i++)
3733 VectorClear(plane.normal);
3734 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3735 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3736 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3745 // reduce all plane distances to tightly fit the rtlight cull box, which
3747 VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3748 VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3749 VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3750 VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3751 VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3752 VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3753 VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3754 VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3755 oldnum = rtlight->cached_numfrustumplanes;
3756 rtlight->cached_numfrustumplanes = 0;
3757 for (j = 0;j < oldnum;j++)
3759 // find the nearest point on the box to this plane
3760 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3761 for (i = 1;i < 8;i++)
3763 dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3764 if (bestdist > dist)
3767 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);
3768 // if the nearest point is near or behind the plane, we want this
3769 // plane, otherwise the plane is useless as it won't cull anything
3770 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3772 PlaneClassify(&rtlight->cached_frustumplanes[j]);
3773 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3780 void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3784 RSurf_ActiveWorldEntity();
3786 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3789 GL_CullFace(GL_NONE);
3790 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3791 for (;mesh;mesh = mesh->next)
3793 if (!mesh->sidetotals[r_shadow_shadowmapside])
3795 r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside];
3796 if (mesh->vertex3fbuffer)
3797 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3799 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3800 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);
3804 else if (r_refdef.scene.worldentity->model)
3805 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);
3807 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3810 void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3812 qboolean zpass = false;
3815 int surfacelistindex;
3816 msurface_t *surface;
3818 // if triangle neighbors are disabled, shadowvolumes are disabled
3819 if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3822 RSurf_ActiveWorldEntity();
3824 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3827 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3829 zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3830 R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3832 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3833 for (;mesh;mesh = mesh->next)
3835 r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3836 if (mesh->vertex3fbuffer)
3837 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3839 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3840 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3842 // increment stencil if frontface is infront of depthbuffer
3843 GL_CullFace(r_refdef.view.cullface_back);
3844 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3845 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);
3846 // decrement stencil if backface is infront of depthbuffer
3847 GL_CullFace(r_refdef.view.cullface_front);
3848 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3850 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3852 // decrement stencil if backface is behind depthbuffer
3853 GL_CullFace(r_refdef.view.cullface_front);
3854 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3855 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);
3856 // increment stencil if frontface is behind depthbuffer
3857 GL_CullFace(r_refdef.view.cullface_back);
3858 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3860 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);
3864 else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3866 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3867 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3868 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3870 surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3871 for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3872 if (CHECKPVSBIT(trispvs, t))
3873 shadowmarklist[numshadowmark++] = t;
3875 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);
3877 else if (numsurfaces)
3879 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);
3882 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3885 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3887 vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3888 vec_t relativeshadowradius;
3889 RSurf_ActiveModelEntity(ent, false, false, false);
3890 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3891 // we need to re-init the shader for each entity because the matrix changed
3892 relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3893 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3894 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3895 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3896 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3897 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3898 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3899 switch (r_shadow_rendermode)
3901 case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3902 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3905 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3908 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3911 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3913 // set up properties for rendering light onto this entity
3914 RSurf_ActiveModelEntity(ent, true, true, false);
3915 Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3916 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3917 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3918 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3921 void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3923 if (!r_refdef.scene.worldmodel->DrawLight)
3926 // set up properties for rendering light onto this entity
3927 RSurf_ActiveWorldEntity();
3928 rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3929 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3930 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3931 VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3933 r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3935 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3938 void R_Shadow_DrawEntityLight(entity_render_t *ent)
3940 dp_model_t *model = ent->model;
3941 if (!model->DrawLight)
3944 R_Shadow_SetupEntityLight(ent);
3946 model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3948 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3951 void R_Shadow_PrepareLight(rtlight_t *rtlight)
3955 int numleafs, numsurfaces;
3956 int *leaflist, *surfacelist;
3957 unsigned char *leafpvs;
3958 unsigned char *shadowtrispvs;
3959 unsigned char *lighttrispvs;
3960 //unsigned char *surfacesides;
3961 int numlightentities;
3962 int numlightentities_noselfshadow;
3963 int numshadowentities;
3964 int numshadowentities_noselfshadow;
3965 static entity_render_t *lightentities[MAX_EDICTS];
3966 static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3967 static entity_render_t *shadowentities[MAX_EDICTS];
3968 static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3971 rtlight->draw = false;
3973 // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3974 // skip lights that are basically invisible (color 0 0 0)
3975 nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3977 // loading is done before visibility checks because loading should happen
3978 // all at once at the start of a level, not when it stalls gameplay.
3979 // (especially important to benchmarks)
3981 if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3983 if (rtlight->compiled)
3984 R_RTLight_Uncompile(rtlight);
3985 R_RTLight_Compile(rtlight);
3989 rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
3991 // look up the light style value at this time
3992 f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
3993 VectorScale(rtlight->color, f, rtlight->currentcolor);
3995 if (rtlight->selected)
3997 f = 2 + sin(realtime * M_PI * 4.0);
3998 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
4002 // if lightstyle is currently off, don't draw the light
4003 if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
4006 // skip processing on corona-only lights
4010 // if the light box is offscreen, skip it
4011 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
4014 VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
4015 VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
4017 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4019 if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
4021 // compiled light, world available and can receive realtime lighting
4022 // retrieve leaf information
4023 numleafs = rtlight->static_numleafs;
4024 leaflist = rtlight->static_leaflist;
4025 leafpvs = rtlight->static_leafpvs;
4026 numsurfaces = rtlight->static_numsurfaces;
4027 surfacelist = rtlight->static_surfacelist;
4028 //surfacesides = NULL;
4029 shadowtrispvs = rtlight->static_shadowtrispvs;
4030 lighttrispvs = rtlight->static_lighttrispvs;
4032 else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4034 // dynamic light, world available and can receive realtime lighting
4035 // calculate lit surfaces and leafs
4036 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);
4037 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4038 leaflist = r_shadow_buffer_leaflist;
4039 leafpvs = r_shadow_buffer_leafpvs;
4040 surfacelist = r_shadow_buffer_surfacelist;
4041 //surfacesides = r_shadow_buffer_surfacesides;
4042 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4043 lighttrispvs = r_shadow_buffer_lighttrispvs;
4044 // if the reduced leaf bounds are offscreen, skip it
4045 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4056 //surfacesides = NULL;
4057 shadowtrispvs = NULL;
4058 lighttrispvs = NULL;
4060 // check if light is illuminating any visible leafs
4063 for (i = 0;i < numleafs;i++)
4064 if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4070 // make a list of lit entities and shadow casting entities
4071 numlightentities = 0;
4072 numlightentities_noselfshadow = 0;
4073 numshadowentities = 0;
4074 numshadowentities_noselfshadow = 0;
4076 // add dynamic entities that are lit by the light
4077 for (i = 0;i < r_refdef.scene.numentities;i++)
4080 entity_render_t *ent = r_refdef.scene.entities[i];
4082 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4084 // skip the object entirely if it is not within the valid
4085 // shadow-casting region (which includes the lit region)
4086 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4088 if (!(model = ent->model))
4090 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4092 // this entity wants to receive light, is visible, and is
4093 // inside the light box
4094 // TODO: check if the surfaces in the model can receive light
4095 // so now check if it's in a leaf seen by the light
4096 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))
4098 if (ent->flags & RENDER_NOSELFSHADOW)
4099 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4101 lightentities[numlightentities++] = ent;
4102 // since it is lit, it probably also casts a shadow...
4103 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4104 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4105 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4107 // note: exterior models without the RENDER_NOSELFSHADOW
4108 // flag still create a RENDER_NOSELFSHADOW shadow but
4109 // are lit normally, this means that they are
4110 // self-shadowing but do not shadow other
4111 // RENDER_NOSELFSHADOW entities such as the gun
4112 // (very weird, but keeps the player shadow off the gun)
4113 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4114 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4116 shadowentities[numshadowentities++] = ent;
4119 else if (ent->flags & RENDER_SHADOW)
4121 // this entity is not receiving light, but may still need to
4123 // TODO: check if the surfaces in the model can cast shadow
4124 // now check if it is in a leaf seen by the light
4125 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))
4127 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4128 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4129 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4131 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4132 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4134 shadowentities[numshadowentities++] = ent;
4139 // return if there's nothing at all to light
4140 if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4143 // count this light in the r_speeds
4144 r_refdef.stats.lights++;
4146 // flag it as worth drawing later
4147 rtlight->draw = true;
4149 // cache all the animated entities that cast a shadow but are not visible
4150 for (i = 0;i < numshadowentities;i++)
4151 if (!shadowentities[i]->animcache_vertex3f)
4152 R_AnimCache_GetEntity(shadowentities[i], false, false);
4153 for (i = 0;i < numshadowentities_noselfshadow;i++)
4154 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4155 R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4157 // allocate some temporary memory for rendering this light later in the frame
4158 // reusable buffers need to be copied, static data can be used as-is
4159 rtlight->cached_numlightentities = numlightentities;
4160 rtlight->cached_numlightentities_noselfshadow = numlightentities_noselfshadow;
4161 rtlight->cached_numshadowentities = numshadowentities;
4162 rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4163 rtlight->cached_numsurfaces = numsurfaces;
4164 rtlight->cached_lightentities = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4165 rtlight->cached_lightentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4166 rtlight->cached_shadowentities = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4167 rtlight->cached_shadowentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4168 if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4170 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4171 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4172 rtlight->cached_shadowtrispvs = (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4173 rtlight->cached_lighttrispvs = (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4174 rtlight->cached_surfacelist = (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4178 // compiled light data
4179 rtlight->cached_shadowtrispvs = shadowtrispvs;
4180 rtlight->cached_lighttrispvs = lighttrispvs;
4181 rtlight->cached_surfacelist = surfacelist;
4185 void R_Shadow_DrawLight(rtlight_t *rtlight)
4189 unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4190 int numlightentities;
4191 int numlightentities_noselfshadow;
4192 int numshadowentities;
4193 int numshadowentities_noselfshadow;
4194 entity_render_t **lightentities;
4195 entity_render_t **lightentities_noselfshadow;
4196 entity_render_t **shadowentities;
4197 entity_render_t **shadowentities_noselfshadow;
4199 static unsigned char entitysides[MAX_EDICTS];
4200 static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4201 vec3_t nearestpoint;
4203 qboolean castshadows;
4206 // check if we cached this light this frame (meaning it is worth drawing)
4210 numlightentities = rtlight->cached_numlightentities;
4211 numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4212 numshadowentities = rtlight->cached_numshadowentities;
4213 numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4214 numsurfaces = rtlight->cached_numsurfaces;
4215 lightentities = rtlight->cached_lightentities;
4216 lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4217 shadowentities = rtlight->cached_shadowentities;
4218 shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4219 shadowtrispvs = rtlight->cached_shadowtrispvs;
4220 lighttrispvs = rtlight->cached_lighttrispvs;
4221 surfacelist = rtlight->cached_surfacelist;
4223 // set up a scissor rectangle for this light
4224 if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4227 // don't let sound skip if going slow
4228 if (r_refdef.scene.extraupdate)
4231 // make this the active rtlight for rendering purposes
4232 R_Shadow_RenderMode_ActiveLight(rtlight);
4234 if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4236 // optionally draw visible shape of the shadow volumes
4237 // for performance analysis by level designers
4238 R_Shadow_RenderMode_VisibleShadowVolumes();
4240 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4241 for (i = 0;i < numshadowentities;i++)
4242 R_Shadow_DrawEntityShadow(shadowentities[i]);
4243 for (i = 0;i < numshadowentities_noselfshadow;i++)
4244 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4245 R_Shadow_RenderMode_VisibleLighting(false, false);
4248 if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4250 // optionally draw the illuminated areas
4251 // for performance analysis by level designers
4252 R_Shadow_RenderMode_VisibleLighting(false, false);
4254 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4255 for (i = 0;i < numlightentities;i++)
4256 R_Shadow_DrawEntityLight(lightentities[i]);
4257 for (i = 0;i < numlightentities_noselfshadow;i++)
4258 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4261 castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4263 nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4264 nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4265 nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4266 distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4268 lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4269 //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4270 lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4272 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4278 int receivermask = 0;
4279 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4280 Matrix4x4_Abs(&radiustolight);
4282 r_shadow_shadowmaplod = 0;
4283 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4284 if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4285 r_shadow_shadowmaplod = i;
4287 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4289 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4291 surfacesides = NULL;
4294 if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4296 castermask = rtlight->static_shadowmap_casters;
4297 receivermask = rtlight->static_shadowmap_receivers;
4301 surfacesides = r_shadow_buffer_surfacesides;
4302 for(i = 0;i < numsurfaces;i++)
4304 msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4305 surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4306 castermask |= surfacesides[i];
4307 receivermask |= surfacesides[i];
4311 if (receivermask < 0x3F)
4313 for (i = 0;i < numlightentities;i++)
4314 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4315 if (receivermask < 0x3F)
4316 for(i = 0; i < numlightentities_noselfshadow;i++)
4317 receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4320 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4324 for (i = 0;i < numshadowentities;i++)
4325 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4326 for (i = 0;i < numshadowentities_noselfshadow;i++)
4327 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4330 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4332 // render shadow casters into 6 sided depth texture
4333 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4335 R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4336 if (! (castermask & (1 << side))) continue;
4338 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4339 for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4340 R_Shadow_DrawEntityShadow(shadowentities[i]);
4343 if (numlightentities_noselfshadow)
4345 // render lighting using the depth texture as shadowmap
4346 // draw lighting in the unmasked areas
4347 R_Shadow_RenderMode_Lighting(false, false, true);
4348 for (i = 0;i < numlightentities_noselfshadow;i++)
4349 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4352 // render shadow casters into 6 sided depth texture
4353 if (numshadowentities_noselfshadow)
4355 for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4357 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4358 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4359 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4363 // render lighting using the depth texture as shadowmap
4364 // draw lighting in the unmasked areas
4365 R_Shadow_RenderMode_Lighting(false, false, true);
4366 // draw lighting in the unmasked areas
4368 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4369 for (i = 0;i < numlightentities;i++)
4370 R_Shadow_DrawEntityLight(lightentities[i]);
4372 else if (castshadows && vid.stencil)
4374 // draw stencil shadow volumes to mask off pixels that are in shadow
4375 // so that they won't receive lighting
4376 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4377 R_Shadow_ClearStencil();
4380 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4381 for (i = 0;i < numshadowentities;i++)
4382 R_Shadow_DrawEntityShadow(shadowentities[i]);
4384 // draw lighting in the unmasked areas
4385 R_Shadow_RenderMode_Lighting(true, false, false);
4386 for (i = 0;i < numlightentities_noselfshadow;i++)
4387 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4389 for (i = 0;i < numshadowentities_noselfshadow;i++)
4390 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4392 // draw lighting in the unmasked areas
4393 R_Shadow_RenderMode_Lighting(true, false, false);
4395 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4396 for (i = 0;i < numlightentities;i++)
4397 R_Shadow_DrawEntityLight(lightentities[i]);
4401 // draw lighting in the unmasked areas
4402 R_Shadow_RenderMode_Lighting(false, false, false);
4404 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4405 for (i = 0;i < numlightentities;i++)
4406 R_Shadow_DrawEntityLight(lightentities[i]);
4407 for (i = 0;i < numlightentities_noselfshadow;i++)
4408 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4411 if (r_shadow_usingdeferredprepass)
4413 // when rendering deferred lighting, we simply rasterize the box
4414 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4415 R_Shadow_RenderMode_DrawDeferredLight(false, true);
4416 else if (castshadows && vid.stencil)
4417 R_Shadow_RenderMode_DrawDeferredLight(true, false);
4419 R_Shadow_RenderMode_DrawDeferredLight(false, false);
4423 static void R_Shadow_FreeDeferred(void)
4425 R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4426 r_shadow_prepassgeometryfbo = 0;
4428 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4429 r_shadow_prepasslightingdiffusespecularfbo = 0;
4431 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4432 r_shadow_prepasslightingdiffusefbo = 0;
4434 if (r_shadow_prepassgeometrydepthtexture)
4435 R_FreeTexture(r_shadow_prepassgeometrydepthtexture);
4436 r_shadow_prepassgeometrydepthtexture = NULL;
4438 if (r_shadow_prepassgeometrydepthcolortexture)
4439 R_FreeTexture(r_shadow_prepassgeometrydepthcolortexture);
4440 r_shadow_prepassgeometrydepthcolortexture = NULL;
4442 if (r_shadow_prepassgeometrynormalmaptexture)
4443 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4444 r_shadow_prepassgeometrynormalmaptexture = NULL;
4446 if (r_shadow_prepasslightingdiffusetexture)
4447 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4448 r_shadow_prepasslightingdiffusetexture = NULL;
4450 if (r_shadow_prepasslightingspeculartexture)
4451 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4452 r_shadow_prepasslightingspeculartexture = NULL;
4455 void R_Shadow_DrawPrepass(void)
4463 entity_render_t *ent;
4464 float clearcolor[4];
4466 R_Mesh_ResetTextureState();
4468 GL_ColorMask(1,1,1,1);
4469 GL_BlendFunc(GL_ONE, GL_ZERO);
4472 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4473 Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4474 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4475 if (r_timereport_active)
4476 R_TimeReport("prepasscleargeom");
4478 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4479 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4480 if (r_timereport_active)
4481 R_TimeReport("prepassworld");
4483 for (i = 0;i < r_refdef.scene.numentities;i++)
4485 if (!r_refdef.viewcache.entityvisible[i])
4487 ent = r_refdef.scene.entities[i];
4488 if (ent->model && ent->model->DrawPrepass != NULL)
4489 ent->model->DrawPrepass(ent);
4492 if (r_timereport_active)
4493 R_TimeReport("prepassmodels");
4495 GL_DepthMask(false);
4496 GL_ColorMask(1,1,1,1);
4499 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4500 Vector4Set(clearcolor, 0, 0, 0, 0);
4501 GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4502 if (r_timereport_active)
4503 R_TimeReport("prepassclearlit");
4505 R_Shadow_RenderMode_Begin();
4507 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4508 if (r_shadow_debuglight.integer >= 0)
4510 lightindex = r_shadow_debuglight.integer;
4511 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4512 if (light && (light->flags & flag) && light->rtlight.draw)
4513 R_Shadow_DrawLight(&light->rtlight);
4517 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4518 for (lightindex = 0;lightindex < range;lightindex++)
4520 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4521 if (light && (light->flags & flag) && light->rtlight.draw)
4522 R_Shadow_DrawLight(&light->rtlight);
4525 if (r_refdef.scene.rtdlight)
4526 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4527 if (r_refdef.scene.lights[lnum]->draw)
4528 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4530 R_Mesh_ResetRenderTargets();
4532 R_Shadow_RenderMode_End();
4534 if (r_timereport_active)
4535 R_TimeReport("prepasslights");
4538 void R_Shadow_DrawLightSprites(void);
4539 void R_Shadow_PrepareLights(void)
4549 if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4550 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4551 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) ||
4552 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer ||
4553 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer ||
4554 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
4555 R_Shadow_FreeShadowMaps();
4557 r_shadow_usingshadowmaportho = false;
4559 switch (vid.renderpath)
4561 case RENDERPATH_GL20:
4562 case RENDERPATH_D3D9:
4563 case RENDERPATH_D3D10:
4564 case RENDERPATH_D3D11:
4565 case RENDERPATH_SOFT:
4566 case RENDERPATH_GLES2:
4567 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4569 r_shadow_usingdeferredprepass = false;
4570 if (r_shadow_prepass_width)
4571 R_Shadow_FreeDeferred();
4572 r_shadow_prepass_width = r_shadow_prepass_height = 0;
4576 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4578 R_Shadow_FreeDeferred();
4580 r_shadow_usingdeferredprepass = true;
4581 r_shadow_prepass_width = vid.width;
4582 r_shadow_prepass_height = vid.height;
4583 r_shadow_prepassgeometrydepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "prepassgeometrydepthmap", vid.width, vid.height, 24, false);
4584 switch (vid.renderpath)
4586 case RENDERPATH_D3D9:
4587 r_shadow_prepassgeometrydepthcolortexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrydepthcolormap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4592 r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4593 r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4594 r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
4596 // set up the geometry pass fbo (depth + normalmap)
4597 r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4598 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4599 // render depth into one texture and normalmap into the other
4600 if (qglDrawBuffersARB)
4602 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4603 qglReadBuffer(GL_NONE);CHECKGLERROR
4604 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4605 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4607 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4608 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4609 r_shadow_usingdeferredprepass = false;
4613 // set up the lighting pass fbo (diffuse + specular)
4614 r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4615 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4616 // render diffuse into one texture and specular into another,
4617 // with depth and normalmap bound as textures,
4618 // with depth bound as attachment as well
4619 if (qglDrawBuffersARB)
4621 qglDrawBuffersARB(2, r_shadow_prepasslightingdrawbuffers);CHECKGLERROR
4622 qglReadBuffer(GL_NONE);CHECKGLERROR
4623 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4624 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4626 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4627 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4628 r_shadow_usingdeferredprepass = false;
4632 // set up the lighting pass fbo (diffuse)
4633 r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4634 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4635 // render diffuse into one texture,
4636 // with depth and normalmap bound as textures,
4637 // with depth bound as attachment as well
4638 if (qglDrawBuffersARB)
4640 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4641 qglReadBuffer(GL_NONE);CHECKGLERROR
4642 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4643 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4645 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4646 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4647 r_shadow_usingdeferredprepass = false;
4652 case RENDERPATH_GL13:
4653 case RENDERPATH_GL11:
4654 r_shadow_usingdeferredprepass = false;
4658 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);
4660 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4661 if (r_shadow_debuglight.integer >= 0)
4663 lightindex = r_shadow_debuglight.integer;
4664 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4665 if (light && (light->flags & flag))
4666 R_Shadow_PrepareLight(&light->rtlight);
4670 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4671 for (lightindex = 0;lightindex < range;lightindex++)
4673 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4674 if (light && (light->flags & flag))
4675 R_Shadow_PrepareLight(&light->rtlight);
4678 if (r_refdef.scene.rtdlight)
4680 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4681 R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4683 else if(gl_flashblend.integer)
4685 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4687 rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4688 f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4689 VectorScale(rtlight->color, f, rtlight->currentcolor);
4693 if (r_editlights.integer)
4694 R_Shadow_DrawLightSprites();
4696 R_Shadow_UpdateBounceGridTexture();
4699 void R_Shadow_DrawLights(void)
4707 R_Shadow_RenderMode_Begin();
4709 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4710 if (r_shadow_debuglight.integer >= 0)
4712 lightindex = r_shadow_debuglight.integer;
4713 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4714 if (light && (light->flags & flag))
4715 R_Shadow_DrawLight(&light->rtlight);
4719 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4720 for (lightindex = 0;lightindex < range;lightindex++)
4722 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4723 if (light && (light->flags & flag))
4724 R_Shadow_DrawLight(&light->rtlight);
4727 if (r_refdef.scene.rtdlight)
4728 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4729 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4731 R_Shadow_RenderMode_End();
4734 extern const float r_screenvertex3f[12];
4735 extern void R_SetupView(qboolean allowwaterclippingplane);
4736 extern void R_ResetViewRendering3D(void);
4737 extern void R_ResetViewRendering2D(void);
4738 extern cvar_t r_shadows;
4739 extern cvar_t r_shadows_darken;
4740 extern cvar_t r_shadows_drawafterrtlighting;
4741 extern cvar_t r_shadows_castfrombmodels;
4742 extern cvar_t r_shadows_throwdistance;
4743 extern cvar_t r_shadows_throwdirection;
4744 extern cvar_t r_shadows_focus;
4745 extern cvar_t r_shadows_shadowmapscale;
4747 void R_Shadow_PrepareModelShadows(void)
4750 float scale, size, radius, dot1, dot2;
4751 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4752 entity_render_t *ent;
4754 if (!r_refdef.scene.numentities)
4757 switch (r_shadow_shadowmode)
4759 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4760 if (r_shadows.integer >= 2)
4763 case R_SHADOW_SHADOWMODE_STENCIL:
4764 for (i = 0;i < r_refdef.scene.numentities;i++)
4766 ent = r_refdef.scene.entities[i];
4767 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4768 R_AnimCache_GetEntity(ent, false, false);
4775 size = 2*r_shadow_shadowmapmaxsize;
4776 scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4777 radius = 0.5f * size / scale;
4779 Math_atov(r_shadows_throwdirection.string, shadowdir);
4780 VectorNormalize(shadowdir);
4781 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4782 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4783 if (fabs(dot1) <= fabs(dot2))
4784 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4786 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4787 VectorNormalize(shadowforward);
4788 CrossProduct(shadowdir, shadowforward, shadowright);
4789 Math_atov(r_shadows_focus.string, shadowfocus);
4790 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4791 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4792 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4793 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4794 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4796 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4798 shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4799 shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4800 shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4801 shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4802 shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4803 shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4805 for (i = 0;i < r_refdef.scene.numentities;i++)
4807 ent = r_refdef.scene.entities[i];
4808 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4810 // cast shadows from anything of the map (submodels are optional)
4811 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4812 R_AnimCache_GetEntity(ent, false, false);
4816 void R_DrawModelShadowMaps(void)
4819 float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4820 entity_render_t *ent;
4821 vec3_t relativelightorigin;
4822 vec3_t relativelightdirection, relativeforward, relativeright;
4823 vec3_t relativeshadowmins, relativeshadowmaxs;
4824 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4826 matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4827 r_viewport_t viewport;
4829 float clearcolor[4];
4831 if (!r_refdef.scene.numentities)
4834 switch (r_shadow_shadowmode)
4836 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4842 R_ResetViewRendering3D();
4843 R_Shadow_RenderMode_Begin();
4844 R_Shadow_RenderMode_ActiveLight(NULL);
4846 switch (r_shadow_shadowmode)
4848 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4849 if (!r_shadow_shadowmap2dtexture)
4850 R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4851 fbo = r_shadow_fbo2d;
4852 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
4853 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
4854 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4860 size = 2*r_shadow_shadowmapmaxsize;
4861 scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4862 radius = 0.5f / scale;
4863 nearclip = -r_shadows_throwdistance.value;
4864 farclip = r_shadows_throwdistance.value;
4865 bias = r_shadow_shadowmapping_bias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4867 r_shadow_shadowmap_parameters[0] = size;
4868 r_shadow_shadowmap_parameters[1] = size;
4869 r_shadow_shadowmap_parameters[2] = 1.0;
4870 r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4872 Math_atov(r_shadows_throwdirection.string, shadowdir);
4873 VectorNormalize(shadowdir);
4874 Math_atov(r_shadows_focus.string, shadowfocus);
4875 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4876 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4877 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4878 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4879 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4880 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4881 if (fabs(dot1) <= fabs(dot2))
4882 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4884 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4885 VectorNormalize(shadowforward);
4886 VectorM(scale, shadowforward, &m[0]);
4887 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4889 m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4890 CrossProduct(shadowdir, shadowforward, shadowright);
4891 VectorM(scale, shadowright, &m[4]);
4892 m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4893 VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4894 m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4895 Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4896 Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4897 R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL);
4899 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4901 R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
4902 R_SetupShader_DepthOrShadow();
4903 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4906 R_SetViewport(&viewport);
4907 GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4908 Vector4Set(clearcolor, 1,1,1,1);
4909 // in D3D9 we have to render to a color texture shadowmap
4910 // in GL we render directly to a depth texture only
4911 if (r_shadow_shadowmap2dtexture)
4912 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4914 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4915 // render into a slightly restricted region so that the borders of the
4916 // shadowmap area fade away, rather than streaking across everything
4917 // outside the usable area
4918 GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4922 R_Mesh_ResetRenderTargets();
4923 R_SetupShader_ShowDepth();
4924 GL_ColorMask(1,1,1,1);
4925 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4928 for (i = 0;i < r_refdef.scene.numentities;i++)
4930 ent = r_refdef.scene.entities[i];
4932 // cast shadows from anything of the map (submodels are optional)
4933 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4935 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4936 Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4937 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4938 Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4939 Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4940 relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4941 relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4942 relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4943 relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4944 relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4945 relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4946 RSurf_ActiveModelEntity(ent, false, false, false);
4947 ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4948 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4955 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4957 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4959 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4960 Cvar_SetValueQuick(&r_test, 0);
4965 R_Shadow_RenderMode_End();
4967 Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4968 Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4969 Matrix4x4_CreateScale3(&scalematrix, size, -size, 1);
4970 Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4971 Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4972 Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4974 switch (vid.renderpath)
4976 case RENDERPATH_GL11:
4977 case RENDERPATH_GL13:
4978 case RENDERPATH_GL20:
4979 case RENDERPATH_SOFT:
4980 case RENDERPATH_GLES2:
4982 case RENDERPATH_D3D9:
4983 case RENDERPATH_D3D10:
4984 case RENDERPATH_D3D11:
4985 #ifdef OPENGL_ORIENTATION
4986 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
4987 r_shadow_shadowmapmatrix.m[0][1] *= -1.0f;
4988 r_shadow_shadowmapmatrix.m[0][2] *= -1.0f;
4989 r_shadow_shadowmapmatrix.m[0][3] *= -1.0f;
4991 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
4992 r_shadow_shadowmapmatrix.m[1][0] *= -1.0f;
4993 r_shadow_shadowmapmatrix.m[2][0] *= -1.0f;
4994 r_shadow_shadowmapmatrix.m[3][0] *= -1.0f;
4999 r_shadow_usingshadowmaportho = true;
5000 switch (r_shadow_shadowmode)
5002 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
5003 r_shadow_usingshadowmap2d = true;
5010 void R_DrawModelShadows(void)
5013 float relativethrowdistance;
5014 entity_render_t *ent;
5015 vec3_t relativelightorigin;
5016 vec3_t relativelightdirection;
5017 vec3_t relativeshadowmins, relativeshadowmaxs;
5018 vec3_t tmp, shadowdir;
5020 if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
5023 R_ResetViewRendering3D();
5024 //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
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 R_Shadow_RenderMode_Begin();
5027 R_Shadow_RenderMode_ActiveLight(NULL);
5028 r_shadow_lightscissor[0] = r_refdef.view.x;
5029 r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
5030 r_shadow_lightscissor[2] = r_refdef.view.width;
5031 r_shadow_lightscissor[3] = r_refdef.view.height;
5032 R_Shadow_RenderMode_StencilShadowVolumes(false);
5035 if (r_shadows.integer == 2)
5037 Math_atov(r_shadows_throwdirection.string, shadowdir);
5038 VectorNormalize(shadowdir);
5041 R_Shadow_ClearStencil();
5043 for (i = 0;i < r_refdef.scene.numentities;i++)
5045 ent = r_refdef.scene.entities[i];
5047 // cast shadows from anything of the map (submodels are optional)
5048 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
5050 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5051 VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5052 VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5053 if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5054 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5057 if(ent->entitynumber != 0)
5059 if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5061 // FIXME handle this
5062 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5066 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5067 int entnum, entnum2, recursion;
5068 entnum = entnum2 = ent->entitynumber;
5069 for(recursion = 32; recursion > 0; --recursion)
5071 entnum2 = cl.entities[entnum].state_current.tagentity;
5072 if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5077 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5079 VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5080 // transform into modelspace of OUR entity
5081 Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5082 Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5085 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5089 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5092 VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5093 RSurf_ActiveModelEntity(ent, false, false, false);
5094 ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5095 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5099 // not really the right mode, but this will disable any silly stencil features
5100 R_Shadow_RenderMode_End();
5102 // set up ortho view for rendering this pass
5103 //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5104 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5105 //GL_ScissorTest(true);
5106 //R_EntityMatrix(&identitymatrix);
5107 //R_Mesh_ResetTextureState();
5108 R_ResetViewRendering2D();
5110 // set up a darkening blend on shadowed areas
5111 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5112 //GL_DepthRange(0, 1);
5113 //GL_DepthTest(false);
5114 //GL_DepthMask(false);
5115 //GL_PolygonOffset(0, 0);CHECKGLERROR
5116 GL_Color(0, 0, 0, r_shadows_darken.value);
5117 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5118 //GL_DepthFunc(GL_ALWAYS);
5119 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5121 // apply the blend to the shadowed areas
5122 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5123 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5124 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5126 // restore the viewport
5127 R_SetViewport(&r_refdef.view.viewport);
5129 // restore other state to normal
5130 //R_Shadow_RenderMode_End();
5133 void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5136 vec3_t centerorigin;
5138 // if it's too close, skip it
5139 if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5141 zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5144 if (usequery && r_numqueries + 2 <= r_maxqueries)
5146 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5147 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5148 // 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
5149 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5151 switch(vid.renderpath)
5153 case RENDERPATH_GL20:
5154 case RENDERPATH_GL13:
5155 case RENDERPATH_GL11:
5156 case RENDERPATH_GLES2:
5158 // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5159 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5160 GL_DepthFunc(GL_ALWAYS);
5161 R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5162 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5163 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5164 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5165 GL_DepthFunc(GL_LEQUAL);
5166 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5167 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5168 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5169 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5170 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5173 case RENDERPATH_D3D9:
5174 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5176 case RENDERPATH_D3D10:
5177 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5179 case RENDERPATH_D3D11:
5180 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5182 case RENDERPATH_SOFT:
5183 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5187 rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5190 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5192 void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5195 GLint allpixels = 0, visiblepixels = 0;
5196 // now we have to check the query result
5197 if (rtlight->corona_queryindex_visiblepixels)
5199 switch(vid.renderpath)
5201 case RENDERPATH_GL20:
5202 case RENDERPATH_GL13:
5203 case RENDERPATH_GL11:
5204 case RENDERPATH_GLES2:
5206 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5207 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5210 case RENDERPATH_D3D9:
5211 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5213 case RENDERPATH_D3D10:
5214 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5216 case RENDERPATH_D3D11:
5217 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5219 case RENDERPATH_SOFT:
5220 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5223 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5224 if (visiblepixels < 1 || allpixels < 1)
5226 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5227 cscale *= rtlight->corona_visibility;
5231 // FIXME: these traces should scan all render entities instead of cl.world
5232 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5235 VectorScale(rtlight->currentcolor, cscale, color);
5236 if (VectorLength(color) > (1.0f / 256.0f))
5239 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5242 VectorNegate(color, color);
5243 switch(vid.renderpath)
5245 case RENDERPATH_GL11:
5246 case RENDERPATH_GL13:
5247 case RENDERPATH_GL20:
5248 case RENDERPATH_GLES2:
5249 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
5251 case RENDERPATH_D3D9:
5253 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
5256 case RENDERPATH_D3D10:
5257 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5259 case RENDERPATH_D3D11:
5260 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5262 case RENDERPATH_SOFT:
5263 DPSOFTRAST_BlendSubtract(true);
5267 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5268 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);
5269 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5272 switch(vid.renderpath)
5274 case RENDERPATH_GL11:
5275 case RENDERPATH_GL13:
5276 case RENDERPATH_GL20:
5277 case RENDERPATH_GLES2:
5278 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
5280 case RENDERPATH_D3D9:
5282 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
5285 case RENDERPATH_D3D10:
5286 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5288 case RENDERPATH_D3D11:
5289 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5291 case RENDERPATH_SOFT:
5292 DPSOFTRAST_BlendSubtract(false);
5299 void R_Shadow_DrawCoronas(void)
5302 qboolean usequery = false;
5307 if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5309 if (r_waterstate.renderingscene)
5311 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5312 R_EntityMatrix(&identitymatrix);
5314 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5316 // check occlusion of coronas
5317 // use GL_ARB_occlusion_query if available
5318 // otherwise use raytraces
5320 switch (vid.renderpath)
5322 case RENDERPATH_GL11:
5323 case RENDERPATH_GL13:
5324 case RENDERPATH_GL20:
5325 case RENDERPATH_GLES2:
5326 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5329 GL_ColorMask(0,0,0,0);
5330 if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5331 if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5334 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5335 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5337 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5340 RSurf_ActiveWorldEntity();
5341 GL_BlendFunc(GL_ONE, GL_ZERO);
5342 GL_CullFace(GL_NONE);
5343 GL_DepthMask(false);
5344 GL_DepthRange(0, 1);
5345 GL_PolygonOffset(0, 0);
5347 R_Mesh_ResetTextureState();
5348 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5351 case RENDERPATH_D3D9:
5353 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5355 case RENDERPATH_D3D10:
5356 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5358 case RENDERPATH_D3D11:
5359 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5361 case RENDERPATH_SOFT:
5363 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5366 for (lightindex = 0;lightindex < range;lightindex++)
5368 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5371 rtlight = &light->rtlight;
5372 rtlight->corona_visibility = 0;
5373 rtlight->corona_queryindex_visiblepixels = 0;
5374 rtlight->corona_queryindex_allpixels = 0;
5375 if (!(rtlight->flags & flag))
5377 if (rtlight->corona <= 0)
5379 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5381 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5383 for (i = 0;i < r_refdef.scene.numlights;i++)
5385 rtlight = r_refdef.scene.lights[i];
5386 rtlight->corona_visibility = 0;
5387 rtlight->corona_queryindex_visiblepixels = 0;
5388 rtlight->corona_queryindex_allpixels = 0;
5389 if (!(rtlight->flags & flag))
5391 if (rtlight->corona <= 0)
5393 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5396 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5398 // now draw the coronas using the query data for intensity info
5399 for (lightindex = 0;lightindex < range;lightindex++)
5401 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5404 rtlight = &light->rtlight;
5405 if (rtlight->corona_visibility <= 0)
5407 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5409 for (i = 0;i < r_refdef.scene.numlights;i++)
5411 rtlight = r_refdef.scene.lights[i];
5412 if (rtlight->corona_visibility <= 0)
5414 if (gl_flashblend.integer)
5415 R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5417 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5423 dlight_t *R_Shadow_NewWorldLight(void)
5425 return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5428 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)
5431 // validate parameters
5432 if (style < 0 || style >= MAX_LIGHTSTYLES)
5434 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5440 // copy to light properties
5441 VectorCopy(origin, light->origin);
5442 light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5443 light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5444 light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5446 light->color[0] = max(color[0], 0);
5447 light->color[1] = max(color[1], 0);
5448 light->color[2] = max(color[2], 0);
5450 light->color[0] = color[0];
5451 light->color[1] = color[1];
5452 light->color[2] = color[2];
5453 light->radius = max(radius, 0);
5454 light->style = style;
5455 light->shadow = shadowenable;
5456 light->corona = corona;
5457 strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5458 light->coronasizescale = coronasizescale;
5459 light->ambientscale = ambientscale;
5460 light->diffusescale = diffusescale;
5461 light->specularscale = specularscale;
5462 light->flags = flags;
5464 // update renderable light data
5465 Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5466 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);
5469 void R_Shadow_FreeWorldLight(dlight_t *light)
5471 if (r_shadow_selectedlight == light)
5472 r_shadow_selectedlight = NULL;
5473 R_RTLight_Uncompile(&light->rtlight);
5474 Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5477 void R_Shadow_ClearWorldLights(void)
5481 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5482 for (lightindex = 0;lightindex < range;lightindex++)
5484 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5486 R_Shadow_FreeWorldLight(light);
5488 r_shadow_selectedlight = NULL;
5491 void R_Shadow_SelectLight(dlight_t *light)
5493 if (r_shadow_selectedlight)
5494 r_shadow_selectedlight->selected = false;
5495 r_shadow_selectedlight = light;
5496 if (r_shadow_selectedlight)
5497 r_shadow_selectedlight->selected = true;
5500 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5502 // this is never batched (there can be only one)
5504 R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5505 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5506 R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5509 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5514 skinframe_t *skinframe;
5517 // this is never batched (due to the ent parameter changing every time)
5518 // so numsurfaces == 1 and surfacelist[0] == lightnumber
5519 const dlight_t *light = (dlight_t *)ent;
5522 R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5525 VectorScale(light->color, intensity, spritecolor);
5526 if (VectorLength(spritecolor) < 0.1732f)
5527 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5528 if (VectorLength(spritecolor) > 1.0f)
5529 VectorNormalize(spritecolor);
5531 // draw light sprite
5532 if (light->cubemapname[0] && !light->shadow)
5533 skinframe = r_editlights_sprcubemapnoshadowlight;
5534 else if (light->cubemapname[0])
5535 skinframe = r_editlights_sprcubemaplight;
5536 else if (!light->shadow)
5537 skinframe = r_editlights_sprnoshadowlight;
5539 skinframe = r_editlights_sprlight;
5541 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);
5542 R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5544 // draw selection sprite if light is selected
5545 if (light->selected)
5547 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5548 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5549 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5553 void R_Shadow_DrawLightSprites(void)
5557 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5558 for (lightindex = 0;lightindex < range;lightindex++)
5560 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5562 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5564 if (!r_editlights_lockcursor)
5565 R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5568 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5573 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5574 if (lightindex >= range)
5576 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5579 rtlight = &light->rtlight;
5580 //if (!(rtlight->flags & flag))
5582 VectorCopy(rtlight->shadoworigin, origin);
5583 *radius = rtlight->radius;
5584 VectorCopy(rtlight->color, color);
5588 void R_Shadow_SelectLightInView(void)
5590 float bestrating, rating, temp[3];
5594 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5598 if (r_editlights_lockcursor)
5600 for (lightindex = 0;lightindex < range;lightindex++)
5602 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5605 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5606 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5609 rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5610 if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5612 bestrating = rating;
5617 R_Shadow_SelectLight(best);
5620 void R_Shadow_LoadWorldLights(void)
5622 int n, a, style, shadow, flags;
5623 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5624 float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5625 if (cl.worldmodel == NULL)
5627 Con_Print("No map loaded.\n");
5630 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5631 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5641 for (;COM_Parse(t, true) && strcmp(
5642 if (COM_Parse(t, true))
5644 if (com_token[0] == '!')
5647 origin[0] = atof(com_token+1);
5650 origin[0] = atof(com_token);
5655 while (*s && *s != '\n' && *s != '\r')
5661 // check for modifier flags
5668 #if _MSC_VER >= 1400
5669 #define sscanf sscanf_s
5671 cubemapname[sizeof(cubemapname)-1] = 0;
5672 #if MAX_QPATH != 128
5673 #error update this code if MAX_QPATH changes
5675 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
5676 #if _MSC_VER >= 1400
5677 , sizeof(cubemapname)
5679 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5682 flags = LIGHTFLAG_REALTIMEMODE;
5690 coronasizescale = 0.25f;
5692 VectorClear(angles);
5695 if (a < 9 || !strcmp(cubemapname, "\"\""))
5697 // remove quotes on cubemapname
5698 if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5701 namelen = strlen(cubemapname) - 2;
5702 memmove(cubemapname, cubemapname + 1, namelen);
5703 cubemapname[namelen] = '\0';
5707 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);
5710 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5718 Con_Printf("invalid rtlights file \"%s\"\n", name);
5719 Mem_Free(lightsstring);
5723 void R_Shadow_SaveWorldLights(void)
5727 size_t bufchars, bufmaxchars;
5729 char name[MAX_QPATH];
5730 char line[MAX_INPUTLINE];
5731 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5732 // I hate lines which are 3 times my screen size :( --blub
5735 if (cl.worldmodel == NULL)
5737 Con_Print("No map loaded.\n");
5740 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5741 bufchars = bufmaxchars = 0;
5743 for (lightindex = 0;lightindex < range;lightindex++)
5745 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5748 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5749 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);
5750 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5751 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]);
5753 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);
5754 if (bufchars + strlen(line) > bufmaxchars)
5756 bufmaxchars = bufchars + strlen(line) + 2048;
5758 buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5762 memcpy(buf, oldbuf, bufchars);
5768 memcpy(buf + bufchars, line, strlen(line));
5769 bufchars += strlen(line);
5773 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5778 void R_Shadow_LoadLightsFile(void)
5781 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5782 float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5783 if (cl.worldmodel == NULL)
5785 Con_Print("No map loaded.\n");
5788 dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5789 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5797 while (*s && *s != '\n' && *s != '\r')
5803 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);
5807 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);
5810 radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5811 radius = bound(15, radius, 4096);
5812 VectorScale(color, (2.0f / (8388608.0f)), color);
5813 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5821 Con_Printf("invalid lights file \"%s\"\n", name);
5822 Mem_Free(lightsstring);
5826 // tyrlite/hmap2 light types in the delay field
5827 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5829 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5841 float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5842 char key[256], value[MAX_INPUTLINE];
5844 if (cl.worldmodel == NULL)
5846 Con_Print("No map loaded.\n");
5849 // try to load a .ent file first
5850 dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5851 data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5852 // and if that is not found, fall back to the bsp file entity string
5854 data = cl.worldmodel->brush.entities;
5857 for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++)
5859 type = LIGHTTYPE_MINUSX;
5860 origin[0] = origin[1] = origin[2] = 0;
5861 originhack[0] = originhack[1] = originhack[2] = 0;
5862 angles[0] = angles[1] = angles[2] = 0;
5863 color[0] = color[1] = color[2] = 1;
5864 light[0] = light[1] = light[2] = 1;light[3] = 300;
5865 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5875 if (!COM_ParseToken_Simple(&data, false, false))
5877 if (com_token[0] == '}')
5878 break; // end of entity
5879 if (com_token[0] == '_')
5880 strlcpy(key, com_token + 1, sizeof(key));
5882 strlcpy(key, com_token, sizeof(key));
5883 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5884 key[strlen(key)-1] = 0;
5885 if (!COM_ParseToken_Simple(&data, false, false))
5887 strlcpy(value, com_token, sizeof(value));
5889 // now that we have the key pair worked out...
5890 if (!strcmp("light", key))
5892 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5896 light[0] = vec[0] * (1.0f / 256.0f);
5897 light[1] = vec[0] * (1.0f / 256.0f);
5898 light[2] = vec[0] * (1.0f / 256.0f);
5904 light[0] = vec[0] * (1.0f / 255.0f);
5905 light[1] = vec[1] * (1.0f / 255.0f);
5906 light[2] = vec[2] * (1.0f / 255.0f);
5910 else if (!strcmp("delay", key))
5912 else if (!strcmp("origin", key))
5913 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5914 else if (!strcmp("angle", key))
5915 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5916 else if (!strcmp("angles", key))
5917 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5918 else if (!strcmp("color", key))
5919 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5920 else if (!strcmp("wait", key))
5921 fadescale = atof(value);
5922 else if (!strcmp("classname", key))
5924 if (!strncmp(value, "light", 5))
5927 if (!strcmp(value, "light_fluoro"))
5932 overridecolor[0] = 1;
5933 overridecolor[1] = 1;
5934 overridecolor[2] = 1;
5936 if (!strcmp(value, "light_fluorospark"))
5941 overridecolor[0] = 1;
5942 overridecolor[1] = 1;
5943 overridecolor[2] = 1;
5945 if (!strcmp(value, "light_globe"))
5950 overridecolor[0] = 1;
5951 overridecolor[1] = 0.8;
5952 overridecolor[2] = 0.4;
5954 if (!strcmp(value, "light_flame_large_yellow"))
5959 overridecolor[0] = 1;
5960 overridecolor[1] = 0.5;
5961 overridecolor[2] = 0.1;
5963 if (!strcmp(value, "light_flame_small_yellow"))
5968 overridecolor[0] = 1;
5969 overridecolor[1] = 0.5;
5970 overridecolor[2] = 0.1;
5972 if (!strcmp(value, "light_torch_small_white"))
5977 overridecolor[0] = 1;
5978 overridecolor[1] = 0.5;
5979 overridecolor[2] = 0.1;
5981 if (!strcmp(value, "light_torch_small_walltorch"))
5986 overridecolor[0] = 1;
5987 overridecolor[1] = 0.5;
5988 overridecolor[2] = 0.1;
5992 else if (!strcmp("style", key))
5993 style = atoi(value);
5994 else if (!strcmp("skin", key))
5995 skin = (int)atof(value);
5996 else if (!strcmp("pflags", key))
5997 pflags = (int)atof(value);
5998 //else if (!strcmp("effects", key))
5999 // effects = (int)atof(value);
6000 else if (cl.worldmodel->type == mod_brushq3)
6002 if (!strcmp("scale", key))
6003 lightscale = atof(value);
6004 if (!strcmp("fade", key))
6005 fadescale = atof(value);
6010 if (lightscale <= 0)
6014 if (color[0] == color[1] && color[0] == color[2])
6016 color[0] *= overridecolor[0];
6017 color[1] *= overridecolor[1];
6018 color[2] *= overridecolor[2];
6020 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
6021 color[0] = color[0] * light[0];
6022 color[1] = color[1] * light[1];
6023 color[2] = color[2] * light[2];
6026 case LIGHTTYPE_MINUSX:
6028 case LIGHTTYPE_RECIPX:
6030 VectorScale(color, (1.0f / 16.0f), color);
6032 case LIGHTTYPE_RECIPXX:
6034 VectorScale(color, (1.0f / 16.0f), color);
6037 case LIGHTTYPE_NONE:
6041 case LIGHTTYPE_MINUSXX:
6044 VectorAdd(origin, originhack, origin);
6046 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6049 Mem_Free(entfiledata);
6053 void R_Shadow_SetCursorLocationForView(void)
6056 vec3_t dest, endpos;
6058 VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
6059 trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
6060 if (trace.fraction < 1)
6062 dist = trace.fraction * r_editlights_cursordistance.value;
6063 push = r_editlights_cursorpushback.value;
6067 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
6068 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
6072 VectorClear( endpos );
6074 r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6075 r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6076 r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6079 void R_Shadow_UpdateWorldLightSelection(void)
6081 if (r_editlights.integer)
6083 R_Shadow_SetCursorLocationForView();
6084 R_Shadow_SelectLightInView();
6087 R_Shadow_SelectLight(NULL);
6090 void R_Shadow_EditLights_Clear_f(void)
6092 R_Shadow_ClearWorldLights();
6095 void R_Shadow_EditLights_Reload_f(void)
6099 strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6100 R_Shadow_ClearWorldLights();
6101 R_Shadow_LoadWorldLights();
6102 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6104 R_Shadow_LoadLightsFile();
6105 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6106 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6110 void R_Shadow_EditLights_Save_f(void)
6114 R_Shadow_SaveWorldLights();
6117 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6119 R_Shadow_ClearWorldLights();
6120 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6123 void R_Shadow_EditLights_ImportLightsFile_f(void)
6125 R_Shadow_ClearWorldLights();
6126 R_Shadow_LoadLightsFile();
6129 void R_Shadow_EditLights_Spawn_f(void)
6132 if (!r_editlights.integer)
6134 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6137 if (Cmd_Argc() != 1)
6139 Con_Print("r_editlights_spawn does not take parameters\n");
6142 color[0] = color[1] = color[2] = 1;
6143 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6146 void R_Shadow_EditLights_Edit_f(void)
6148 vec3_t origin, angles, color;
6149 vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6150 int style, shadows, flags, normalmode, realtimemode;
6151 char cubemapname[MAX_INPUTLINE];
6152 if (!r_editlights.integer)
6154 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6157 if (!r_shadow_selectedlight)
6159 Con_Print("No selected light.\n");
6162 VectorCopy(r_shadow_selectedlight->origin, origin);
6163 VectorCopy(r_shadow_selectedlight->angles, angles);
6164 VectorCopy(r_shadow_selectedlight->color, color);
6165 radius = r_shadow_selectedlight->radius;
6166 style = r_shadow_selectedlight->style;
6167 if (r_shadow_selectedlight->cubemapname)
6168 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6171 shadows = r_shadow_selectedlight->shadow;
6172 corona = r_shadow_selectedlight->corona;
6173 coronasizescale = r_shadow_selectedlight->coronasizescale;
6174 ambientscale = r_shadow_selectedlight->ambientscale;
6175 diffusescale = r_shadow_selectedlight->diffusescale;
6176 specularscale = r_shadow_selectedlight->specularscale;
6177 flags = r_shadow_selectedlight->flags;
6178 normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6179 realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6180 if (!strcmp(Cmd_Argv(1), "origin"))
6182 if (Cmd_Argc() != 5)
6184 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6187 origin[0] = atof(Cmd_Argv(2));
6188 origin[1] = atof(Cmd_Argv(3));
6189 origin[2] = atof(Cmd_Argv(4));
6191 else if (!strcmp(Cmd_Argv(1), "originscale"))
6193 if (Cmd_Argc() != 5)
6195 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6198 origin[0] *= atof(Cmd_Argv(2));
6199 origin[1] *= atof(Cmd_Argv(3));
6200 origin[2] *= atof(Cmd_Argv(4));
6202 else if (!strcmp(Cmd_Argv(1), "originx"))
6204 if (Cmd_Argc() != 3)
6206 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6209 origin[0] = atof(Cmd_Argv(2));
6211 else if (!strcmp(Cmd_Argv(1), "originy"))
6213 if (Cmd_Argc() != 3)
6215 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6218 origin[1] = atof(Cmd_Argv(2));
6220 else if (!strcmp(Cmd_Argv(1), "originz"))
6222 if (Cmd_Argc() != 3)
6224 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6227 origin[2] = atof(Cmd_Argv(2));
6229 else if (!strcmp(Cmd_Argv(1), "move"))
6231 if (Cmd_Argc() != 5)
6233 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6236 origin[0] += atof(Cmd_Argv(2));
6237 origin[1] += atof(Cmd_Argv(3));
6238 origin[2] += atof(Cmd_Argv(4));
6240 else if (!strcmp(Cmd_Argv(1), "movex"))
6242 if (Cmd_Argc() != 3)
6244 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6247 origin[0] += atof(Cmd_Argv(2));
6249 else if (!strcmp(Cmd_Argv(1), "movey"))
6251 if (Cmd_Argc() != 3)
6253 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6256 origin[1] += atof(Cmd_Argv(2));
6258 else if (!strcmp(Cmd_Argv(1), "movez"))
6260 if (Cmd_Argc() != 3)
6262 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6265 origin[2] += atof(Cmd_Argv(2));
6267 else if (!strcmp(Cmd_Argv(1), "angles"))
6269 if (Cmd_Argc() != 5)
6271 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6274 angles[0] = atof(Cmd_Argv(2));
6275 angles[1] = atof(Cmd_Argv(3));
6276 angles[2] = atof(Cmd_Argv(4));
6278 else if (!strcmp(Cmd_Argv(1), "anglesx"))
6280 if (Cmd_Argc() != 3)
6282 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6285 angles[0] = atof(Cmd_Argv(2));
6287 else if (!strcmp(Cmd_Argv(1), "anglesy"))
6289 if (Cmd_Argc() != 3)
6291 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6294 angles[1] = atof(Cmd_Argv(2));
6296 else if (!strcmp(Cmd_Argv(1), "anglesz"))
6298 if (Cmd_Argc() != 3)
6300 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6303 angles[2] = atof(Cmd_Argv(2));
6305 else if (!strcmp(Cmd_Argv(1), "color"))
6307 if (Cmd_Argc() != 5)
6309 Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6312 color[0] = atof(Cmd_Argv(2));
6313 color[1] = atof(Cmd_Argv(3));
6314 color[2] = atof(Cmd_Argv(4));
6316 else if (!strcmp(Cmd_Argv(1), "radius"))
6318 if (Cmd_Argc() != 3)
6320 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6323 radius = atof(Cmd_Argv(2));
6325 else if (!strcmp(Cmd_Argv(1), "colorscale"))
6327 if (Cmd_Argc() == 3)
6329 double scale = atof(Cmd_Argv(2));
6336 if (Cmd_Argc() != 5)
6338 Con_Printf("usage: r_editlights_edit %s red green blue (OR grey instead of red green blue)\n", Cmd_Argv(1));
6341 color[0] *= atof(Cmd_Argv(2));
6342 color[1] *= atof(Cmd_Argv(3));
6343 color[2] *= atof(Cmd_Argv(4));
6346 else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6348 if (Cmd_Argc() != 3)
6350 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6353 radius *= atof(Cmd_Argv(2));
6355 else if (!strcmp(Cmd_Argv(1), "style"))
6357 if (Cmd_Argc() != 3)
6359 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6362 style = atoi(Cmd_Argv(2));
6364 else if (!strcmp(Cmd_Argv(1), "cubemap"))
6368 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6371 if (Cmd_Argc() == 3)
6372 strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6376 else if (!strcmp(Cmd_Argv(1), "shadows"))
6378 if (Cmd_Argc() != 3)
6380 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6383 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6385 else if (!strcmp(Cmd_Argv(1), "corona"))
6387 if (Cmd_Argc() != 3)
6389 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6392 corona = atof(Cmd_Argv(2));
6394 else if (!strcmp(Cmd_Argv(1), "coronasize"))
6396 if (Cmd_Argc() != 3)
6398 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6401 coronasizescale = atof(Cmd_Argv(2));
6403 else if (!strcmp(Cmd_Argv(1), "ambient"))
6405 if (Cmd_Argc() != 3)
6407 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6410 ambientscale = atof(Cmd_Argv(2));
6412 else if (!strcmp(Cmd_Argv(1), "diffuse"))
6414 if (Cmd_Argc() != 3)
6416 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6419 diffusescale = atof(Cmd_Argv(2));
6421 else if (!strcmp(Cmd_Argv(1), "specular"))
6423 if (Cmd_Argc() != 3)
6425 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6428 specularscale = atof(Cmd_Argv(2));
6430 else if (!strcmp(Cmd_Argv(1), "normalmode"))
6432 if (Cmd_Argc() != 3)
6434 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6437 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6439 else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6441 if (Cmd_Argc() != 3)
6443 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6446 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6450 Con_Print("usage: r_editlights_edit [property] [value]\n");
6451 Con_Print("Selected light's properties:\n");
6452 Con_Printf("Origin : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6453 Con_Printf("Angles : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6454 Con_Printf("Color : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6455 Con_Printf("Radius : %f\n", r_shadow_selectedlight->radius);
6456 Con_Printf("Corona : %f\n", r_shadow_selectedlight->corona);
6457 Con_Printf("Style : %i\n", r_shadow_selectedlight->style);
6458 Con_Printf("Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6459 Con_Printf("Cubemap : %s\n", r_shadow_selectedlight->cubemapname);
6460 Con_Printf("CoronaSize : %f\n", r_shadow_selectedlight->coronasizescale);
6461 Con_Printf("Ambient : %f\n", r_shadow_selectedlight->ambientscale);
6462 Con_Printf("Diffuse : %f\n", r_shadow_selectedlight->diffusescale);
6463 Con_Printf("Specular : %f\n", r_shadow_selectedlight->specularscale);
6464 Con_Printf("NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6465 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6468 flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6469 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6472 void R_Shadow_EditLights_EditAll_f(void)
6475 dlight_t *light, *oldselected;
6478 if (!r_editlights.integer)
6480 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6484 oldselected = r_shadow_selectedlight;
6485 // EditLights doesn't seem to have a "remove" command or something so:
6486 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6487 for (lightindex = 0;lightindex < range;lightindex++)
6489 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6492 R_Shadow_SelectLight(light);
6493 R_Shadow_EditLights_Edit_f();
6495 // return to old selected (to not mess editing once selection is locked)
6496 R_Shadow_SelectLight(oldselected);
6499 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6501 int lightnumber, lightcount;
6502 size_t lightindex, range;
6506 if (!r_editlights.integer)
6508 x = vid_conwidth.value - 240;
6510 DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6513 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6514 for (lightindex = 0;lightindex < range;lightindex++)
6516 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6519 if (light == r_shadow_selectedlight)
6520 lightnumber = lightindex;
6523 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;
6524 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;
6526 if (r_shadow_selectedlight == NULL)
6528 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;
6529 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;
6530 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;
6531 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;
6532 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;
6533 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;
6534 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;
6535 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;
6536 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;
6537 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;
6538 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;
6539 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;
6540 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;
6541 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;
6542 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;
6545 void R_Shadow_EditLights_ToggleShadow_f(void)
6547 if (!r_editlights.integer)
6549 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6552 if (!r_shadow_selectedlight)
6554 Con_Print("No selected light.\n");
6557 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);
6560 void R_Shadow_EditLights_ToggleCorona_f(void)
6562 if (!r_editlights.integer)
6564 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6567 if (!r_shadow_selectedlight)
6569 Con_Print("No selected light.\n");
6572 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);
6575 void R_Shadow_EditLights_Remove_f(void)
6577 if (!r_editlights.integer)
6579 Con_Print("Cannot remove light when not in editing mode. Set r_editlights to 1.\n");
6582 if (!r_shadow_selectedlight)
6584 Con_Print("No selected light.\n");
6587 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6588 r_shadow_selectedlight = NULL;
6591 void R_Shadow_EditLights_Help_f(void)
6594 "Documentation on r_editlights system:\n"
6596 "r_editlights : enable/disable editing mode\n"
6597 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6598 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6599 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6600 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6601 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6603 "r_editlights_help : this help\n"
6604 "r_editlights_clear : remove all lights\n"
6605 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6606 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6607 "r_editlights_save : save to .rtlights file\n"
6608 "r_editlights_spawn : create a light with default settings\n"
6609 "r_editlights_edit command : edit selected light - more documentation below\n"
6610 "r_editlights_remove : remove selected light\n"
6611 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6612 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6613 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6615 "origin x y z : set light location\n"
6616 "originx x: set x component of light location\n"
6617 "originy y: set y component of light location\n"
6618 "originz z: set z component of light location\n"
6619 "move x y z : adjust light location\n"
6620 "movex x: adjust x component of light location\n"
6621 "movey y: adjust y component of light location\n"
6622 "movez z: adjust z component of light location\n"
6623 "angles x y z : set light angles\n"
6624 "anglesx x: set x component of light angles\n"
6625 "anglesy y: set y component of light angles\n"
6626 "anglesz z: set z component of light angles\n"
6627 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6628 "radius radius : set radius (size) of light\n"
6629 "colorscale grey : multiply color of light (1 does nothing)\n"
6630 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6631 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6632 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6633 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6634 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6635 "cubemap basename : set filter cubemap of light (not yet supported)\n"
6636 "shadows 1/0 : turn on/off shadows\n"
6637 "corona n : set corona intensity\n"
6638 "coronasize n : set corona size (0-1)\n"
6639 "ambient n : set ambient intensity (0-1)\n"
6640 "diffuse n : set diffuse intensity (0-1)\n"
6641 "specular n : set specular intensity (0-1)\n"
6642 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6643 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6644 "<nothing> : print light properties to console\n"
6648 void R_Shadow_EditLights_CopyInfo_f(void)
6650 if (!r_editlights.integer)
6652 Con_Print("Cannot copy light info when not in editing mode. Set r_editlights to 1.\n");
6655 if (!r_shadow_selectedlight)
6657 Con_Print("No selected light.\n");
6660 VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6661 VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6662 r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6663 r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6664 if (r_shadow_selectedlight->cubemapname)
6665 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6667 r_shadow_bufferlight.cubemapname[0] = 0;
6668 r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6669 r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6670 r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6671 r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6672 r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6673 r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6674 r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6677 void R_Shadow_EditLights_PasteInfo_f(void)
6679 if (!r_editlights.integer)
6681 Con_Print("Cannot paste light info when not in editing mode. Set r_editlights to 1.\n");
6684 if (!r_shadow_selectedlight)
6686 Con_Print("No selected light.\n");
6689 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);
6692 void R_Shadow_EditLights_Lock_f(void)
6694 if (!r_editlights.integer)
6696 Con_Print("Cannot lock on light when not in editing mode. Set r_editlights to 1.\n");
6699 if (r_editlights_lockcursor)
6701 r_editlights_lockcursor = false;
6704 if (!r_shadow_selectedlight)
6706 Con_Print("No selected light to lock on.\n");
6709 r_editlights_lockcursor = true;
6712 void R_Shadow_EditLights_Init(void)
6714 Cvar_RegisterVariable(&r_editlights);
6715 Cvar_RegisterVariable(&r_editlights_cursordistance);
6716 Cvar_RegisterVariable(&r_editlights_cursorpushback);
6717 Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6718 Cvar_RegisterVariable(&r_editlights_cursorgrid);
6719 Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6720 Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6721 Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6722 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)");
6723 Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6724 Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6725 Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6726 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)");
6727 Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6728 Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6729 Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6730 Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6731 Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6732 Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6733 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)");
6734 Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6740 =============================================================================
6744 =============================================================================
6747 void R_LightPoint(vec3_t color, const vec3_t p, const int flags)
6749 int i, numlights, flag;
6750 float f, relativepoint[3], dist, dist2, lightradius2;
6757 if (r_fullbright.integer)
6759 VectorSet(color, 1, 1, 1);
6763 if (flags & LP_LIGHTMAP)
6765 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6767 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6768 color[0] += r_refdef.scene.ambient + diffuse[0];
6769 color[1] += r_refdef.scene.ambient + diffuse[1];
6770 color[2] += r_refdef.scene.ambient + diffuse[2];
6773 VectorSet(color, 1, 1, 1);
6775 if (flags & LP_RTWORLD)
6777 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6778 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6779 for (i = 0; i < numlights; i++)
6781 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6784 light = &dlight->rtlight;
6785 if (!(light->flags & flag))
6788 lightradius2 = light->radius * light->radius;
6789 VectorSubtract(light->shadoworigin, p, relativepoint);
6790 dist2 = VectorLength2(relativepoint);
6791 if (dist2 >= lightradius2)
6793 dist = sqrt(dist2) / light->radius;
6794 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6797 // todo: add to both ambient and diffuse
6798 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6799 VectorMA(color, f, light->currentcolor, color);
6802 if (flags & LP_DYNLIGHT)
6805 for (i = 0;i < r_refdef.scene.numlights;i++)
6807 light = r_refdef.scene.lights[i];
6809 lightradius2 = light->radius * light->radius;
6810 VectorSubtract(light->shadoworigin, p, relativepoint);
6811 dist2 = VectorLength2(relativepoint);
6812 if (dist2 >= lightradius2)
6814 dist = sqrt(dist2) / light->radius;
6815 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6818 // todo: add to both ambient and diffuse
6819 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6820 VectorMA(color, f, light->color, color);
6825 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6827 int i, numlights, flag;
6830 float relativepoint[3];
6839 if (r_fullbright.integer)
6841 VectorSet(ambient, 1, 1, 1);
6842 VectorClear(diffuse);
6843 VectorClear(lightdir);
6847 if (flags == LP_LIGHTMAP)
6849 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6850 VectorClear(diffuse);
6851 VectorClear(lightdir);
6852 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6853 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6857 memset(sample, 0, sizeof(sample));
6858 VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6860 if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6863 VectorClear(tempambient);
6865 VectorClear(relativepoint);
6866 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6867 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6868 VectorScale(color, r_refdef.lightmapintensity, color);
6869 VectorAdd(sample, tempambient, sample);
6870 VectorMA(sample , 0.5f , color, sample );
6871 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6872 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6873 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6874 // calculate a weighted average light direction as well
6875 intensity = VectorLength(color);
6876 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6879 if (flags & LP_RTWORLD)
6881 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6882 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6883 for (i = 0; i < numlights; i++)
6885 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6888 light = &dlight->rtlight;
6889 if (!(light->flags & flag))
6892 lightradius2 = light->radius * light->radius;
6893 VectorSubtract(light->shadoworigin, p, relativepoint);
6894 dist2 = VectorLength2(relativepoint);
6895 if (dist2 >= lightradius2)
6897 dist = sqrt(dist2) / light->radius;
6898 intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6899 if (intensity <= 0.0f)
6901 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6903 // scale down intensity to add to both ambient and diffuse
6904 //intensity *= 0.5f;
6905 VectorNormalize(relativepoint);
6906 VectorScale(light->currentcolor, intensity, color);
6907 VectorMA(sample , 0.5f , color, sample );
6908 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6909 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6910 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6911 // calculate a weighted average light direction as well
6912 intensity *= VectorLength(color);
6913 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6917 if (flags & LP_DYNLIGHT)
6920 for (i = 0;i < r_refdef.scene.numlights;i++)
6922 light = r_refdef.scene.lights[i];
6924 lightradius2 = light->radius * light->radius;
6925 VectorSubtract(light->shadoworigin, p, relativepoint);
6926 dist2 = VectorLength2(relativepoint);
6927 if (dist2 >= lightradius2)
6929 dist = sqrt(dist2) / light->radius;
6930 intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6931 if (intensity <= 0.0f)
6933 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6935 // scale down intensity to add to both ambient and diffuse
6936 //intensity *= 0.5f;
6937 VectorNormalize(relativepoint);
6938 VectorScale(light->currentcolor, intensity, color);
6939 VectorMA(sample , 0.5f , color, sample );
6940 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6941 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6942 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6943 // calculate a weighted average light direction as well
6944 intensity *= VectorLength(color);
6945 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6949 // calculate the direction we'll use to reduce the sample to a directional light source
6950 VectorCopy(sample + 12, dir);
6951 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6952 VectorNormalize(dir);
6953 // extract the diffuse color along the chosen direction and scale it
6954 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6955 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6956 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6957 // subtract some of diffuse from ambient
6958 VectorMA(sample, -0.333f, diffuse, ambient);
6959 // store the normalized lightdir
6960 VectorCopy(dir, lightdir);