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_airstepmax = {CVAR_SAVE, "r_shadow_bouncegrid_airstepmax", "1024", "maximum number of photon accumulation contributions for one photon"};
324 cvar_t r_shadow_bouncegrid_airstepsize = {CVAR_SAVE, "r_shadow_bouncegrid_airstepsize", "64", "maximum spacing of photon accumulation through the air"};
325 cvar_t r_shadow_bouncegrid_bounceanglediffuse = {CVAR_SAVE, "r_shadow_bouncegrid_bounceanglediffuse", "0", "use random bounce direction rather than true reflection, makes some corner areas dark"};
326 cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 8x as many pixels to hold the additional data"};
327 cvar_t r_shadow_bouncegrid_dlightparticlemultiplier = {CVAR_SAVE, "r_shadow_bouncegrid_dlightparticlemultiplier", "0", "if set to a high value like 16 this can make dlights look great, but 0 is recommended for performance reasons"};
328 cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"};
329 cvar_t r_shadow_bouncegrid_includedirectlighting = {CVAR_SAVE, "r_shadow_bouncegrid_includedirectlighting", "0", "allows direct lighting to be recorded, not just indirect (gives an effect somewhat like r_shadow_realtime_world_lightmaps)"};
330 cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"};
331 cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1)"};
332 cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "5", "maximum number of bounces for a particle (minimum is 1)"};
333 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"};
334 cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"};
335 cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"};
336 cvar_t r_shadow_bouncegrid_spacingx = {CVAR_SAVE, "r_shadow_bouncegrid_spacingx", "64", "unit size of bouncegrid pixel on X axis"};
337 cvar_t r_shadow_bouncegrid_spacingy = {CVAR_SAVE, "r_shadow_bouncegrid_spacingy", "64", "unit size of bouncegrid pixel on Y axis"};
338 cvar_t r_shadow_bouncegrid_spacingz = {CVAR_SAVE, "r_shadow_bouncegrid_spacingz", "64", "unit size of bouncegrid pixel on Z axis"};
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_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"};
341 cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"};
342 cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"};
343 cvar_t r_shadow_bouncegrid_updateinterval = {CVAR_SAVE, "r_shadow_bouncegrid_updateinterval", "0", "update bouncegrid texture once per this many seconds, useful values are 0, 0.05, or 1000000"};
344 cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"};
345 cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"};
346 cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"};
347 cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"};
348 cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"};
349 cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"};
350 cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"};
351 cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"};
352 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
353 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
354 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
355 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
356 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
357 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
358 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
360 typedef struct r_shadow_bouncegrid_settings_s
363 qboolean bounceanglediffuse;
364 qboolean directionalshading;
365 qboolean includedirectlighting;
366 float dlightparticlemultiplier;
368 float lightradiusscale;
370 float particlebounceintensity;
371 float particleintensity;
378 r_shadow_bouncegrid_settings_t;
380 r_shadow_bouncegrid_settings_t r_shadow_bouncegridsettings;
381 rtexture_t *r_shadow_bouncegridtexture;
382 matrix4x4_t r_shadow_bouncegridmatrix;
383 vec_t r_shadow_bouncegridintensity;
384 qboolean r_shadow_bouncegriddirectional;
385 static double r_shadow_bouncegridtime;
386 static int r_shadow_bouncegridresolution[3];
387 static int r_shadow_bouncegridnumpixels;
388 static unsigned char *r_shadow_bouncegridpixels;
389 static float *r_shadow_bouncegridhighpixels;
391 // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error
392 #define ATTENTABLESIZE 256
393 // 1D gradient, 2D circle and 3D sphere attenuation textures
394 #define ATTEN1DSIZE 32
395 #define ATTEN2DSIZE 64
396 #define ATTEN3DSIZE 32
398 static float r_shadow_attendividebias; // r_shadow_lightattenuationdividebias
399 static float r_shadow_attenlinearscale; // r_shadow_lightattenuationlinearscale
400 static float r_shadow_attentable[ATTENTABLESIZE+1];
402 rtlight_t *r_shadow_compilingrtlight;
403 static memexpandablearray_t r_shadow_worldlightsarray;
404 dlight_t *r_shadow_selectedlight;
405 dlight_t r_shadow_bufferlight;
406 vec3_t r_editlights_cursorlocation;
407 qboolean r_editlights_lockcursor;
409 extern int con_vislines;
411 void R_Shadow_UncompileWorldLights(void);
412 void R_Shadow_ClearWorldLights(void);
413 void R_Shadow_SaveWorldLights(void);
414 void R_Shadow_LoadWorldLights(void);
415 void R_Shadow_LoadLightsFile(void);
416 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
417 void R_Shadow_EditLights_Reload_f(void);
418 void R_Shadow_ValidateCvars(void);
419 static void R_Shadow_MakeTextures(void);
421 #define EDLIGHTSPRSIZE 8
422 skinframe_t *r_editlights_sprcursor;
423 skinframe_t *r_editlights_sprlight;
424 skinframe_t *r_editlights_sprnoshadowlight;
425 skinframe_t *r_editlights_sprcubemaplight;
426 skinframe_t *r_editlights_sprcubemapnoshadowlight;
427 skinframe_t *r_editlights_sprselection;
429 void R_Shadow_SetShadowMode(void)
431 r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4);
432 r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20;
433 r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer;
434 r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer;
435 r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16);
436 r_shadow_shadowmaplod = -1;
437 r_shadow_shadowmapsize = 0;
438 r_shadow_shadowmapsampler = false;
439 r_shadow_shadowmappcf = 0;
440 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
441 if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
443 switch(vid.renderpath)
445 case RENDERPATH_GL20:
446 if(r_shadow_shadowmapfilterquality < 0)
448 if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
449 r_shadow_shadowmappcf = 1;
450 else if(strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD"))
452 r_shadow_shadowmapsampler = vid.support.arb_shadow;
453 r_shadow_shadowmappcf = 1;
455 else if(strstr(gl_vendor, "ATI"))
456 r_shadow_shadowmappcf = 1;
458 r_shadow_shadowmapsampler = vid.support.arb_shadow;
462 switch (r_shadow_shadowmapfilterquality)
465 r_shadow_shadowmapsampler = vid.support.arb_shadow;
468 r_shadow_shadowmapsampler = vid.support.arb_shadow;
469 r_shadow_shadowmappcf = 1;
472 r_shadow_shadowmappcf = 1;
475 r_shadow_shadowmappcf = 2;
479 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
481 case RENDERPATH_D3D9:
482 case RENDERPATH_D3D10:
483 case RENDERPATH_D3D11:
484 case RENDERPATH_SOFT:
485 r_shadow_shadowmapsampler = false;
486 r_shadow_shadowmappcf = 1;
487 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
489 case RENDERPATH_GL11:
490 case RENDERPATH_GL13:
491 case RENDERPATH_GLES1:
492 case RENDERPATH_GLES2:
498 qboolean R_Shadow_ShadowMappingEnabled(void)
500 switch (r_shadow_shadowmode)
502 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
509 void R_Shadow_FreeShadowMaps(void)
511 R_Shadow_SetShadowMode();
513 R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
517 if (r_shadow_shadowmap2dtexture)
518 R_FreeTexture(r_shadow_shadowmap2dtexture);
519 r_shadow_shadowmap2dtexture = NULL;
521 if (r_shadow_shadowmap2dcolortexture)
522 R_FreeTexture(r_shadow_shadowmap2dcolortexture);
523 r_shadow_shadowmap2dcolortexture = NULL;
525 if (r_shadow_shadowmapvsdcttexture)
526 R_FreeTexture(r_shadow_shadowmapvsdcttexture);
527 r_shadow_shadowmapvsdcttexture = NULL;
530 void r_shadow_start(void)
532 // allocate vertex processing arrays
533 r_shadow_bouncegridpixels = NULL;
534 r_shadow_bouncegridhighpixels = NULL;
535 r_shadow_bouncegridnumpixels = 0;
536 r_shadow_bouncegridtexture = NULL;
537 r_shadow_bouncegriddirectional = false;
538 r_shadow_attenuationgradienttexture = NULL;
539 r_shadow_attenuation2dtexture = NULL;
540 r_shadow_attenuation3dtexture = NULL;
541 r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
542 r_shadow_shadowmap2dtexture = NULL;
543 r_shadow_shadowmap2dcolortexture = NULL;
544 r_shadow_shadowmapvsdcttexture = NULL;
545 r_shadow_shadowmapmaxsize = 0;
546 r_shadow_shadowmapsize = 0;
547 r_shadow_shadowmaplod = 0;
548 r_shadow_shadowmapfilterquality = -1;
549 r_shadow_shadowmapdepthbits = 0;
550 r_shadow_shadowmapvsdct = false;
551 r_shadow_shadowmapsampler = false;
552 r_shadow_shadowmappcf = 0;
555 R_Shadow_FreeShadowMaps();
557 r_shadow_texturepool = NULL;
558 r_shadow_filters_texturepool = NULL;
559 R_Shadow_ValidateCvars();
560 R_Shadow_MakeTextures();
561 maxshadowtriangles = 0;
562 shadowelements = NULL;
563 maxshadowvertices = 0;
564 shadowvertex3f = NULL;
572 shadowmarklist = NULL;
577 shadowsideslist = NULL;
578 r_shadow_buffer_numleafpvsbytes = 0;
579 r_shadow_buffer_visitingleafpvs = NULL;
580 r_shadow_buffer_leafpvs = NULL;
581 r_shadow_buffer_leaflist = NULL;
582 r_shadow_buffer_numsurfacepvsbytes = 0;
583 r_shadow_buffer_surfacepvs = NULL;
584 r_shadow_buffer_surfacelist = NULL;
585 r_shadow_buffer_surfacesides = NULL;
586 r_shadow_buffer_numshadowtrispvsbytes = 0;
587 r_shadow_buffer_shadowtrispvs = NULL;
588 r_shadow_buffer_numlighttrispvsbytes = 0;
589 r_shadow_buffer_lighttrispvs = NULL;
591 r_shadow_usingdeferredprepass = false;
592 r_shadow_prepass_width = r_shadow_prepass_height = 0;
595 static void R_Shadow_FreeDeferred(void);
596 void r_shadow_shutdown(void)
599 R_Shadow_UncompileWorldLights();
601 R_Shadow_FreeShadowMaps();
603 r_shadow_usingdeferredprepass = false;
604 if (r_shadow_prepass_width)
605 R_Shadow_FreeDeferred();
606 r_shadow_prepass_width = r_shadow_prepass_height = 0;
609 r_shadow_bouncegridtexture = NULL;
610 r_shadow_bouncegridpixels = NULL;
611 r_shadow_bouncegridhighpixels = NULL;
612 r_shadow_bouncegridnumpixels = 0;
613 r_shadow_bouncegriddirectional = false;
614 r_shadow_attenuationgradienttexture = NULL;
615 r_shadow_attenuation2dtexture = NULL;
616 r_shadow_attenuation3dtexture = NULL;
617 R_FreeTexturePool(&r_shadow_texturepool);
618 R_FreeTexturePool(&r_shadow_filters_texturepool);
619 maxshadowtriangles = 0;
621 Mem_Free(shadowelements);
622 shadowelements = NULL;
624 Mem_Free(shadowvertex3f);
625 shadowvertex3f = NULL;
628 Mem_Free(vertexupdate);
631 Mem_Free(vertexremap);
637 Mem_Free(shadowmark);
640 Mem_Free(shadowmarklist);
641 shadowmarklist = NULL;
646 Mem_Free(shadowsides);
649 Mem_Free(shadowsideslist);
650 shadowsideslist = NULL;
651 r_shadow_buffer_numleafpvsbytes = 0;
652 if (r_shadow_buffer_visitingleafpvs)
653 Mem_Free(r_shadow_buffer_visitingleafpvs);
654 r_shadow_buffer_visitingleafpvs = NULL;
655 if (r_shadow_buffer_leafpvs)
656 Mem_Free(r_shadow_buffer_leafpvs);
657 r_shadow_buffer_leafpvs = NULL;
658 if (r_shadow_buffer_leaflist)
659 Mem_Free(r_shadow_buffer_leaflist);
660 r_shadow_buffer_leaflist = NULL;
661 r_shadow_buffer_numsurfacepvsbytes = 0;
662 if (r_shadow_buffer_surfacepvs)
663 Mem_Free(r_shadow_buffer_surfacepvs);
664 r_shadow_buffer_surfacepvs = NULL;
665 if (r_shadow_buffer_surfacelist)
666 Mem_Free(r_shadow_buffer_surfacelist);
667 r_shadow_buffer_surfacelist = NULL;
668 if (r_shadow_buffer_surfacesides)
669 Mem_Free(r_shadow_buffer_surfacesides);
670 r_shadow_buffer_surfacesides = NULL;
671 r_shadow_buffer_numshadowtrispvsbytes = 0;
672 if (r_shadow_buffer_shadowtrispvs)
673 Mem_Free(r_shadow_buffer_shadowtrispvs);
674 r_shadow_buffer_numlighttrispvsbytes = 0;
675 if (r_shadow_buffer_lighttrispvs)
676 Mem_Free(r_shadow_buffer_lighttrispvs);
679 void r_shadow_newmap(void)
681 if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL;
682 if (r_shadow_lightcorona) R_SkinFrame_MarkUsed(r_shadow_lightcorona);
683 if (r_editlights_sprcursor) R_SkinFrame_MarkUsed(r_editlights_sprcursor);
684 if (r_editlights_sprlight) R_SkinFrame_MarkUsed(r_editlights_sprlight);
685 if (r_editlights_sprnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprnoshadowlight);
686 if (r_editlights_sprcubemaplight) R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight);
687 if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight);
688 if (r_editlights_sprselection) R_SkinFrame_MarkUsed(r_editlights_sprselection);
689 if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname)))
690 R_Shadow_EditLights_Reload_f();
693 void R_Shadow_Init(void)
695 Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
696 Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
697 Cvar_RegisterVariable(&r_shadow_usebihculling);
698 Cvar_RegisterVariable(&r_shadow_usenormalmap);
699 Cvar_RegisterVariable(&r_shadow_debuglight);
700 Cvar_RegisterVariable(&r_shadow_deferred);
701 Cvar_RegisterVariable(&r_shadow_deferred_8bitrange);
702 // Cvar_RegisterVariable(&r_shadow_deferred_fp);
703 Cvar_RegisterVariable(&r_shadow_gloss);
704 Cvar_RegisterVariable(&r_shadow_gloss2intensity);
705 Cvar_RegisterVariable(&r_shadow_glossintensity);
706 Cvar_RegisterVariable(&r_shadow_glossexponent);
707 Cvar_RegisterVariable(&r_shadow_gloss2exponent);
708 Cvar_RegisterVariable(&r_shadow_glossexact);
709 Cvar_RegisterVariable(&r_shadow_lightattenuationdividebias);
710 Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale);
711 Cvar_RegisterVariable(&r_shadow_lightintensityscale);
712 Cvar_RegisterVariable(&r_shadow_lightradiusscale);
713 Cvar_RegisterVariable(&r_shadow_projectdistance);
714 Cvar_RegisterVariable(&r_shadow_frontsidecasting);
715 Cvar_RegisterVariable(&r_shadow_realtime_dlight);
716 Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
717 Cvar_RegisterVariable(&r_shadow_realtime_dlight_svbspculling);
718 Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
719 Cvar_RegisterVariable(&r_shadow_realtime_world);
720 Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
721 Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
722 Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
723 Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
724 Cvar_RegisterVariable(&r_shadow_realtime_world_compilesvbsp);
725 Cvar_RegisterVariable(&r_shadow_realtime_world_compileportalculling);
726 Cvar_RegisterVariable(&r_shadow_scissor);
727 Cvar_RegisterVariable(&r_shadow_shadowmapping);
728 Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct);
729 Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality);
730 Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits);
731 Cvar_RegisterVariable(&r_shadow_shadowmapping_precision);
732 Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize);
733 Cvar_RegisterVariable(&r_shadow_shadowmapping_minsize);
734 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_bias);
735 // Cvar_RegisterVariable(&r_shadow_shadowmapping_lod_scale);
736 Cvar_RegisterVariable(&r_shadow_shadowmapping_bordersize);
737 Cvar_RegisterVariable(&r_shadow_shadowmapping_nearclip);
738 Cvar_RegisterVariable(&r_shadow_shadowmapping_bias);
739 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor);
740 Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset);
741 Cvar_RegisterVariable(&r_shadow_sortsurfaces);
742 Cvar_RegisterVariable(&r_shadow_polygonfactor);
743 Cvar_RegisterVariable(&r_shadow_polygonoffset);
744 Cvar_RegisterVariable(&r_shadow_texture3d);
745 Cvar_RegisterVariable(&r_shadow_bouncegrid);
746 Cvar_RegisterVariable(&r_shadow_bouncegrid_airstepmax);
747 Cvar_RegisterVariable(&r_shadow_bouncegrid_airstepsize);
748 Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse);
749 Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading);
750 Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier);
751 Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels);
752 Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting);
753 Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity);
754 Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale);
755 Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce);
756 Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity);
757 Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity);
758 Cvar_RegisterVariable(&r_shadow_bouncegrid_photons);
759 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingx);
760 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingy);
761 Cvar_RegisterVariable(&r_shadow_bouncegrid_spacingz);
762 Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom);
763 Cvar_RegisterVariable(&r_shadow_bouncegrid_static);
764 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading);
765 Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons);
766 Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval);
767 Cvar_RegisterVariable(&r_shadow_bouncegrid_x);
768 Cvar_RegisterVariable(&r_shadow_bouncegrid_y);
769 Cvar_RegisterVariable(&r_shadow_bouncegrid_z);
770 Cvar_RegisterVariable(&r_coronas);
771 Cvar_RegisterVariable(&r_coronas_occlusionsizescale);
772 Cvar_RegisterVariable(&r_coronas_occlusionquery);
773 Cvar_RegisterVariable(&gl_flashblend);
774 Cvar_RegisterVariable(&gl_ext_separatestencil);
775 Cvar_RegisterVariable(&gl_ext_stenciltwoside);
776 R_Shadow_EditLights_Init();
777 Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128);
778 maxshadowtriangles = 0;
779 shadowelements = NULL;
780 maxshadowvertices = 0;
781 shadowvertex3f = NULL;
789 shadowmarklist = NULL;
794 shadowsideslist = NULL;
795 r_shadow_buffer_numleafpvsbytes = 0;
796 r_shadow_buffer_visitingleafpvs = NULL;
797 r_shadow_buffer_leafpvs = NULL;
798 r_shadow_buffer_leaflist = NULL;
799 r_shadow_buffer_numsurfacepvsbytes = 0;
800 r_shadow_buffer_surfacepvs = NULL;
801 r_shadow_buffer_surfacelist = NULL;
802 r_shadow_buffer_surfacesides = NULL;
803 r_shadow_buffer_shadowtrispvs = NULL;
804 r_shadow_buffer_lighttrispvs = NULL;
805 R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL);
808 matrix4x4_t matrix_attenuationxyz =
811 {0.5, 0.0, 0.0, 0.5},
812 {0.0, 0.5, 0.0, 0.5},
813 {0.0, 0.0, 0.5, 0.5},
818 matrix4x4_t matrix_attenuationz =
821 {0.0, 0.0, 0.5, 0.5},
822 {0.0, 0.0, 0.0, 0.5},
823 {0.0, 0.0, 0.0, 0.5},
828 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale)
830 numvertices = ((numvertices + 255) & ~255) * vertscale;
831 numtriangles = ((numtriangles + 255) & ~255) * triscale;
832 // make sure shadowelements is big enough for this volume
833 if (maxshadowtriangles < numtriangles)
835 maxshadowtriangles = numtriangles;
837 Mem_Free(shadowelements);
838 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[3]));
840 // make sure shadowvertex3f is big enough for this volume
841 if (maxshadowvertices < numvertices)
843 maxshadowvertices = numvertices;
845 Mem_Free(shadowvertex3f);
846 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[3]));
850 static void R_Shadow_EnlargeLeafSurfaceTrisBuffer(int numleafs, int numsurfaces, int numshadowtriangles, int numlighttriangles)
852 int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
853 int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
854 int numshadowtrispvsbytes = (((numshadowtriangles + 7) >> 3) + 255) & ~255;
855 int numlighttrispvsbytes = (((numlighttriangles + 7) >> 3) + 255) & ~255;
856 if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
858 if (r_shadow_buffer_visitingleafpvs)
859 Mem_Free(r_shadow_buffer_visitingleafpvs);
860 if (r_shadow_buffer_leafpvs)
861 Mem_Free(r_shadow_buffer_leafpvs);
862 if (r_shadow_buffer_leaflist)
863 Mem_Free(r_shadow_buffer_leaflist);
864 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
865 r_shadow_buffer_visitingleafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
866 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
867 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
869 if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
871 if (r_shadow_buffer_surfacepvs)
872 Mem_Free(r_shadow_buffer_surfacepvs);
873 if (r_shadow_buffer_surfacelist)
874 Mem_Free(r_shadow_buffer_surfacelist);
875 if (r_shadow_buffer_surfacesides)
876 Mem_Free(r_shadow_buffer_surfacesides);
877 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
878 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
879 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
880 r_shadow_buffer_surfacesides = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
882 if (r_shadow_buffer_numshadowtrispvsbytes < numshadowtrispvsbytes)
884 if (r_shadow_buffer_shadowtrispvs)
885 Mem_Free(r_shadow_buffer_shadowtrispvs);
886 r_shadow_buffer_numshadowtrispvsbytes = numshadowtrispvsbytes;
887 r_shadow_buffer_shadowtrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numshadowtrispvsbytes);
889 if (r_shadow_buffer_numlighttrispvsbytes < numlighttrispvsbytes)
891 if (r_shadow_buffer_lighttrispvs)
892 Mem_Free(r_shadow_buffer_lighttrispvs);
893 r_shadow_buffer_numlighttrispvsbytes = numlighttrispvsbytes;
894 r_shadow_buffer_lighttrispvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numlighttrispvsbytes);
898 void R_Shadow_PrepareShadowMark(int numtris)
900 // make sure shadowmark is big enough for this volume
901 if (maxshadowmark < numtris)
903 maxshadowmark = numtris;
905 Mem_Free(shadowmark);
907 Mem_Free(shadowmarklist);
908 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
909 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
913 // if shadowmarkcount wrapped we clear the array and adjust accordingly
914 if (shadowmarkcount == 0)
917 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
922 void R_Shadow_PrepareShadowSides(int numtris)
924 if (maxshadowsides < numtris)
926 maxshadowsides = numtris;
928 Mem_Free(shadowsides);
930 Mem_Free(shadowsideslist);
931 shadowsides = (unsigned char *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsides));
932 shadowsideslist = (int *)Mem_Alloc(r_main_mempool, maxshadowsides * sizeof(*shadowsideslist));
937 static int R_Shadow_ConstructShadowVolume_ZFail(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
940 int outtriangles = 0, outvertices = 0;
943 float ratio, direction[3], projectvector[3];
945 if (projectdirection)
946 VectorScale(projectdirection, projectdistance, projectvector);
948 VectorClear(projectvector);
950 // create the vertices
951 if (projectdirection)
953 for (i = 0;i < numshadowmarktris;i++)
955 element = inelement3i + shadowmarktris[i] * 3;
956 for (j = 0;j < 3;j++)
958 if (vertexupdate[element[j]] != vertexupdatenum)
960 vertexupdate[element[j]] = vertexupdatenum;
961 vertexremap[element[j]] = outvertices;
962 vertex = invertex3f + element[j] * 3;
963 // project one copy of the vertex according to projectvector
964 VectorCopy(vertex, outvertex3f);
965 VectorAdd(vertex, projectvector, (outvertex3f + 3));
974 for (i = 0;i < numshadowmarktris;i++)
976 element = inelement3i + shadowmarktris[i] * 3;
977 for (j = 0;j < 3;j++)
979 if (vertexupdate[element[j]] != vertexupdatenum)
981 vertexupdate[element[j]] = vertexupdatenum;
982 vertexremap[element[j]] = outvertices;
983 vertex = invertex3f + element[j] * 3;
984 // project one copy of the vertex to the sphere radius of the light
985 // (FIXME: would projecting it to the light box be better?)
986 VectorSubtract(vertex, projectorigin, direction);
987 ratio = projectdistance / VectorLength(direction);
988 VectorCopy(vertex, outvertex3f);
989 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
997 if (r_shadow_frontsidecasting.integer)
999 for (i = 0;i < numshadowmarktris;i++)
1001 int remappedelement[3];
1003 const int *neighbortriangle;
1005 markindex = shadowmarktris[i] * 3;
1006 element = inelement3i + markindex;
1007 neighbortriangle = inneighbor3i + markindex;
1008 // output the front and back triangles
1009 outelement3i[0] = vertexremap[element[0]];
1010 outelement3i[1] = vertexremap[element[1]];
1011 outelement3i[2] = vertexremap[element[2]];
1012 outelement3i[3] = vertexremap[element[2]] + 1;
1013 outelement3i[4] = vertexremap[element[1]] + 1;
1014 outelement3i[5] = vertexremap[element[0]] + 1;
1018 // output the sides (facing outward from this triangle)
1019 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1021 remappedelement[0] = vertexremap[element[0]];
1022 remappedelement[1] = vertexremap[element[1]];
1023 outelement3i[0] = remappedelement[1];
1024 outelement3i[1] = remappedelement[0];
1025 outelement3i[2] = remappedelement[0] + 1;
1026 outelement3i[3] = remappedelement[1];
1027 outelement3i[4] = remappedelement[0] + 1;
1028 outelement3i[5] = remappedelement[1] + 1;
1033 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1035 remappedelement[1] = vertexremap[element[1]];
1036 remappedelement[2] = vertexremap[element[2]];
1037 outelement3i[0] = remappedelement[2];
1038 outelement3i[1] = remappedelement[1];
1039 outelement3i[2] = remappedelement[1] + 1;
1040 outelement3i[3] = remappedelement[2];
1041 outelement3i[4] = remappedelement[1] + 1;
1042 outelement3i[5] = remappedelement[2] + 1;
1047 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1049 remappedelement[0] = vertexremap[element[0]];
1050 remappedelement[2] = vertexremap[element[2]];
1051 outelement3i[0] = remappedelement[0];
1052 outelement3i[1] = remappedelement[2];
1053 outelement3i[2] = remappedelement[2] + 1;
1054 outelement3i[3] = remappedelement[0];
1055 outelement3i[4] = remappedelement[2] + 1;
1056 outelement3i[5] = remappedelement[0] + 1;
1065 for (i = 0;i < numshadowmarktris;i++)
1067 int remappedelement[3];
1069 const int *neighbortriangle;
1071 markindex = shadowmarktris[i] * 3;
1072 element = inelement3i + markindex;
1073 neighbortriangle = inneighbor3i + markindex;
1074 // output the front and back triangles
1075 outelement3i[0] = vertexremap[element[2]];
1076 outelement3i[1] = vertexremap[element[1]];
1077 outelement3i[2] = vertexremap[element[0]];
1078 outelement3i[3] = vertexremap[element[0]] + 1;
1079 outelement3i[4] = vertexremap[element[1]] + 1;
1080 outelement3i[5] = vertexremap[element[2]] + 1;
1084 // output the sides (facing outward from this triangle)
1085 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
1087 remappedelement[0] = vertexremap[element[0]];
1088 remappedelement[1] = vertexremap[element[1]];
1089 outelement3i[0] = remappedelement[0];
1090 outelement3i[1] = remappedelement[1];
1091 outelement3i[2] = remappedelement[1] + 1;
1092 outelement3i[3] = remappedelement[0];
1093 outelement3i[4] = remappedelement[1] + 1;
1094 outelement3i[5] = remappedelement[0] + 1;
1099 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
1101 remappedelement[1] = vertexremap[element[1]];
1102 remappedelement[2] = vertexremap[element[2]];
1103 outelement3i[0] = remappedelement[1];
1104 outelement3i[1] = remappedelement[2];
1105 outelement3i[2] = remappedelement[2] + 1;
1106 outelement3i[3] = remappedelement[1];
1107 outelement3i[4] = remappedelement[2] + 1;
1108 outelement3i[5] = remappedelement[1] + 1;
1113 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
1115 remappedelement[0] = vertexremap[element[0]];
1116 remappedelement[2] = vertexremap[element[2]];
1117 outelement3i[0] = remappedelement[2];
1118 outelement3i[1] = remappedelement[0];
1119 outelement3i[2] = remappedelement[0] + 1;
1120 outelement3i[3] = remappedelement[2];
1121 outelement3i[4] = remappedelement[0] + 1;
1122 outelement3i[5] = remappedelement[2] + 1;
1130 *outnumvertices = outvertices;
1131 return outtriangles;
1134 static int R_Shadow_ConstructShadowVolume_ZPass(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, const float *projectdirection, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
1137 int outtriangles = 0, outvertices = 0;
1139 const float *vertex;
1140 float ratio, direction[3], projectvector[3];
1143 if (projectdirection)
1144 VectorScale(projectdirection, projectdistance, projectvector);
1146 VectorClear(projectvector);
1148 for (i = 0;i < numshadowmarktris;i++)
1150 int remappedelement[3];
1152 const int *neighbortriangle;
1154 markindex = shadowmarktris[i] * 3;
1155 neighbortriangle = inneighbor3i + markindex;
1156 side[0] = shadowmark[neighbortriangle[0]] == shadowmarkcount;
1157 side[1] = shadowmark[neighbortriangle[1]] == shadowmarkcount;
1158 side[2] = shadowmark[neighbortriangle[2]] == shadowmarkcount;
1159 if (side[0] + side[1] + side[2] == 0)
1163 element = inelement3i + markindex;
1165 // create the vertices
1166 for (j = 0;j < 3;j++)
1168 if (side[j] + side[j+1] == 0)
1171 if (vertexupdate[k] != vertexupdatenum)
1173 vertexupdate[k] = vertexupdatenum;
1174 vertexremap[k] = outvertices;
1175 vertex = invertex3f + k * 3;
1176 VectorCopy(vertex, outvertex3f);
1177 if (projectdirection)
1179 // project one copy of the vertex according to projectvector
1180 VectorAdd(vertex, projectvector, (outvertex3f + 3));
1184 // project one copy of the vertex to the sphere radius of the light
1185 // (FIXME: would projecting it to the light box be better?)
1186 VectorSubtract(vertex, projectorigin, direction);
1187 ratio = projectdistance / VectorLength(direction);
1188 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
1195 // output the sides (facing outward from this triangle)
1198 remappedelement[0] = vertexremap[element[0]];
1199 remappedelement[1] = vertexremap[element[1]];
1200 outelement3i[0] = remappedelement[1];
1201 outelement3i[1] = remappedelement[0];
1202 outelement3i[2] = remappedelement[0] + 1;
1203 outelement3i[3] = remappedelement[1];
1204 outelement3i[4] = remappedelement[0] + 1;
1205 outelement3i[5] = remappedelement[1] + 1;
1212 remappedelement[1] = vertexremap[element[1]];
1213 remappedelement[2] = vertexremap[element[2]];
1214 outelement3i[0] = remappedelement[2];
1215 outelement3i[1] = remappedelement[1];
1216 outelement3i[2] = remappedelement[1] + 1;
1217 outelement3i[3] = remappedelement[2];
1218 outelement3i[4] = remappedelement[1] + 1;
1219 outelement3i[5] = remappedelement[2] + 1;
1226 remappedelement[0] = vertexremap[element[0]];
1227 remappedelement[2] = vertexremap[element[2]];
1228 outelement3i[0] = remappedelement[0];
1229 outelement3i[1] = remappedelement[2];
1230 outelement3i[2] = remappedelement[2] + 1;
1231 outelement3i[3] = remappedelement[0];
1232 outelement3i[4] = remappedelement[2] + 1;
1233 outelement3i[5] = remappedelement[0] + 1;
1240 *outnumvertices = outvertices;
1241 return outtriangles;
1244 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
1250 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1252 tend = firsttriangle + numtris;
1253 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1255 // surface box entirely inside light box, no box cull
1256 if (projectdirection)
1258 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1260 TriangleNormal(invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3, normal);
1261 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1262 shadowmarklist[numshadowmark++] = t;
1267 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1268 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
1269 shadowmarklist[numshadowmark++] = t;
1274 // surface box not entirely inside light box, cull each triangle
1275 if (projectdirection)
1277 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1279 v[0] = invertex3f + e[0] * 3;
1280 v[1] = invertex3f + e[1] * 3;
1281 v[2] = invertex3f + e[2] * 3;
1282 TriangleNormal(v[0], v[1], v[2], normal);
1283 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1284 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1285 shadowmarklist[numshadowmark++] = t;
1290 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1292 v[0] = invertex3f + e[0] * 3;
1293 v[1] = invertex3f + e[1] * 3;
1294 v[2] = invertex3f + e[2] * 3;
1295 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1296 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1297 shadowmarklist[numshadowmark++] = t;
1303 qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs)
1308 if (r_shadow_compilingrtlight || !r_shadow_frontsidecasting.integer || !r_shadow_usezpassifpossible.integer)
1310 // check if the shadow volume intersects the near plane
1312 // a ray between the eye and light origin may intersect the caster,
1313 // indicating that the shadow may touch the eye location, however we must
1314 // test the near plane (a polygon), not merely the eye location, so it is
1315 // easiest to enlarge the caster bounding shape slightly for this.
1321 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, const vec3_t projectdirection, float projectdistance, int nummarktris, const int *marktris, vec3_t trismins, vec3_t trismaxs)
1323 int i, tris, outverts;
1324 if (projectdistance < 0.1)
1326 Con_Printf("R_Shadow_Volume: projectdistance %f\n", projectdistance);
1329 if (!numverts || !nummarktris)
1331 // make sure shadowelements is big enough for this volume
1332 if (maxshadowtriangles < nummarktris*8 || maxshadowvertices < numverts*2)
1333 R_Shadow_ResizeShadowArrays(numverts, nummarktris, 2, 8);
1335 if (maxvertexupdate < numverts)
1337 maxvertexupdate = numverts;
1339 Mem_Free(vertexupdate);
1341 Mem_Free(vertexremap);
1342 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1343 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
1344 vertexupdatenum = 0;
1347 if (vertexupdatenum == 0)
1349 vertexupdatenum = 1;
1350 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
1351 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
1354 for (i = 0;i < nummarktris;i++)
1355 shadowmark[marktris[i]] = shadowmarkcount;
1357 if (r_shadow_compilingrtlight)
1359 // if we're compiling an rtlight, capture the mesh
1360 //tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1361 //Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zpass, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1362 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1363 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements);
1365 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
1367 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1368 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1369 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1373 // decide which type of shadow to generate and set stencil mode
1374 R_Shadow_RenderMode_StencilShadowVolumes(R_Shadow_UseZPass(trismins, trismaxs));
1375 // generate the sides or a solid volume, depending on type
1376 if (r_shadow_rendermode >= R_SHADOW_RENDERMODE_ZPASS_STENCIL && r_shadow_rendermode <= R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE)
1377 tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1379 tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
1380 r_refdef.stats.lights_dynamicshadowtriangles += tris;
1381 r_refdef.stats.lights_shadowtriangles += tris;
1382 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
1384 // increment stencil if frontface is infront of depthbuffer
1385 GL_CullFace(r_refdef.view.cullface_front);
1386 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
1387 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1388 // decrement stencil if backface is infront of depthbuffer
1389 GL_CullFace(r_refdef.view.cullface_back);
1390 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
1392 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
1394 // decrement stencil if backface is behind depthbuffer
1395 GL_CullFace(r_refdef.view.cullface_front);
1396 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
1397 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1398 // increment stencil if frontface is behind depthbuffer
1399 GL_CullFace(r_refdef.view.cullface_back);
1400 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
1402 R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL);
1403 R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
1407 int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias)
1409 // p1, p2, p3 are in the cubemap's local coordinate system
1410 // bias = border/(size - border)
1413 float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1414 dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2),
1415 dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3);
1416 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1418 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1419 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1420 | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1421 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1423 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1424 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1425 | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1427 dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1428 dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2),
1429 dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3);
1430 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1432 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1433 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1434 | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1435 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1437 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1438 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1439 | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1441 dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1442 dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2),
1443 dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3);
1444 if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3)
1446 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1447 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1448 | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1449 if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3)
1451 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1452 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1453 | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1458 int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias)
1460 vec3_t center, radius, lightcenter, lightradius, pmin, pmax;
1461 float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2;
1464 VectorSubtract(maxs, mins, radius);
1465 VectorScale(radius, 0.5f, radius);
1466 VectorAdd(mins, radius, center);
1467 Matrix4x4_Transform(worldtolight, center, lightcenter);
1468 Matrix4x4_Transform3x3(radiustolight, radius, lightradius);
1469 VectorSubtract(lightcenter, lightradius, pmin);
1470 VectorAdd(lightcenter, lightradius, pmax);
1472 dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1),
1473 dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2);
1474 if(ap1 > bias*an1 && ap2 > bias*an2)
1476 | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2))
1477 | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1478 if(an1 > bias*ap1 && an2 > bias*ap2)
1480 | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2))
1481 | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1483 dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1),
1484 dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2);
1485 if(ap1 > bias*an1 && ap2 > bias*an2)
1487 | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4))
1488 | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1489 if(an1 > bias*ap1 && an2 > bias*ap2)
1491 | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4))
1492 | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1494 dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1),
1495 dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2);
1496 if(ap1 > bias*an1 && ap2 > bias*an2)
1498 | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0))
1499 | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1500 if(an1 > bias*ap1 && an2 > bias*ap2)
1502 | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0))
1503 | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1508 #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias)
1510 int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias)
1512 // p is in the cubemap's local coordinate system
1513 // bias = border/(size - border)
1514 float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn);
1515 float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn);
1516 float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn);
1518 if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2));
1519 if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2));
1520 if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4));
1521 if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4));
1522 if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0));
1523 if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0));
1527 int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border)
1531 int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 };
1532 float scale = (size - 2*border)/size, len;
1533 float bias = border / (float)(size - border), dp, dn, ap, an;
1534 // check if cone enclosing side would cross frustum plane
1535 scale = 2 / (scale*scale + 2);
1536 for (i = 0;i < 5;i++)
1538 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125)
1540 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n);
1541 len = scale*VectorLength2(n);
1542 if(n[0]*n[0] > len) sides &= n[0] < 0 ? ~(1<<0) : ~(2 << 0);
1543 if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2);
1544 if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4);
1546 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125)
1548 Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n);
1549 len = scale*VectorLength(n);
1550 if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0);
1551 if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2);
1552 if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4);
1554 // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results
1555 // check if frustum corners/origin cross plane sides
1557 // infinite version, assumes frustum corners merely give direction and extend to infinite distance
1558 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p);
1559 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1560 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1561 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1562 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1563 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1564 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1565 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1566 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1567 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1568 for (i = 0;i < 4;i++)
1570 Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n);
1571 VectorSubtract(n, p, n);
1572 dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn);
1573 if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2);
1574 if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2);
1575 dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn);
1576 if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4);
1577 if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4);
1578 dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn);
1579 if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0);
1580 if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0);
1583 // finite version, assumes corners are a finite distance from origin dependent on far plane
1584 for (i = 0;i < 5;i++)
1586 Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p);
1587 dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn);
1588 masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2));
1589 masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2));
1590 dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn);
1591 masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4));
1592 masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4));
1593 dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn);
1594 masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0));
1595 masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0));
1598 return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5];
1601 int R_Shadow_ChooseSidesFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const matrix4x4_t *worldtolight, const vec3_t projectorigin, const vec3_t projectdirection, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs, int *totals)
1609 int mask, surfacemask = 0;
1610 if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
1612 bias = r_shadow_shadowmapborder / (float)(r_shadow_shadowmapmaxsize - r_shadow_shadowmapborder);
1613 tend = firsttriangle + numtris;
1614 if (BoxInsideBox(surfacemins, surfacemaxs, lightmins, lightmaxs))
1616 // surface box entirely inside light box, no box cull
1617 if (projectdirection)
1619 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1621 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1622 TriangleNormal(v[0], v[1], v[2], normal);
1623 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0))
1625 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1626 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1627 surfacemask |= mask;
1630 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1631 shadowsides[numshadowsides] = mask;
1632 shadowsideslist[numshadowsides++] = t;
1639 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1641 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1642 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]))
1644 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1645 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1646 surfacemask |= mask;
1649 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1650 shadowsides[numshadowsides] = mask;
1651 shadowsideslist[numshadowsides++] = t;
1659 // surface box not entirely inside light box, cull each triangle
1660 if (projectdirection)
1662 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1664 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1665 TriangleNormal(v[0], v[1], v[2], normal);
1666 if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0)
1667 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1669 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1670 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1671 surfacemask |= mask;
1674 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1675 shadowsides[numshadowsides] = mask;
1676 shadowsideslist[numshadowsides++] = t;
1683 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
1685 v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3;
1686 if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
1687 && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs))
1689 Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]);
1690 mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias);
1691 surfacemask |= mask;
1694 totals[0] += mask&1, totals[1] += (mask>>1)&1, totals[2] += (mask>>2)&1, totals[3] += (mask>>3)&1, totals[4] += (mask>>4)&1, totals[5] += mask>>5;
1695 shadowsides[numshadowsides] = mask;
1696 shadowsideslist[numshadowsides++] = t;
1705 void R_Shadow_ShadowMapFromList(int numverts, int numtris, const float *vertex3f, const int *elements, int numsidetris, const int *sidetotals, const unsigned char *sides, const int *sidetris)
1707 int i, j, outtriangles = 0;
1708 int *outelement3i[6];
1709 if (!numverts || !numsidetris || !r_shadow_compilingrtlight)
1711 outtriangles = sidetotals[0] + sidetotals[1] + sidetotals[2] + sidetotals[3] + sidetotals[4] + sidetotals[5];
1712 // make sure shadowelements is big enough for this mesh
1713 if (maxshadowtriangles < outtriangles)
1714 R_Shadow_ResizeShadowArrays(0, outtriangles, 0, 1);
1716 // compute the offset and size of the separate index lists for each cubemap side
1718 for (i = 0;i < 6;i++)
1720 outelement3i[i] = shadowelements + outtriangles * 3;
1721 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sideoffsets[i] = outtriangles;
1722 r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap->sidetotals[i] = sidetotals[i];
1723 outtriangles += sidetotals[i];
1726 // gather up the (sparse) triangles into separate index lists for each cubemap side
1727 for (i = 0;i < numsidetris;i++)
1729 const int *element = elements + sidetris[i] * 3;
1730 for (j = 0;j < 6;j++)
1732 if (sides[i] & (1 << j))
1734 outelement3i[j][0] = element[0];
1735 outelement3i[j][1] = element[1];
1736 outelement3i[j][2] = element[2];
1737 outelement3i[j] += 3;
1742 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, outtriangles, shadowelements);
1745 static void R_Shadow_MakeTextures_MakeCorona(void)
1749 unsigned char pixels[32][32][4];
1750 for (y = 0;y < 32;y++)
1752 dy = (y - 15.5f) * (1.0f / 16.0f);
1753 for (x = 0;x < 32;x++)
1755 dx = (x - 15.5f) * (1.0f / 16.0f);
1756 a = (int)(((1.0f / (dx * dx + dy * dy + 0.2f)) - (1.0f / (1.0f + 0.2))) * 32.0f / (1.0f / (1.0f + 0.2)));
1757 a = bound(0, a, 255);
1758 pixels[y][x][0] = a;
1759 pixels[y][x][1] = a;
1760 pixels[y][x][2] = a;
1761 pixels[y][x][3] = 255;
1764 r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false);
1767 static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z)
1769 float dist = sqrt(x*x+y*y+z*z);
1770 float intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1771 // note this code could suffer byte order issues except that it is multiplying by an integer that reads the same both ways
1772 return (unsigned char)bound(0, intensity * 256.0f, 255) * 0x01010101;
1775 static void R_Shadow_MakeTextures(void)
1778 float intensity, dist;
1780 R_Shadow_FreeShadowMaps();
1781 R_FreeTexturePool(&r_shadow_texturepool);
1782 r_shadow_texturepool = R_AllocTexturePool();
1783 r_shadow_attenlinearscale = r_shadow_lightattenuationlinearscale.value;
1784 r_shadow_attendividebias = r_shadow_lightattenuationdividebias.value;
1785 data = (unsigned int *)Mem_Alloc(tempmempool, max(max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE, ATTEN2DSIZE*ATTEN2DSIZE), ATTEN1DSIZE) * 4);
1786 // the table includes one additional value to avoid the need to clamp indexing due to minor math errors
1787 for (x = 0;x <= ATTENTABLESIZE;x++)
1789 dist = (x + 0.5f) * (1.0f / ATTENTABLESIZE) * (1.0f / 0.9375);
1790 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
1791 r_shadow_attentable[x] = bound(0, intensity, 1);
1793 // 1D gradient texture
1794 for (x = 0;x < ATTEN1DSIZE;x++)
1795 data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0);
1796 r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1797 // 2D circle texture
1798 for (y = 0;y < ATTEN2DSIZE;y++)
1799 for (x = 0;x < ATTEN2DSIZE;x++)
1800 data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0);
1801 r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1802 // 3D sphere texture
1803 if (r_shadow_texture3d.integer && vid.support.ext_texture_3d)
1805 for (z = 0;z < ATTEN3DSIZE;z++)
1806 for (y = 0;y < ATTEN3DSIZE;y++)
1807 for (x = 0;x < ATTEN3DSIZE;x++)
1808 data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375));
1809 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL);
1812 r_shadow_attenuation3dtexture = NULL;
1815 R_Shadow_MakeTextures_MakeCorona();
1817 // Editor light sprites
1818 r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1835 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1836 r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1853 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1854 r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1871 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1872 r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1889 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1890 r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *)
1907 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1908 r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *)
1925 , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic);
1928 void R_Shadow_ValidateCvars(void)
1930 if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d)
1931 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
1932 if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil)
1933 Cvar_SetValueQuick(&gl_ext_separatestencil, 0);
1934 if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side)
1935 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
1938 void R_Shadow_RenderMode_Begin(void)
1944 R_Shadow_ValidateCvars();
1946 if (!r_shadow_attenuation2dtexture
1947 || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
1948 || r_shadow_lightattenuationdividebias.value != r_shadow_attendividebias
1949 || r_shadow_lightattenuationlinearscale.value != r_shadow_attenlinearscale)
1950 R_Shadow_MakeTextures();
1953 R_Mesh_ResetTextureState();
1954 GL_BlendFunc(GL_ONE, GL_ZERO);
1955 GL_AlphaTest(false);
1956 GL_DepthRange(0, 1);
1957 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
1959 GL_DepthMask(false);
1960 GL_Color(0, 0, 0, 1);
1961 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
1963 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1965 if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil)
1967 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL;
1968 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL;
1970 else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side)
1972 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE;
1973 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE;
1977 r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCIL;
1978 r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL;
1981 switch(vid.renderpath)
1983 case RENDERPATH_GL20:
1984 case RENDERPATH_D3D9:
1985 case RENDERPATH_D3D10:
1986 case RENDERPATH_D3D11:
1987 case RENDERPATH_SOFT:
1988 case RENDERPATH_GLES2:
1989 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
1991 case RENDERPATH_GL11:
1992 case RENDERPATH_GL13:
1993 case RENDERPATH_GLES1:
1994 if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture)
1995 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN;
1996 else if (r_textureunits.integer >= 3 && vid.texunits >= 3)
1997 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN;
1998 else if (r_textureunits.integer >= 2 && vid.texunits >= 2)
1999 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN;
2001 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
2007 qglGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);CHECKGLERROR
2008 qglGetIntegerv(GL_READ_BUFFER, &readbuffer);CHECKGLERROR
2009 r_shadow_drawbuffer = drawbuffer;
2010 r_shadow_readbuffer = readbuffer;
2012 r_shadow_cullface_front = r_refdef.view.cullface_front;
2013 r_shadow_cullface_back = r_refdef.view.cullface_back;
2016 void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
2018 rsurface.rtlight = rtlight;
2021 void R_Shadow_RenderMode_Reset(void)
2023 R_Mesh_SetMainRenderTargets();
2024 R_SetViewport(&r_refdef.view.viewport);
2025 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
2026 R_Mesh_ResetTextureState();
2027 GL_DepthRange(0, 1);
2029 GL_DepthMask(false);
2030 GL_DepthFunc(GL_LEQUAL);
2031 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2032 r_refdef.view.cullface_front = r_shadow_cullface_front;
2033 r_refdef.view.cullface_back = r_shadow_cullface_back;
2034 GL_CullFace(r_refdef.view.cullface_back);
2035 GL_Color(1, 1, 1, 1);
2036 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2037 GL_BlendFunc(GL_ONE, GL_ZERO);
2038 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
2039 r_shadow_usingshadowmap2d = false;
2040 r_shadow_usingshadowmaportho = false;
2041 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2044 void R_Shadow_ClearStencil(void)
2046 GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
2047 r_refdef.stats.lights_clears++;
2050 void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
2052 r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
2053 if (r_shadow_rendermode == mode)
2055 R_Shadow_RenderMode_Reset();
2056 GL_DepthFunc(GL_LESS);
2057 GL_ColorMask(0, 0, 0, 0);
2058 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2059 GL_CullFace(GL_NONE);
2060 R_SetupShader_DepthOrShadow();
2061 r_shadow_rendermode = mode;
2066 case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
2067 case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
2068 R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
2070 case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
2071 case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
2072 R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
2077 static void R_Shadow_MakeVSDCT(void)
2079 // maps to a 2x3 texture rectangle with normalized coordinates
2084 // stores abs(dir.xy), offset.xy/2.5
2085 unsigned char data[4*6] =
2087 255, 0, 0x33, 0x33, // +X: <1, 0>, <0.5, 0.5>
2088 255, 0, 0x99, 0x33, // -X: <1, 0>, <1.5, 0.5>
2089 0, 255, 0x33, 0x99, // +Y: <0, 1>, <0.5, 1.5>
2090 0, 255, 0x99, 0x99, // -Y: <0, 1>, <1.5, 1.5>
2091 0, 0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5>
2092 0, 0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5>
2094 r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
2097 static void R_Shadow_MakeShadowMap(int side, int size)
2099 switch (r_shadow_shadowmode)
2101 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
2102 if (r_shadow_shadowmap2dtexture) return;
2103 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);
2104 r_shadow_shadowmap2dcolortexture = NULL;
2105 switch(vid.renderpath)
2108 case RENDERPATH_D3D9:
2109 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);
2110 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2114 r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
2122 // render depth into the fbo, do not render color at all
2123 // validate the fbo now
2127 qglDrawBuffer(GL_NONE);CHECKGLERROR
2128 qglReadBuffer(GL_NONE);CHECKGLERROR
2129 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
2130 if (status != GL_FRAMEBUFFER_COMPLETE_EXT && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
2132 Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
2133 Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
2134 Cvar_SetValueQuick(&r_shadow_deferred, 0);
2139 void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
2141 float nearclip, farclip, bias;
2142 r_viewport_t viewport;
2145 float clearcolor[4];
2146 nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
2148 bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
2149 r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias;
2150 r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip);
2151 r_shadow_shadowmapside = side;
2152 r_shadow_shadowmapsize = size;
2154 r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder);
2155 r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size;
2156 R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL);
2157 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done;
2159 // complex unrolled cube approach (more flexible)
2160 if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture)
2161 R_Shadow_MakeVSDCT();
2162 if (!r_shadow_shadowmap2dtexture)
2163 R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
2164 if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d;
2165 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
2166 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
2167 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
2169 R_Mesh_ResetTextureState();
2170 R_Shadow_RenderMode_Reset();
2171 R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
2172 R_SetupShader_DepthOrShadow();
2173 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
2178 R_SetViewport(&viewport);
2179 flipped = (side & 1) ^ (side >> 2);
2180 r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
2181 r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
2182 switch(vid.renderpath)
2184 case RENDERPATH_GL11:
2185 case RENDERPATH_GL13:
2186 case RENDERPATH_GL20:
2187 case RENDERPATH_SOFT:
2188 case RENDERPATH_GLES1:
2189 case RENDERPATH_GLES2:
2190 GL_CullFace(r_refdef.view.cullface_back);
2191 // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
2192 if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
2194 // get tightest scissor rectangle that encloses all viewports in the clear mask
2195 int x1 = clear & 0x15 ? 0 : size;
2196 int x2 = clear & 0x2A ? 2 * size : size;
2197 int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
2198 int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
2199 GL_Scissor(x1, y1, x2 - x1, y2 - y1);
2200 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
2202 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2204 case RENDERPATH_D3D9:
2205 case RENDERPATH_D3D10:
2206 case RENDERPATH_D3D11:
2207 Vector4Set(clearcolor, 1,1,1,1);
2208 // completely different meaning than in OpenGL path
2209 r_shadow_shadowmap_parameters[1] = 0;
2210 r_shadow_shadowmap_parameters[3] = -bias;
2211 // we invert the cull mode because we flip the projection matrix
2212 // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
2213 GL_CullFace(r_refdef.view.cullface_front);
2214 // D3D considers it an error to use a scissor larger than the viewport... clear just this view
2215 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
2216 if (r_shadow_shadowmapsampler)
2218 GL_ColorMask(0,0,0,0);
2220 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
2224 GL_ColorMask(1,1,1,1);
2226 GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
2232 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
2234 R_Mesh_ResetTextureState();
2235 R_Mesh_SetMainRenderTargets();
2238 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2239 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2240 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2241 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2243 R_Shadow_RenderMode_Reset();
2244 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2246 GL_DepthFunc(GL_EQUAL);
2247 // do global setup needed for the chosen lighting mode
2248 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2249 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
2250 r_shadow_usingshadowmap2d = shadowmapping;
2251 r_shadow_rendermode = r_shadow_lightingrendermode;
2252 // only draw light where this geometry was already rendered AND the
2253 // stencil is 128 (values other than this mean shadow)
2255 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2257 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
2260 static const unsigned short bboxelements[36] =
2270 static const float bboxpoints[8][3] =
2282 void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping)
2285 float vertex3f[8*3];
2286 const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
2287 // do global setup needed for the chosen lighting mode
2288 R_Shadow_RenderMode_Reset();
2289 r_shadow_rendermode = r_shadow_lightingrendermode;
2290 R_EntityMatrix(&identitymatrix);
2291 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2292 // only draw light where this geometry was already rendered AND the
2293 // stencil is 128 (values other than this mean shadow)
2294 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2295 if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0)
2296 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
2298 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
2300 r_shadow_usingshadowmap2d = shadowmapping;
2302 // render the lighting
2303 R_SetupShader_DeferredLight(rsurface.rtlight);
2304 for (i = 0;i < 8;i++)
2305 Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
2306 GL_ColorMask(1,1,1,1);
2307 GL_DepthMask(false);
2308 GL_DepthRange(0, 1);
2309 GL_PolygonOffset(0, 0);
2311 GL_DepthFunc(GL_GREATER);
2312 GL_CullFace(r_refdef.view.cullface_back);
2313 R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL);
2314 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
2317 static void R_Shadow_UpdateBounceGridTexture(void)
2319 #define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576
2321 int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2323 int hitsupercontentsmask;
2332 //trace_t cliptrace2;
2333 //trace_t cliptrace3;
2334 unsigned char *pixel;
2335 unsigned char *pixels;
2338 unsigned int lightindex;
2340 unsigned int range1;
2341 unsigned int range2;
2342 unsigned int seed = (unsigned int)(realtime * 1000.0f);
2344 vec3_t baseshotcolor;
2359 vec_t lightintensity;
2360 vec_t photonscaling;
2361 vec_t photonresidual;
2363 float texlerp[2][3];
2364 float splatcolor[32];
2365 float pixelweight[8];
2377 r_shadow_bouncegrid_settings_t settings;
2378 qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel;
2379 qboolean allowdirectionalshading = false;
2380 switch(vid.renderpath)
2382 case RENDERPATH_GL20:
2383 allowdirectionalshading = true;
2384 if (!vid.support.ext_texture_3d)
2387 case RENDERPATH_GLES2:
2388 // for performance reasons, do not use directional shading on GLES devices
2389 if (!vid.support.ext_texture_3d)
2392 // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them...
2393 case RENDERPATH_GL11:
2394 case RENDERPATH_GL13:
2395 case RENDERPATH_GLES1:
2396 case RENDERPATH_SOFT:
2397 case RENDERPATH_D3D9:
2398 case RENDERPATH_D3D10:
2399 case RENDERPATH_D3D11:
2403 r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value;
2405 // see if there are really any lights to render...
2406 if (enable && r_shadow_bouncegrid_static.integer)
2409 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2410 for (lightindex = 0;lightindex < range;lightindex++)
2412 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2413 if (!light || !(light->flags & flag))
2415 rtlight = &light->rtlight;
2416 // when static, we skip styled lights because they tend to change...
2417 if (rtlight->style > 0)
2419 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor);
2420 if (!VectorLength2(lightcolor))
2429 if (r_shadow_bouncegridtexture)
2431 R_FreeTexture(r_shadow_bouncegridtexture);
2432 r_shadow_bouncegridtexture = NULL;
2434 if (r_shadow_bouncegridpixels)
2435 Mem_Free(r_shadow_bouncegridpixels);
2436 r_shadow_bouncegridpixels = NULL;
2437 if (r_shadow_bouncegridhighpixels)
2438 Mem_Free(r_shadow_bouncegridhighpixels);
2439 r_shadow_bouncegridhighpixels = NULL;
2440 r_shadow_bouncegridnumpixels = 0;
2441 r_shadow_bouncegriddirectional = false;
2445 // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters
2446 memset(&settings, 0, sizeof(settings));
2447 settings.staticmode = r_shadow_bouncegrid_static.integer != 0;
2448 settings.airstepmax = bound(1, r_shadow_bouncegrid_airstepmax.integer, 1048576);
2449 settings.airstepsize = bound(1.0f, r_shadow_bouncegrid_airstepsize.value, 1024.0f);
2450 settings.bounceanglediffuse = r_shadow_bouncegrid_bounceanglediffuse.integer != 0;
2451 settings.directionalshading = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading;
2452 settings.dlightparticlemultiplier = r_shadow_bouncegrid_dlightparticlemultiplier.value;
2453 settings.hitmodels = r_shadow_bouncegrid_hitmodels.integer != 0;
2454 settings.includedirectlighting = r_shadow_bouncegrid_includedirectlighting.integer != 0;
2455 settings.lightradiusscale = r_shadow_bouncegrid_lightradiusscale.value;
2456 settings.maxbounce = r_shadow_bouncegrid_maxbounce.integer;
2457 settings.particlebounceintensity = r_shadow_bouncegrid_particlebounceintensity.value;
2458 settings.particleintensity = r_shadow_bouncegrid_particleintensity.value;
2459 settings.photons = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer;
2460 settings.spacing[0] = r_shadow_bouncegrid_spacingx.value;
2461 settings.spacing[1] = r_shadow_bouncegrid_spacingy.value;
2462 settings.spacing[2] = r_shadow_bouncegrid_spacingz.value;
2463 settings.stablerandom = r_shadow_bouncegrid_stablerandom.integer;
2465 // bound the values for sanity
2466 settings.photons = bound(1, settings.photons, 1048576);
2467 settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f);
2468 settings.maxbounce = bound(0, settings.maxbounce, 16);
2469 settings.spacing[0] = bound(1, settings.spacing[0], 512);
2470 settings.spacing[1] = bound(1, settings.spacing[1], 512);
2471 settings.spacing[2] = bound(1, settings.spacing[2], 512);
2473 // get the spacing values
2474 spacing[0] = settings.spacing[0];
2475 spacing[1] = settings.spacing[1];
2476 spacing[2] = settings.spacing[2];
2477 ispacing[0] = 1.0f / spacing[0];
2478 ispacing[1] = 1.0f / spacing[1];
2479 ispacing[2] = 1.0f / spacing[2];
2481 // calculate texture size enclosing entire world bounds at the spacing
2482 VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins);
2483 VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs);
2484 VectorSubtract(maxs, mins, size);
2485 // now we can calculate the resolution we want
2486 c[0] = (int)floor(size[0] / spacing[0] + 0.5f);
2487 c[1] = (int)floor(size[1] / spacing[1] + 0.5f);
2488 c[2] = (int)floor(size[2] / spacing[2] + 0.5f);
2489 // figure out the exact texture size (honoring power of 2 if required)
2490 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2491 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2492 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2493 if (vid.support.arb_texture_non_power_of_two)
2495 resolution[0] = c[0];
2496 resolution[1] = c[1];
2497 resolution[2] = c[2];
2501 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2502 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2503 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2505 size[0] = spacing[0] * resolution[0];
2506 size[1] = spacing[1] * resolution[1];
2507 size[2] = spacing[2] * resolution[2];
2509 // if dynamic we may or may not want to use the world bounds
2510 // if the dynamic size is smaller than the world bounds, use it instead
2511 if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2]))
2513 // we know the resolution we want
2514 c[0] = r_shadow_bouncegrid_x.integer;
2515 c[1] = r_shadow_bouncegrid_y.integer;
2516 c[2] = r_shadow_bouncegrid_z.integer;
2517 // now we can calculate the texture size (power of 2 if required)
2518 c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d);
2519 c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d);
2520 c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d);
2521 if (vid.support.arb_texture_non_power_of_two)
2523 resolution[0] = c[0];
2524 resolution[1] = c[1];
2525 resolution[2] = c[2];
2529 for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ;
2530 for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ;
2531 for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ;
2533 size[0] = spacing[0] * resolution[0];
2534 size[1] = spacing[1] * resolution[1];
2535 size[2] = spacing[2] * resolution[2];
2536 // center the rendering on the view
2537 mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0];
2538 mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1];
2539 mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2];
2542 // recalculate the maxs in case the resolution was not satisfactory
2543 VectorAdd(mins, size, maxs);
2545 // if all the settings seem identical to the previous update, return
2546 if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings)))
2549 // store the new settings
2550 r_shadow_bouncegridsettings = settings;
2552 pixelbands = settings.directionalshading ? 8 : 1;
2553 pixelsperband = resolution[0]*resolution[1]*resolution[2];
2554 numpixels = pixelsperband*pixelbands;
2556 // we're going to update the bouncegrid, update the matrix...
2557 memset(m, 0, sizeof(m));
2558 m[0] = 1.0f / size[0];
2559 m[3] = -mins[0] * m[0];
2560 m[5] = 1.0f / size[1];
2561 m[7] = -mins[1] * m[5];
2562 m[10] = 1.0f / size[2];
2563 m[11] = -mins[2] * m[10];
2565 Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m);
2566 // reallocate pixels for this update if needed...
2567 if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels)
2569 if (r_shadow_bouncegridtexture)
2571 R_FreeTexture(r_shadow_bouncegridtexture);
2572 r_shadow_bouncegridtexture = NULL;
2574 r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4]));
2575 r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4]));
2577 r_shadow_bouncegridnumpixels = numpixels;
2578 pixels = r_shadow_bouncegridpixels;
2579 highpixels = r_shadow_bouncegridhighpixels;
2580 x = pixelsperband*4;
2581 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2584 memset(pixels + pixelband * x, 128, x);
2586 memset(pixels + pixelband * x, 0, x);
2588 memset(highpixels, 0, numpixels * sizeof(float[4]));
2589 // figure out what we want to interact with
2590 if (settings.hitmodels)
2591 hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK;
2593 hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK;
2594 maxbounce = settings.maxbounce;
2595 // clear variables that produce warnings otherwise
2596 memset(splatcolor, 0, sizeof(splatcolor));
2597 // iterate world rtlights
2598 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
2599 range1 = settings.staticmode ? 0 : r_refdef.scene.numlights;
2600 range2 = range + range1;
2602 for (lightindex = 0;lightindex < range2;lightindex++)
2604 if (settings.staticmode)
2606 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2607 if (!light || !(light->flags & flag))
2609 rtlight = &light->rtlight;
2610 // when static, we skip styled lights because they tend to change...
2611 if (rtlight->style > 0)
2613 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2617 if (lightindex < range)
2619 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2620 rtlight = &light->rtlight;
2623 rtlight = r_refdef.scene.lights[lightindex - range];
2624 // draw only visible lights (major speedup)
2627 VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2629 if (!VectorLength2(lightcolor))
2631 // shoot particles from this light
2632 // use a calculation for the number of particles that will not
2633 // vary with lightstyle, otherwise we get randomized particle
2634 // distribution, the seeded random is only consistent for a
2635 // consistent number of particles on this light...
2636 radius = rtlight->radius * settings.lightradiusscale;
2637 s = rtlight->radius;
2638 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2639 if (lightindex >= range)
2640 lightintensity *= settings.dlightparticlemultiplier;
2641 photoncount += max(0.0f, lightintensity * s * s);
2643 photonscaling = (float)settings.photons / max(1, photoncount);
2644 photonresidual = 0.0f;
2645 for (lightindex = 0;lightindex < range2;lightindex++)
2647 if (settings.staticmode)
2649 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2650 if (!light || !(light->flags & flag))
2652 rtlight = &light->rtlight;
2653 // when static, we skip styled lights because they tend to change...
2654 if (rtlight->style > 0)
2656 VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) * (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1), lightcolor);
2660 if (lightindex < range)
2662 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
2663 rtlight = &light->rtlight;
2666 rtlight = r_refdef.scene.lights[lightindex - range];
2667 // draw only visible lights (major speedup)
2670 VectorScale(rtlight->currentcolor, rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale, lightcolor);
2672 if (!VectorLength2(lightcolor))
2674 // shoot particles from this light
2675 // use a calculation for the number of particles that will not
2676 // vary with lightstyle, otherwise we get randomized particle
2677 // distribution, the seeded random is only consistent for a
2678 // consistent number of particles on this light...
2679 radius = rtlight->radius * settings.lightradiusscale;
2680 s = rtlight->radius;
2681 lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale);
2682 if (lightindex >= range)
2683 lightintensity *= settings.dlightparticlemultiplier;
2684 photonresidual += lightintensity * s * s * photonscaling;
2685 shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT);
2686 if (!shootparticles)
2688 photonresidual -= shootparticles;
2689 s = settings.particleintensity / shootparticles;
2690 VectorScale(lightcolor, s, baseshotcolor);
2691 if (VectorLength2(baseshotcolor) == 0.0f)
2693 r_refdef.stats.bouncegrid_lights++;
2694 r_refdef.stats.bouncegrid_particles += shootparticles;
2695 for (shotparticles = 0;shotparticles < shootparticles;shotparticles++)
2697 if (settings.stablerandom > 0)
2698 seed = lightindex * 11937 + shotparticles;
2699 VectorCopy(baseshotcolor, shotcolor);
2700 VectorCopy(rtlight->shadoworigin, clipstart);
2701 if (settings.stablerandom < 0)
2702 VectorRandom(clipend);
2704 VectorCheeseRandom(clipend);
2705 VectorMA(clipstart, radius, clipend, clipend);
2706 for (bouncecount = 0;;bouncecount++)
2708 r_refdef.stats.bouncegrid_traces++;
2709 //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask);
2710 //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask);
2711 if (settings.staticmode)
2712 Collision_ClipLineToWorld(&cliptrace, cl.worldmodel, clipstart, clipend, hitsupercontentsmask, true);
2714 cliptrace = CL_TraceLine(clipstart, clipend, settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS, NULL, hitsupercontentsmask, true, false, NULL, true, true);
2715 if (bouncecount > 0 || settings.includedirectlighting)
2717 // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ)
2718 // accumulate average shotcolor
2719 w = VectorLength(shotcolor);
2720 splatcolor[ 0] = shotcolor[0];
2721 splatcolor[ 1] = shotcolor[1];
2722 splatcolor[ 2] = shotcolor[2];
2723 splatcolor[ 3] = 0.0f;
2726 VectorSubtract(clipstart, cliptrace.endpos, clipdiff);
2727 VectorNormalize(clipdiff);
2728 // store bentnormal in case the shader has a use for it
2729 splatcolor[ 4] = clipdiff[0] * w;
2730 splatcolor[ 5] = clipdiff[1] * w;
2731 splatcolor[ 6] = clipdiff[2] * w;
2733 // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z)
2734 splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]);
2735 splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]);
2736 splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]);
2737 splatcolor[11] = 0.0f;
2738 splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]);
2739 splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]);
2740 splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]);
2741 splatcolor[15] = 0.0f;
2742 splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]);
2743 splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]);
2744 splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]);
2745 splatcolor[19] = 0.0f;
2746 splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]);
2747 splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]);
2748 splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]);
2749 splatcolor[23] = 0.0f;
2750 splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]);
2751 splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]);
2752 splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]);
2753 splatcolor[27] = 0.0f;
2754 splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]);
2755 splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]);
2756 splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]);
2757 splatcolor[31] = 0.0f;
2759 // calculate the number of steps we need to traverse this distance
2760 VectorSubtract(cliptrace.endpos, clipstart, stepdelta);
2761 numsteps = (int)(VectorLength(stepdelta) / settings.airstepsize);
2762 numsteps = bound(1, numsteps, settings.airstepmax);
2763 w = 1.0f / numsteps;
2764 VectorScale(stepdelta, w, stepdelta);
2765 VectorMA(clipstart, 0.5f, stepdelta, steppos);
2766 if (settings.airstepmax == 1)
2767 VectorCopy(cliptrace.endpos, steppos);
2768 for (step = 0;step < numsteps;step++)
2770 r_refdef.stats.bouncegrid_splats++;
2771 // figure out which texture pixel this is in
2772 texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]);
2773 texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]);
2774 texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]);
2775 tex[0] = (int)floor(texlerp[1][0]);
2776 tex[1] = (int)floor(texlerp[1][1]);
2777 tex[2] = (int)floor(texlerp[1][2]);
2778 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)
2780 // it is within bounds... do the real work now
2781 // calculate the lerp factors
2782 texlerp[1][0] -= tex[0];
2783 texlerp[1][1] -= tex[1];
2784 texlerp[1][2] -= tex[2];
2785 texlerp[0][0] = 1.0f - texlerp[1][0];
2786 texlerp[0][1] = 1.0f - texlerp[1][1];
2787 texlerp[0][2] = 1.0f - texlerp[1][2];
2788 // calculate individual pixel indexes and weights
2789 pixelindex[0] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]);
2790 pixelindex[1] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]);
2791 pixelindex[2] = (((tex[2] )*resolution[1]+tex[1]+1)*resolution[0]+tex[0] );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]);
2792 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]);
2793 pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]);
2794 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]);
2795 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]);
2796 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]);
2797 // update the 8 pixels...
2798 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2800 for (corner = 0;corner < 8;corner++)
2802 // calculate address for pixel
2803 w = pixelweight[corner];
2804 pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2805 highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4;
2806 // add to the high precision pixel color
2807 highpixel[0] += (splatcolor[pixelband*4+0]*w);
2808 highpixel[1] += (splatcolor[pixelband*4+1]*w);
2809 highpixel[2] += (splatcolor[pixelband*4+2]*w);
2810 highpixel[3] += (splatcolor[pixelband*4+3]*w);
2811 // flag the low precision pixel as needing to be updated
2813 // advance to next band of coefficients
2814 //pixel += pixelsperband*4;
2815 //highpixel += pixelsperband*4;
2819 VectorAdd(steppos, stepdelta, steppos);
2822 if (cliptrace.fraction >= 1.0f)
2824 r_refdef.stats.bouncegrid_hits++;
2825 if (bouncecount >= maxbounce)
2827 // scale down shot color by bounce intensity and texture color (or 50% if no texture reported)
2828 // also clamp the resulting color to never add energy, even if the user requests extreme values
2829 if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe)
2830 VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor);
2832 VectorSet(surfcolor, 0.5f, 0.5f, 0.5f);
2833 VectorScale(surfcolor, settings.particlebounceintensity, surfcolor);
2834 surfcolor[0] = min(surfcolor[0], 1.0f);
2835 surfcolor[1] = min(surfcolor[1], 1.0f);
2836 surfcolor[2] = min(surfcolor[2], 1.0f);
2837 VectorMultiply(shotcolor, surfcolor, shotcolor);
2838 if (VectorLength2(baseshotcolor) == 0.0f)
2840 r_refdef.stats.bouncegrid_bounces++;
2841 if (settings.bounceanglediffuse)
2843 // random direction, primarily along plane normal
2844 s = VectorDistance(cliptrace.endpos, clipend);
2845 if (settings.stablerandom < 0)
2846 VectorRandom(clipend);
2848 VectorCheeseRandom(clipend);
2849 VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend);
2850 VectorNormalize(clipend);
2851 VectorScale(clipend, s, clipend);
2855 // reflect the remaining portion of the line across plane normal
2856 VectorSubtract(clipend, cliptrace.endpos, clipdiff);
2857 VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend);
2859 // calculate the new line start and end
2860 VectorCopy(cliptrace.endpos, clipstart);
2861 VectorAdd(clipstart, clipend, clipend);
2865 // generate pixels array from highpixels array
2866 // skip first and last columns, rows, and layers as these are blank
2867 // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated
2868 for (pixelband = 0;pixelband < pixelbands;pixelband++)
2870 for (z = 1;z < resolution[2]-1;z++)
2872 for (y = 1;y < resolution[1]-1;y++)
2874 for (x = 1, pixelindex[0] = ((pixelband*resolution[2]+z)*resolution[1]+y)*resolution[0]+x, pixel = pixels + 4*pixelindex[0], highpixel = highpixels + 4*pixelindex[0];x < resolution[0]-1;x++, pixel += 4, highpixel += 4)
2876 // only convert pixels that were hit by photons
2877 if (pixel[3] == 255)
2879 // normalize the bentnormal...
2882 VectorNormalize(highpixel);
2883 c[0] = (int)(highpixel[0]*128.0f+128.0f);
2884 c[1] = (int)(highpixel[1]*128.0f+128.0f);
2885 c[2] = (int)(highpixel[2]*128.0f+128.0f);
2886 c[3] = (int)(highpixel[3]*128.0f+128.0f);
2890 c[0] = (int)(highpixel[0]*256.0f);
2891 c[1] = (int)(highpixel[1]*256.0f);
2892 c[2] = (int)(highpixel[2]*256.0f);
2893 c[3] = (int)(highpixel[3]*256.0f);
2895 pixel[2] = (unsigned char)bound(0, c[0], 255);
2896 pixel[1] = (unsigned char)bound(0, c[1], 255);
2897 pixel[0] = (unsigned char)bound(0, c[2], 255);
2898 pixel[3] = (unsigned char)bound(0, c[3], 255);
2904 if (r_shadow_bouncegridtexture && r_shadow_bouncegridresolution[0] == resolution[0] && r_shadow_bouncegridresolution[1] == resolution[1] && r_shadow_bouncegridresolution[2] == resolution[2] && r_shadow_bouncegriddirectional == settings.directionalshading)
2905 R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands);
2908 VectorCopy(resolution, r_shadow_bouncegridresolution);
2909 r_shadow_bouncegriddirectional = settings.directionalshading;
2910 if (r_shadow_bouncegridtexture)
2911 R_FreeTexture(r_shadow_bouncegridtexture);
2912 r_shadow_bouncegridtexture = R_LoadTexture3D(r_shadow_texturepool, "bouncegrid", resolution[0], resolution[1], resolution[2]*pixelbands, pixels, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, 0, NULL);
2914 r_shadow_bouncegridtime = realtime;
2917 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
2919 R_Shadow_RenderMode_Reset();
2920 GL_BlendFunc(GL_ONE, GL_ONE);
2921 GL_DepthRange(0, 1);
2922 GL_DepthTest(r_showshadowvolumes.integer < 2);
2923 GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1);
2924 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
2925 GL_CullFace(GL_NONE);
2926 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
2929 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
2931 R_Shadow_RenderMode_Reset();
2932 GL_BlendFunc(GL_ONE, GL_ONE);
2933 GL_DepthRange(0, 1);
2934 GL_DepthTest(r_showlighting.integer < 2);
2935 GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
2937 GL_DepthFunc(GL_EQUAL);
2938 R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
2939 r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
2942 void R_Shadow_RenderMode_End(void)
2944 R_Shadow_RenderMode_Reset();
2945 R_Shadow_RenderMode_ActiveLight(NULL);
2947 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
2948 r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
2951 int bboxedges[12][2] =
2970 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
2972 if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass)
2974 r_shadow_lightscissor[0] = r_refdef.view.viewport.x;
2975 r_shadow_lightscissor[1] = r_refdef.view.viewport.y;
2976 r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
2977 r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
2980 if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor))
2981 return true; // invisible
2982 if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x
2983 || r_shadow_lightscissor[1] != r_refdef.view.viewport.y
2984 || r_shadow_lightscissor[2] != r_refdef.view.viewport.width
2985 || r_shadow_lightscissor[3] != r_refdef.view.viewport.height)
2986 r_refdef.stats.lights_scissored++;
2990 static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor)
2993 const float *vertex3f;
2994 const float *normal3f;
2996 float dist, dot, distintensity, shadeintensity, v[3], n[3];
2997 switch (r_shadow_rendermode)
2999 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3000 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3001 if (VectorLength2(diffusecolor) > 0)
3003 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)
3005 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3006 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3007 if ((dot = DotProduct(n, v)) < 0)
3009 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3010 VectorMA(ambientcolor, shadeintensity, diffusecolor, color4f);
3013 VectorCopy(ambientcolor, color4f);
3014 if (r_refdef.fogenabled)
3017 f = RSurf_FogVertex(vertex3f);
3018 VectorScale(color4f, f, color4f);
3025 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3027 VectorCopy(ambientcolor, color4f);
3028 if (r_refdef.fogenabled)
3031 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3032 f = RSurf_FogVertex(vertex3f);
3033 VectorScale(color4f + 4*i, f, color4f);
3039 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3040 if (VectorLength2(diffusecolor) > 0)
3042 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)
3044 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3045 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3047 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3048 if ((dot = DotProduct(n, v)) < 0)
3050 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3051 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3052 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3053 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3057 color4f[0] = ambientcolor[0] * distintensity;
3058 color4f[1] = ambientcolor[1] * distintensity;
3059 color4f[2] = ambientcolor[2] * distintensity;
3061 if (r_refdef.fogenabled)
3064 f = RSurf_FogVertex(vertex3f);
3065 VectorScale(color4f, f, color4f);
3069 VectorClear(color4f);
3075 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3077 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3078 if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3080 color4f[0] = ambientcolor[0] * distintensity;
3081 color4f[1] = ambientcolor[1] * distintensity;
3082 color4f[2] = ambientcolor[2] * distintensity;
3083 if (r_refdef.fogenabled)
3086 f = RSurf_FogVertex(vertex3f);
3087 VectorScale(color4f, f, color4f);
3091 VectorClear(color4f);
3096 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3097 if (VectorLength2(diffusecolor) > 0)
3099 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)
3101 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3102 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3104 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3105 Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n);
3106 if ((dot = DotProduct(n, v)) < 0)
3108 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
3109 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
3110 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
3111 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
3115 color4f[0] = ambientcolor[0] * distintensity;
3116 color4f[1] = ambientcolor[1] * distintensity;
3117 color4f[2] = ambientcolor[2] * distintensity;
3119 if (r_refdef.fogenabled)
3122 f = RSurf_FogVertex(vertex3f);
3123 VectorScale(color4f, f, color4f);
3127 VectorClear(color4f);
3133 for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4)
3135 Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v);
3136 if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)]))
3138 distintensity = (1 - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3139 color4f[0] = ambientcolor[0] * distintensity;
3140 color4f[1] = ambientcolor[1] * distintensity;
3141 color4f[2] = ambientcolor[2] * distintensity;
3142 if (r_refdef.fogenabled)
3145 f = RSurf_FogVertex(vertex3f);
3146 VectorScale(color4f, f, color4f);
3150 VectorClear(color4f);
3160 static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3162 // used to display how many times a surface is lit for level design purposes
3163 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3164 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
3168 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
3170 // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
3171 R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL);
3172 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3173 GL_DepthFunc(GL_EQUAL);
3175 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
3176 GL_DepthFunc(GL_LEQUAL);
3179 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
3186 int newnumtriangles;
3190 int maxtriangles = 4096;
3191 static int newelements[4096*3];
3192 R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2);
3193 for (renders = 0;renders < 4;renders++)
3198 newnumtriangles = 0;
3200 // due to low fillrate on the cards this vertex lighting path is
3201 // designed for, we manually cull all triangles that do not
3202 // contain a lit vertex
3203 // this builds batches of triangles from multiple surfaces and
3204 // renders them at once
3205 for (i = 0, e = element3i;i < numtriangles;i++, e += 3)
3207 if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01)
3209 if (newnumtriangles)
3211 newfirstvertex = min(newfirstvertex, e[0]);
3212 newlastvertex = max(newlastvertex, e[0]);
3216 newfirstvertex = e[0];
3217 newlastvertex = e[0];
3219 newfirstvertex = min(newfirstvertex, e[1]);
3220 newlastvertex = max(newlastvertex, e[1]);
3221 newfirstvertex = min(newfirstvertex, e[2]);
3222 newlastvertex = max(newlastvertex, e[2]);
3228 if (newnumtriangles >= maxtriangles)
3230 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3231 newnumtriangles = 0;
3237 if (newnumtriangles >= 1)
3239 R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0);
3242 // if we couldn't find any lit triangles, exit early
3245 // now reduce the intensity for the next overbright pass
3246 // we have to clamp to 0 here incase the drivers have improper
3247 // handling of negative colors
3248 // (some old drivers even have improper handling of >1 color)
3250 for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4)
3252 if (c[0] > 1 || c[1] > 1 || c[2] > 1)
3254 c[0] = max(0, c[0] - 1);
3255 c[1] = max(0, c[1] - 1);
3256 c[2] = max(0, c[2] - 1);
3268 static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale)
3270 // OpenGL 1.1 path (anything)
3271 float ambientcolorbase[3], diffusecolorbase[3];
3272 float ambientcolorpants[3], diffusecolorpants[3];
3273 float ambientcolorshirt[3], diffusecolorshirt[3];
3274 const float *surfacecolor = rsurface.texture->dlightcolor;
3275 const float *surfacepants = rsurface.colormap_pantscolor;
3276 const float *surfaceshirt = rsurface.colormap_shirtcolor;
3277 rtexture_t *basetexture = rsurface.texture->basetexture;
3278 rtexture_t *pantstexture = rsurface.texture->pantstexture;
3279 rtexture_t *shirttexture = rsurface.texture->shirttexture;
3280 qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f);
3281 qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f);
3282 ambientscale *= 2 * r_refdef.view.colorscale;
3283 diffusescale *= 2 * r_refdef.view.colorscale;
3284 ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2];
3285 diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2];
3286 ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2];
3287 diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2];
3288 ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2];
3289 diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2];
3290 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
3291 rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4]));
3292 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3293 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
3294 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
3295 R_Mesh_TexBind(0, basetexture);
3296 R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
3297 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
3298 switch(r_shadow_rendermode)
3300 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3301 R_Mesh_TexBind(1, r_shadow_attenuation3dtexture);
3302 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3303 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3304 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3306 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3307 R_Mesh_TexBind(2, r_shadow_attenuation2dtexture);
3308 R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz);
3309 R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1);
3310 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3312 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3313 R_Mesh_TexBind(1, r_shadow_attenuation2dtexture);
3314 R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz);
3315 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1);
3316 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
3318 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3323 //R_Mesh_TexBind(0, basetexture);
3324 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase);
3327 R_Mesh_TexBind(0, pantstexture);
3328 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants);
3332 R_Mesh_TexBind(0, shirttexture);
3333 R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt);
3337 extern cvar_t gl_lightmaps;
3338 void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist)
3340 float ambientscale, diffusescale, specularscale;
3342 float lightcolor[3];
3343 VectorCopy(rsurface.rtlight->currentcolor, lightcolor);
3344 ambientscale = rsurface.rtlight->ambientscale;
3345 diffusescale = rsurface.rtlight->diffusescale;
3346 specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale;
3347 if (!r_shadow_usenormalmap.integer)
3349 ambientscale += 1.0f * diffusescale;
3353 if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f))
3355 negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract;
3358 VectorNegate(lightcolor, lightcolor);
3359 switch(vid.renderpath)
3361 case RENDERPATH_GL11:
3362 case RENDERPATH_GL13:
3363 case RENDERPATH_GL20:
3364 case RENDERPATH_GLES1:
3365 case RENDERPATH_GLES2:
3366 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
3368 case RENDERPATH_D3D9:
3370 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
3373 case RENDERPATH_D3D10:
3374 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3376 case RENDERPATH_D3D11:
3377 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3379 case RENDERPATH_SOFT:
3380 DPSOFTRAST_BlendSubtract(true);
3384 RSurf_SetupDepthAndCulling();
3385 switch (r_shadow_rendermode)
3387 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
3388 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer);
3389 R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist);
3391 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
3392 R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale);
3394 case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN:
3395 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN:
3396 case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN:
3397 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
3398 R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale);
3401 Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
3406 switch(vid.renderpath)
3408 case RENDERPATH_GL11:
3409 case RENDERPATH_GL13:
3410 case RENDERPATH_GL20:
3411 case RENDERPATH_GLES1:
3412 case RENDERPATH_GLES2:
3413 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
3415 case RENDERPATH_D3D9:
3417 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
3420 case RENDERPATH_D3D10:
3421 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3423 case RENDERPATH_D3D11:
3424 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
3426 case RENDERPATH_SOFT:
3427 DPSOFTRAST_BlendSubtract(false);
3433 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)
3435 matrix4x4_t tempmatrix = *matrix;
3436 Matrix4x4_Scale(&tempmatrix, r_shadow_lightradiusscale.value, 1);
3438 // if this light has been compiled before, free the associated data
3439 R_RTLight_Uncompile(rtlight);
3441 // clear it completely to avoid any lingering data
3442 memset(rtlight, 0, sizeof(*rtlight));
3444 // copy the properties
3445 rtlight->matrix_lighttoworld = tempmatrix;
3446 Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &tempmatrix);
3447 Matrix4x4_OriginFromMatrix(&tempmatrix, rtlight->shadoworigin);
3448 rtlight->radius = Matrix4x4_ScaleFromMatrix(&tempmatrix);
3449 VectorCopy(color, rtlight->color);
3450 rtlight->cubemapname[0] = 0;
3451 if (cubemapname && cubemapname[0])
3452 strlcpy(rtlight->cubemapname, cubemapname, sizeof(rtlight->cubemapname));
3453 rtlight->shadow = shadow;
3454 rtlight->corona = corona;
3455 rtlight->style = style;
3456 rtlight->isstatic = isstatic;
3457 rtlight->coronasizescale = coronasizescale;
3458 rtlight->ambientscale = ambientscale;
3459 rtlight->diffusescale = diffusescale;
3460 rtlight->specularscale = specularscale;
3461 rtlight->flags = flags;
3463 // compute derived data
3464 //rtlight->cullradius = rtlight->radius;
3465 //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
3466 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3467 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3468 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3469 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3470 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3471 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3474 // compiles rtlight geometry
3475 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
3476 void R_RTLight_Compile(rtlight_t *rtlight)
3479 int numsurfaces, numleafs, numleafpvsbytes, numshadowtrispvsbytes, numlighttrispvsbytes;
3480 int lighttris, shadowtris, shadowzpasstris, shadowzfailtris;
3481 entity_render_t *ent = r_refdef.scene.worldentity;
3482 dp_model_t *model = r_refdef.scene.worldmodel;
3483 unsigned char *data;
3486 // compile the light
3487 rtlight->compiled = true;
3488 rtlight->shadowmode = rtlight->shadow ? (int)r_shadow_shadowmode : -1;
3489 rtlight->static_numleafs = 0;
3490 rtlight->static_numleafpvsbytes = 0;
3491 rtlight->static_leaflist = NULL;
3492 rtlight->static_leafpvs = NULL;
3493 rtlight->static_numsurfaces = 0;
3494 rtlight->static_surfacelist = NULL;
3495 rtlight->static_shadowmap_receivers = 0x3F;
3496 rtlight->static_shadowmap_casters = 0x3F;
3497 rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
3498 rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
3499 rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
3500 rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
3501 rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
3502 rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
3504 if (model && model->GetLightInfo)
3506 // this variable must be set for the CompileShadowVolume/CompileShadowMap code
3507 r_shadow_compilingrtlight = rtlight;
3508 R_FrameData_SetMark();
3509 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);
3510 R_FrameData_ReturnToMark();
3511 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
3512 numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3;
3513 numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3;
3514 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numsurfaces + sizeof(int) * numleafs + numleafpvsbytes + numshadowtrispvsbytes + numlighttrispvsbytes);
3515 rtlight->static_numsurfaces = numsurfaces;
3516 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
3517 rtlight->static_numleafs = numleafs;
3518 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
3519 rtlight->static_numleafpvsbytes = numleafpvsbytes;
3520 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
3521 rtlight->static_numshadowtrispvsbytes = numshadowtrispvsbytes;
3522 rtlight->static_shadowtrispvs = (unsigned char *)data;data += numshadowtrispvsbytes;
3523 rtlight->static_numlighttrispvsbytes = numlighttrispvsbytes;
3524 rtlight->static_lighttrispvs = (unsigned char *)data;data += numlighttrispvsbytes;
3525 if (rtlight->static_numsurfaces)
3526 memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
3527 if (rtlight->static_numleafs)
3528 memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
3529 if (rtlight->static_numleafpvsbytes)
3530 memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
3531 if (rtlight->static_numshadowtrispvsbytes)
3532 memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes);
3533 if (rtlight->static_numlighttrispvsbytes)
3534 memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes);
3535 R_FrameData_SetMark();
3536 switch (rtlight->shadowmode)
3538 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
3539 if (model->CompileShadowMap && rtlight->shadow)
3540 model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3543 if (model->CompileShadowVolume && rtlight->shadow)
3544 model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
3547 R_FrameData_ReturnToMark();
3548 // now we're done compiling the rtlight
3549 r_shadow_compilingrtlight = NULL;
3553 // use smallest available cullradius - box radius or light radius
3554 //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
3555 //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
3557 shadowzpasstris = 0;
3558 if (rtlight->static_meshchain_shadow_zpass)
3559 for (mesh = rtlight->static_meshchain_shadow_zpass;mesh;mesh = mesh->next)
3560 shadowzpasstris += mesh->numtriangles;
3562 shadowzfailtris = 0;
3563 if (rtlight->static_meshchain_shadow_zfail)
3564 for (mesh = rtlight->static_meshchain_shadow_zfail;mesh;mesh = mesh->next)
3565 shadowzfailtris += mesh->numtriangles;
3568 if (rtlight->static_numlighttrispvsbytes)
3569 for (i = 0;i < rtlight->static_numlighttrispvsbytes*8;i++)
3570 if (CHECKPVSBIT(rtlight->static_lighttrispvs, i))
3574 if (rtlight->static_numlighttrispvsbytes)
3575 for (i = 0;i < rtlight->static_numshadowtrispvsbytes*8;i++)
3576 if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i))
3579 if (developer_extra.integer)
3580 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);
3583 void R_RTLight_Uncompile(rtlight_t *rtlight)
3585 if (rtlight->compiled)
3587 if (rtlight->static_meshchain_shadow_zpass)
3588 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zpass);
3589 rtlight->static_meshchain_shadow_zpass = NULL;
3590 if (rtlight->static_meshchain_shadow_zfail)
3591 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_zfail);
3592 rtlight->static_meshchain_shadow_zfail = NULL;
3593 if (rtlight->static_meshchain_shadow_shadowmap)
3594 Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow_shadowmap);
3595 rtlight->static_meshchain_shadow_shadowmap = NULL;
3596 // these allocations are grouped
3597 if (rtlight->static_surfacelist)
3598 Mem_Free(rtlight->static_surfacelist);
3599 rtlight->static_numleafs = 0;
3600 rtlight->static_numleafpvsbytes = 0;
3601 rtlight->static_leaflist = NULL;
3602 rtlight->static_leafpvs = NULL;
3603 rtlight->static_numsurfaces = 0;
3604 rtlight->static_surfacelist = NULL;
3605 rtlight->static_numshadowtrispvsbytes = 0;
3606 rtlight->static_shadowtrispvs = NULL;
3607 rtlight->static_numlighttrispvsbytes = 0;
3608 rtlight->static_lighttrispvs = NULL;
3609 rtlight->compiled = false;
3613 void R_Shadow_UncompileWorldLights(void)
3617 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
3618 for (lightindex = 0;lightindex < range;lightindex++)
3620 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
3623 R_RTLight_Uncompile(&light->rtlight);
3627 void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight)
3631 // reset the count of frustum planes
3632 // see rtlight->cached_frustumplanes definition for how much this array
3634 rtlight->cached_numfrustumplanes = 0;
3636 // haven't implemented a culling path for ortho rendering
3637 if (!r_refdef.view.useperspective)
3639 // check if the light is on screen and copy the 4 planes if it is
3640 for (i = 0;i < 4;i++)
3641 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3644 for (i = 0;i < 4;i++)
3645 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3650 // generate a deformed frustum that includes the light origin, this is
3651 // used to cull shadow casting surfaces that can not possibly cast a
3652 // shadow onto the visible light-receiving surfaces, which can be a
3655 // if the light origin is onscreen the result will be 4 planes exactly
3656 // if the light origin is offscreen on only one axis the result will
3657 // be exactly 5 planes (split-side case)
3658 // if the light origin is offscreen on two axes the result will be
3659 // exactly 4 planes (stretched corner case)
3660 for (i = 0;i < 4;i++)
3662 // quickly reject standard frustum planes that put the light
3663 // origin outside the frustum
3664 if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125)
3667 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i];
3669 // if all the standard frustum planes were accepted, the light is onscreen
3670 // otherwise we need to generate some more planes below...
3671 if (rtlight->cached_numfrustumplanes < 4)
3673 // at least one of the stock frustum planes failed, so we need to
3674 // create one or two custom planes to enclose the light origin
3675 for (i = 0;i < 4;i++)
3677 // create a plane using the view origin and light origin, and a
3678 // single point from the frustum corner set
3679 TriangleNormal(r_refdef.view.origin, r_refdef.view.frustumcorner[i], rtlight->shadoworigin, plane.normal);
3680 VectorNormalize(plane.normal);
3681 plane.dist = DotProduct(r_refdef.view.origin, plane.normal);
3682 // see if this plane is backwards and flip it if so
3683 for (j = 0;j < 4;j++)
3684 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3688 VectorNegate(plane.normal, plane.normal);
3690 // flipped plane, test again to see if it is now valid
3691 for (j = 0;j < 4;j++)
3692 if (j != i && DotProduct(r_refdef.view.frustumcorner[j], plane.normal) - plane.dist < -0.03125)
3694 // if the plane is still not valid, then it is dividing the
3695 // frustum and has to be rejected
3699 // we have created a valid plane, compute extra info
3700 PlaneClassify(&plane);
3702 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3704 // if we've found 5 frustum planes then we have constructed a
3705 // proper split-side case and do not need to keep searching for
3706 // planes to enclose the light origin
3707 if (rtlight->cached_numfrustumplanes == 5)
3715 for (i = 0;i < rtlight->cached_numfrustumplanes;i++)
3717 plane = rtlight->cached_frustumplanes[i];
3718 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));
3723 // now add the light-space box planes if the light box is rotated, as any
3724 // caster outside the oriented light box is irrelevant (even if it passed
3725 // the worldspace light box, which is axial)
3726 if (rtlight->matrix_lighttoworld.m[0][0] != 1 || rtlight->matrix_lighttoworld.m[1][1] != 1 || rtlight->matrix_lighttoworld.m[2][2] != 1)
3728 for (i = 0;i < 6;i++)
3732 v[i >> 1] = (i & 1) ? -1 : 1;
3733 Matrix4x4_Transform(&rtlight->matrix_lighttoworld, v, plane.normal);
3734 VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal);
3735 plane.dist = VectorNormalizeLength(plane.normal);
3736 plane.dist += DotProduct(plane.normal, rtlight->shadoworigin);
3737 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3743 // add the world-space reduced box planes
3744 for (i = 0;i < 6;i++)
3746 VectorClear(plane.normal);
3747 plane.normal[i >> 1] = (i & 1) ? -1 : 1;
3748 plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1];
3749 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane;
3758 // reduce all plane distances to tightly fit the rtlight cull box, which
3760 VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3761 VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]);
3762 VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3763 VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]);
3764 VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3765 VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]);
3766 VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3767 VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]);
3768 oldnum = rtlight->cached_numfrustumplanes;
3769 rtlight->cached_numfrustumplanes = 0;
3770 for (j = 0;j < oldnum;j++)
3772 // find the nearest point on the box to this plane
3773 bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]);
3774 for (i = 1;i < 8;i++)
3776 dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]);
3777 if (bestdist > dist)
3780 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);
3781 // if the nearest point is near or behind the plane, we want this
3782 // plane, otherwise the plane is useless as it won't cull anything
3783 if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125)
3785 PlaneClassify(&rtlight->cached_frustumplanes[j]);
3786 rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j];
3793 void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides)
3797 RSurf_ActiveWorldEntity();
3799 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3802 GL_CullFace(GL_NONE);
3803 mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap;
3804 for (;mesh;mesh = mesh->next)
3806 if (!mesh->sidetotals[r_shadow_shadowmapside])
3808 r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside];
3809 if (mesh->vertex3fbuffer)
3810 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3812 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3813 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);
3817 else if (r_refdef.scene.worldentity->model)
3818 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);
3820 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3823 void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs)
3825 qboolean zpass = false;
3828 int surfacelistindex;
3829 msurface_t *surface;
3831 // if triangle neighbors are disabled, shadowvolumes are disabled
3832 if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i)
3835 RSurf_ActiveWorldEntity();
3837 if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
3840 if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES)
3842 zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3843 R_Shadow_RenderMode_StencilShadowVolumes(zpass);
3845 mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail;
3846 for (;mesh;mesh = mesh->next)
3848 r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
3849 if (mesh->vertex3fbuffer)
3850 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vertex3fbuffer);
3852 R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer);
3853 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
3855 // increment stencil if frontface is infront of depthbuffer
3856 GL_CullFace(r_refdef.view.cullface_back);
3857 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
3858 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);
3859 // decrement stencil if backface is infront of depthbuffer
3860 GL_CullFace(r_refdef.view.cullface_front);
3861 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
3863 else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
3865 // decrement stencil if backface is behind depthbuffer
3866 GL_CullFace(r_refdef.view.cullface_front);
3867 R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
3868 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);
3869 // increment stencil if frontface is behind depthbuffer
3870 GL_CullFace(r_refdef.view.cullface_back);
3871 R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
3873 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);
3877 else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh)
3879 // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light
3880 R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles);
3881 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
3883 surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[surfacelistindex];
3884 for (t = surface->num_firstshadowmeshtriangle, tend = t + surface->num_triangles;t < tend;t++)
3885 if (CHECKPVSBIT(trispvs, t))
3886 shadowmarklist[numshadowmark++] = t;
3888 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);
3890 else if (numsurfaces)
3892 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);
3895 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3898 void R_Shadow_DrawEntityShadow(entity_render_t *ent)
3900 vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
3901 vec_t relativeshadowradius;
3902 RSurf_ActiveModelEntity(ent, false, false, false);
3903 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin);
3904 // we need to re-init the shader for each entity because the matrix changed
3905 relativeshadowradius = rsurface.rtlight->radius / ent->scale;
3906 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
3907 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
3908 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
3909 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
3910 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
3911 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
3912 switch (r_shadow_rendermode)
3914 case R_SHADOW_RENDERMODE_SHADOWMAP2D:
3915 ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
3918 ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
3921 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3924 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
3926 // set up properties for rendering light onto this entity
3927 RSurf_ActiveModelEntity(ent, true, true, false);
3928 Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix);
3929 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3930 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3931 Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3934 void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs)
3936 if (!r_refdef.scene.worldmodel->DrawLight)
3939 // set up properties for rendering light onto this entity
3940 RSurf_ActiveWorldEntity();
3941 rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight;
3942 Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight);
3943 Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight);
3944 VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin);
3946 r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs);
3948 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3951 void R_Shadow_DrawEntityLight(entity_render_t *ent)
3953 dp_model_t *model = ent->model;
3954 if (!model->DrawLight)
3957 R_Shadow_SetupEntityLight(ent);
3959 model->DrawLight(ent, model->nummodelsurfaces, model->sortedmodelsurfaces, NULL);
3961 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
3964 void R_Shadow_PrepareLight(rtlight_t *rtlight)
3968 int numleafs, numsurfaces;
3969 int *leaflist, *surfacelist;
3970 unsigned char *leafpvs;
3971 unsigned char *shadowtrispvs;
3972 unsigned char *lighttrispvs;
3973 //unsigned char *surfacesides;
3974 int numlightentities;
3975 int numlightentities_noselfshadow;
3976 int numshadowentities;
3977 int numshadowentities_noselfshadow;
3978 static entity_render_t *lightentities[MAX_EDICTS];
3979 static entity_render_t *lightentities_noselfshadow[MAX_EDICTS];
3980 static entity_render_t *shadowentities[MAX_EDICTS];
3981 static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS];
3984 rtlight->draw = false;
3986 // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
3987 // skip lights that are basically invisible (color 0 0 0)
3988 nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f);
3990 // loading is done before visibility checks because loading should happen
3991 // all at once at the start of a level, not when it stalls gameplay.
3992 // (especially important to benchmarks)
3994 if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer)
3996 if (rtlight->compiled)
3997 R_RTLight_Uncompile(rtlight);
3998 R_RTLight_Compile(rtlight);
4002 rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube;
4004 // look up the light style value at this time
4005 f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4006 VectorScale(rtlight->color, f, rtlight->currentcolor);
4008 if (rtlight->selected)
4010 f = 2 + sin(realtime * M_PI * 4.0);
4011 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
4015 // if lightstyle is currently off, don't draw the light
4016 if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
4019 // skip processing on corona-only lights
4023 // if the light box is offscreen, skip it
4024 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
4027 VectorCopy(rtlight->cullmins, rtlight->cached_cullmins);
4028 VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs);
4030 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4032 if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
4034 // compiled light, world available and can receive realtime lighting
4035 // retrieve leaf information
4036 numleafs = rtlight->static_numleafs;
4037 leaflist = rtlight->static_leaflist;
4038 leafpvs = rtlight->static_leafpvs;
4039 numsurfaces = rtlight->static_numsurfaces;
4040 surfacelist = rtlight->static_surfacelist;
4041 //surfacesides = NULL;
4042 shadowtrispvs = rtlight->static_shadowtrispvs;
4043 lighttrispvs = rtlight->static_lighttrispvs;
4045 else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->GetLightInfo)
4047 // dynamic light, world available and can receive realtime lighting
4048 // calculate lit surfaces and leafs
4049 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);
4050 R_Shadow_ComputeShadowCasterCullingPlanes(rtlight);
4051 leaflist = r_shadow_buffer_leaflist;
4052 leafpvs = r_shadow_buffer_leafpvs;
4053 surfacelist = r_shadow_buffer_surfacelist;
4054 //surfacesides = r_shadow_buffer_surfacesides;
4055 shadowtrispvs = r_shadow_buffer_shadowtrispvs;
4056 lighttrispvs = r_shadow_buffer_lighttrispvs;
4057 // if the reduced leaf bounds are offscreen, skip it
4058 if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4069 //surfacesides = NULL;
4070 shadowtrispvs = NULL;
4071 lighttrispvs = NULL;
4073 // check if light is illuminating any visible leafs
4076 for (i = 0;i < numleafs;i++)
4077 if (r_refdef.viewcache.world_leafvisible[leaflist[i]])
4083 // make a list of lit entities and shadow casting entities
4084 numlightentities = 0;
4085 numlightentities_noselfshadow = 0;
4086 numshadowentities = 0;
4087 numshadowentities_noselfshadow = 0;
4089 // add dynamic entities that are lit by the light
4090 for (i = 0;i < r_refdef.scene.numentities;i++)
4093 entity_render_t *ent = r_refdef.scene.entities[i];
4095 if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4097 // skip the object entirely if it is not within the valid
4098 // shadow-casting region (which includes the lit region)
4099 if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
4101 if (!(model = ent->model))
4103 if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT))
4105 // this entity wants to receive light, is visible, and is
4106 // inside the light box
4107 // TODO: check if the surfaces in the model can receive light
4108 // so now check if it's in a leaf seen by the light
4109 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))
4111 if (ent->flags & RENDER_NOSELFSHADOW)
4112 lightentities_noselfshadow[numlightentities_noselfshadow++] = ent;
4114 lightentities[numlightentities++] = ent;
4115 // since it is lit, it probably also casts a shadow...
4116 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4117 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4118 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4120 // note: exterior models without the RENDER_NOSELFSHADOW
4121 // flag still create a RENDER_NOSELFSHADOW shadow but
4122 // are lit normally, this means that they are
4123 // self-shadowing but do not shadow other
4124 // RENDER_NOSELFSHADOW entities such as the gun
4125 // (very weird, but keeps the player shadow off the gun)
4126 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4127 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4129 shadowentities[numshadowentities++] = ent;
4132 else if (ent->flags & RENDER_SHADOW)
4134 // this entity is not receiving light, but may still need to
4136 // TODO: check if the surfaces in the model can cast shadow
4137 // now check if it is in a leaf seen by the light
4138 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))
4140 // about the VectorDistance2 - light emitting entities should not cast their own shadow
4141 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
4142 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1)
4144 if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL))
4145 shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent;
4147 shadowentities[numshadowentities++] = ent;
4152 // return if there's nothing at all to light
4153 if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0)
4156 // count this light in the r_speeds
4157 r_refdef.stats.lights++;
4159 // flag it as worth drawing later
4160 rtlight->draw = true;
4162 // cache all the animated entities that cast a shadow but are not visible
4163 for (i = 0;i < numshadowentities;i++)
4164 if (!shadowentities[i]->animcache_vertex3f)
4165 R_AnimCache_GetEntity(shadowentities[i], false, false);
4166 for (i = 0;i < numshadowentities_noselfshadow;i++)
4167 if (!shadowentities_noselfshadow[i]->animcache_vertex3f)
4168 R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false);
4170 // allocate some temporary memory for rendering this light later in the frame
4171 // reusable buffers need to be copied, static data can be used as-is
4172 rtlight->cached_numlightentities = numlightentities;
4173 rtlight->cached_numlightentities_noselfshadow = numlightentities_noselfshadow;
4174 rtlight->cached_numshadowentities = numshadowentities;
4175 rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow;
4176 rtlight->cached_numsurfaces = numsurfaces;
4177 rtlight->cached_lightentities = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities);
4178 rtlight->cached_lightentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow);
4179 rtlight->cached_shadowentities = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities);
4180 rtlight->cached_shadowentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow);
4181 if (shadowtrispvs == r_shadow_buffer_shadowtrispvs)
4183 int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3);
4184 int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3);
4185 rtlight->cached_shadowtrispvs = (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs);
4186 rtlight->cached_lighttrispvs = (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs);
4187 rtlight->cached_surfacelist = (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist);
4191 // compiled light data
4192 rtlight->cached_shadowtrispvs = shadowtrispvs;
4193 rtlight->cached_lighttrispvs = lighttrispvs;
4194 rtlight->cached_surfacelist = surfacelist;
4198 void R_Shadow_DrawLight(rtlight_t *rtlight)
4202 unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides;
4203 int numlightentities;
4204 int numlightentities_noselfshadow;
4205 int numshadowentities;
4206 int numshadowentities_noselfshadow;
4207 entity_render_t **lightentities;
4208 entity_render_t **lightentities_noselfshadow;
4209 entity_render_t **shadowentities;
4210 entity_render_t **shadowentities_noselfshadow;
4212 static unsigned char entitysides[MAX_EDICTS];
4213 static unsigned char entitysides_noselfshadow[MAX_EDICTS];
4214 vec3_t nearestpoint;
4216 qboolean castshadows;
4219 // check if we cached this light this frame (meaning it is worth drawing)
4223 numlightentities = rtlight->cached_numlightentities;
4224 numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow;
4225 numshadowentities = rtlight->cached_numshadowentities;
4226 numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow;
4227 numsurfaces = rtlight->cached_numsurfaces;
4228 lightentities = rtlight->cached_lightentities;
4229 lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow;
4230 shadowentities = rtlight->cached_shadowentities;
4231 shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow;
4232 shadowtrispvs = rtlight->cached_shadowtrispvs;
4233 lighttrispvs = rtlight->cached_lighttrispvs;
4234 surfacelist = rtlight->cached_surfacelist;
4236 // set up a scissor rectangle for this light
4237 if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs))
4240 // don't let sound skip if going slow
4241 if (r_refdef.scene.extraupdate)
4244 // make this the active rtlight for rendering purposes
4245 R_Shadow_RenderMode_ActiveLight(rtlight);
4247 if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows))
4249 // optionally draw visible shape of the shadow volumes
4250 // for performance analysis by level designers
4251 R_Shadow_RenderMode_VisibleShadowVolumes();
4253 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4254 for (i = 0;i < numshadowentities;i++)
4255 R_Shadow_DrawEntityShadow(shadowentities[i]);
4256 for (i = 0;i < numshadowentities_noselfshadow;i++)
4257 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4258 R_Shadow_RenderMode_VisibleLighting(false, false);
4261 if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow)
4263 // optionally draw the illuminated areas
4264 // for performance analysis by level designers
4265 R_Shadow_RenderMode_VisibleLighting(false, false);
4267 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4268 for (i = 0;i < numlightentities;i++)
4269 R_Shadow_DrawEntityLight(lightentities[i]);
4270 for (i = 0;i < numlightentities_noselfshadow;i++)
4271 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4274 castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows);
4276 nearestpoint[0] = bound(rtlight->cullmins[0], r_refdef.view.origin[0], rtlight->cullmaxs[0]);
4277 nearestpoint[1] = bound(rtlight->cullmins[1], r_refdef.view.origin[1], rtlight->cullmaxs[1]);
4278 nearestpoint[2] = bound(rtlight->cullmins[2], r_refdef.view.origin[2], rtlight->cullmaxs[2]);
4279 distance = VectorDistance(nearestpoint, r_refdef.view.origin);
4281 lodlinear = (rtlight->radius * r_shadow_shadowmapping_precision.value) / sqrt(max(1.0f, distance/rtlight->radius));
4282 //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance));
4283 lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize);
4285 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4291 int receivermask = 0;
4292 matrix4x4_t radiustolight = rtlight->matrix_worldtolight;
4293 Matrix4x4_Abs(&radiustolight);
4295 r_shadow_shadowmaplod = 0;
4296 for (i = 1;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
4297 if ((r_shadow_shadowmapmaxsize >> i) > lodlinear)
4298 r_shadow_shadowmaplod = i;
4300 size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize);
4302 borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder);
4304 surfacesides = NULL;
4307 if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
4309 castermask = rtlight->static_shadowmap_casters;
4310 receivermask = rtlight->static_shadowmap_receivers;
4314 surfacesides = r_shadow_buffer_surfacesides;
4315 for(i = 0;i < numsurfaces;i++)
4317 msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i];
4318 surfacesides[i] = R_Shadow_CalcBBoxSideMask(surface->mins, surface->maxs, &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4319 castermask |= surfacesides[i];
4320 receivermask |= surfacesides[i];
4324 if (receivermask < 0x3F)
4326 for (i = 0;i < numlightentities;i++)
4327 receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4328 if (receivermask < 0x3F)
4329 for(i = 0; i < numlightentities_noselfshadow;i++)
4330 receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias);
4333 receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder);
4337 for (i = 0;i < numshadowentities;i++)
4338 castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4339 for (i = 0;i < numshadowentities_noselfshadow;i++)
4340 castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias));
4343 //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size);
4345 // render shadow casters into 6 sided depth texture
4346 for (side = 0;side < 6;side++) if (receivermask & (1 << side))
4348 R_Shadow_RenderMode_ShadowMap(side, receivermask, size);
4349 if (! (castermask & (1 << side))) continue;
4351 R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides);
4352 for (i = 0;i < numshadowentities;i++) if (entitysides[i] & (1 << side))
4353 R_Shadow_DrawEntityShadow(shadowentities[i]);
4356 if (numlightentities_noselfshadow)
4358 // render lighting using the depth texture as shadowmap
4359 // draw lighting in the unmasked areas
4360 R_Shadow_RenderMode_Lighting(false, false, true);
4361 for (i = 0;i < numlightentities_noselfshadow;i++)
4362 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4365 // render shadow casters into 6 sided depth texture
4366 if (numshadowentities_noselfshadow)
4368 for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side))
4370 R_Shadow_RenderMode_ShadowMap(side, 0, size);
4371 for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side))
4372 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4376 // render lighting using the depth texture as shadowmap
4377 // draw lighting in the unmasked areas
4378 R_Shadow_RenderMode_Lighting(false, false, true);
4379 // draw lighting in the unmasked areas
4381 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4382 for (i = 0;i < numlightentities;i++)
4383 R_Shadow_DrawEntityLight(lightentities[i]);
4385 else if (castshadows && vid.stencil)
4387 // draw stencil shadow volumes to mask off pixels that are in shadow
4388 // so that they won't receive lighting
4389 GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
4390 R_Shadow_ClearStencil();
4393 R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs);
4394 for (i = 0;i < numshadowentities;i++)
4395 R_Shadow_DrawEntityShadow(shadowentities[i]);
4397 // draw lighting in the unmasked areas
4398 R_Shadow_RenderMode_Lighting(true, false, false);
4399 for (i = 0;i < numlightentities_noselfshadow;i++)
4400 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4402 for (i = 0;i < numshadowentities_noselfshadow;i++)
4403 R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]);
4405 // draw lighting in the unmasked areas
4406 R_Shadow_RenderMode_Lighting(true, false, false);
4408 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4409 for (i = 0;i < numlightentities;i++)
4410 R_Shadow_DrawEntityLight(lightentities[i]);
4414 // draw lighting in the unmasked areas
4415 R_Shadow_RenderMode_Lighting(false, false, false);
4417 R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs);
4418 for (i = 0;i < numlightentities;i++)
4419 R_Shadow_DrawEntityLight(lightentities[i]);
4420 for (i = 0;i < numlightentities_noselfshadow;i++)
4421 R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]);
4424 if (r_shadow_usingdeferredprepass)
4426 // when rendering deferred lighting, we simply rasterize the box
4427 if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D)
4428 R_Shadow_RenderMode_DrawDeferredLight(false, true);
4429 else if (castshadows && vid.stencil)
4430 R_Shadow_RenderMode_DrawDeferredLight(true, false);
4432 R_Shadow_RenderMode_DrawDeferredLight(false, false);
4436 static void R_Shadow_FreeDeferred(void)
4438 R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
4439 r_shadow_prepassgeometryfbo = 0;
4441 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo);
4442 r_shadow_prepasslightingdiffusespecularfbo = 0;
4444 R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo);
4445 r_shadow_prepasslightingdiffusefbo = 0;
4447 if (r_shadow_prepassgeometrydepthtexture)
4448 R_FreeTexture(r_shadow_prepassgeometrydepthtexture);
4449 r_shadow_prepassgeometrydepthtexture = NULL;
4451 if (r_shadow_prepassgeometrydepthcolortexture)
4452 R_FreeTexture(r_shadow_prepassgeometrydepthcolortexture);
4453 r_shadow_prepassgeometrydepthcolortexture = NULL;
4455 if (r_shadow_prepassgeometrynormalmaptexture)
4456 R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture);
4457 r_shadow_prepassgeometrynormalmaptexture = NULL;
4459 if (r_shadow_prepasslightingdiffusetexture)
4460 R_FreeTexture(r_shadow_prepasslightingdiffusetexture);
4461 r_shadow_prepasslightingdiffusetexture = NULL;
4463 if (r_shadow_prepasslightingspeculartexture)
4464 R_FreeTexture(r_shadow_prepasslightingspeculartexture);
4465 r_shadow_prepasslightingspeculartexture = NULL;
4468 void R_Shadow_DrawPrepass(void)
4476 entity_render_t *ent;
4477 float clearcolor[4];
4479 R_Mesh_ResetTextureState();
4481 GL_ColorMask(1,1,1,1);
4482 GL_BlendFunc(GL_ONE, GL_ZERO);
4485 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4486 Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
4487 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4488 if (r_timereport_active)
4489 R_TimeReport("prepasscleargeom");
4491 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
4492 r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
4493 if (r_timereport_active)
4494 R_TimeReport("prepassworld");
4496 for (i = 0;i < r_refdef.scene.numentities;i++)
4498 if (!r_refdef.viewcache.entityvisible[i])
4500 ent = r_refdef.scene.entities[i];
4501 if (ent->model && ent->model->DrawPrepass != NULL)
4502 ent->model->DrawPrepass(ent);
4505 if (r_timereport_active)
4506 R_TimeReport("prepassmodels");
4508 GL_DepthMask(false);
4509 GL_ColorMask(1,1,1,1);
4512 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4513 Vector4Set(clearcolor, 0, 0, 0, 0);
4514 GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
4515 if (r_timereport_active)
4516 R_TimeReport("prepassclearlit");
4518 R_Shadow_RenderMode_Begin();
4520 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4521 if (r_shadow_debuglight.integer >= 0)
4523 lightindex = r_shadow_debuglight.integer;
4524 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4525 if (light && (light->flags & flag) && light->rtlight.draw)
4526 R_Shadow_DrawLight(&light->rtlight);
4530 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4531 for (lightindex = 0;lightindex < range;lightindex++)
4533 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4534 if (light && (light->flags & flag) && light->rtlight.draw)
4535 R_Shadow_DrawLight(&light->rtlight);
4538 if (r_refdef.scene.rtdlight)
4539 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4540 if (r_refdef.scene.lights[lnum]->draw)
4541 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4543 R_Mesh_SetMainRenderTargets();
4545 R_Shadow_RenderMode_End();
4547 if (r_timereport_active)
4548 R_TimeReport("prepasslights");
4551 void R_Shadow_DrawLightSprites(void);
4552 void R_Shadow_PrepareLights(void)
4562 if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) ||
4563 (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) ||
4564 r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) ||
4565 r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer ||
4566 r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer ||
4567 r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16))
4568 R_Shadow_FreeShadowMaps();
4570 r_shadow_usingshadowmaportho = false;
4572 switch (vid.renderpath)
4574 case RENDERPATH_GL20:
4575 case RENDERPATH_D3D9:
4576 case RENDERPATH_D3D10:
4577 case RENDERPATH_D3D11:
4578 case RENDERPATH_SOFT:
4579 case RENDERPATH_GLES2:
4580 if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
4582 r_shadow_usingdeferredprepass = false;
4583 if (r_shadow_prepass_width)
4584 R_Shadow_FreeDeferred();
4585 r_shadow_prepass_width = r_shadow_prepass_height = 0;
4589 if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height)
4591 R_Shadow_FreeDeferred();
4593 r_shadow_usingdeferredprepass = true;
4594 r_shadow_prepass_width = vid.width;
4595 r_shadow_prepass_height = vid.height;
4596 r_shadow_prepassgeometrydepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "prepassgeometrydepthmap", vid.width, vid.height, 24, false);
4597 switch (vid.renderpath)
4599 case RENDERPATH_D3D9:
4600 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);
4605 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);
4606 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);
4607 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);
4609 // set up the geometry pass fbo (depth + normalmap)
4610 r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
4611 R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, r_shadow_prepassgeometrydepthcolortexture, NULL, NULL);
4612 // render depth into one texture and normalmap into the other
4613 if (qglDrawBuffersARB)
4615 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4616 qglReadBuffer(GL_NONE);CHECKGLERROR
4617 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4618 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4620 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4621 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4622 r_shadow_usingdeferredprepass = false;
4626 // set up the lighting pass fbo (diffuse + specular)
4627 r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4628 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
4629 // render diffuse into one texture and specular into another,
4630 // with depth and normalmap bound as textures,
4631 // with depth bound as attachment as well
4632 if (qglDrawBuffersARB)
4634 qglDrawBuffersARB(2, r_shadow_prepasslightingdrawbuffers);CHECKGLERROR
4635 qglReadBuffer(GL_NONE);CHECKGLERROR
4636 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4637 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4639 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4640 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4641 r_shadow_usingdeferredprepass = false;
4645 // set up the lighting pass fbo (diffuse)
4646 r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4647 R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL);
4648 // render diffuse into one texture,
4649 // with depth and normalmap bound as textures,
4650 // with depth bound as attachment as well
4651 if (qglDrawBuffersARB)
4653 qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
4654 qglReadBuffer(GL_NONE);CHECKGLERROR
4655 status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
4656 if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
4658 Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
4659 Cvar_SetValueQuick(&r_shadow_deferred, 0);
4660 r_shadow_usingdeferredprepass = false;
4665 case RENDERPATH_GL11:
4666 case RENDERPATH_GL13:
4667 case RENDERPATH_GLES1:
4668 r_shadow_usingdeferredprepass = false;
4672 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);
4674 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4675 if (r_shadow_debuglight.integer >= 0)
4677 lightindex = r_shadow_debuglight.integer;
4678 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4679 if (light && (light->flags & flag))
4680 R_Shadow_PrepareLight(&light->rtlight);
4684 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4685 for (lightindex = 0;lightindex < range;lightindex++)
4687 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4688 if (light && (light->flags & flag))
4689 R_Shadow_PrepareLight(&light->rtlight);
4692 if (r_refdef.scene.rtdlight)
4694 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4695 R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]);
4697 else if(gl_flashblend.integer)
4699 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4701 rtlight_t *rtlight = r_refdef.scene.lights[lnum];
4702 f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value;
4703 VectorScale(rtlight->color, f, rtlight->currentcolor);
4707 if (r_editlights.integer)
4708 R_Shadow_DrawLightSprites();
4710 R_Shadow_UpdateBounceGridTexture();
4713 void R_Shadow_DrawLights(void)
4721 R_Shadow_RenderMode_Begin();
4723 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
4724 if (r_shadow_debuglight.integer >= 0)
4726 lightindex = r_shadow_debuglight.integer;
4727 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4728 if (light && (light->flags & flag))
4729 R_Shadow_DrawLight(&light->rtlight);
4733 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
4734 for (lightindex = 0;lightindex < range;lightindex++)
4736 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
4737 if (light && (light->flags & flag))
4738 R_Shadow_DrawLight(&light->rtlight);
4741 if (r_refdef.scene.rtdlight)
4742 for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
4743 R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
4745 R_Shadow_RenderMode_End();
4748 extern const float r_screenvertex3f[12];
4749 extern void R_SetupView(qboolean allowwaterclippingplane);
4750 extern void R_ResetViewRendering3D(void);
4751 extern void R_ResetViewRendering2D(void);
4752 extern cvar_t r_shadows;
4753 extern cvar_t r_shadows_darken;
4754 extern cvar_t r_shadows_drawafterrtlighting;
4755 extern cvar_t r_shadows_castfrombmodels;
4756 extern cvar_t r_shadows_throwdistance;
4757 extern cvar_t r_shadows_throwdirection;
4758 extern cvar_t r_shadows_focus;
4759 extern cvar_t r_shadows_shadowmapscale;
4761 void R_Shadow_PrepareModelShadows(void)
4764 float scale, size, radius, dot1, dot2;
4765 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs;
4766 entity_render_t *ent;
4768 if (!r_refdef.scene.numentities)
4771 switch (r_shadow_shadowmode)
4773 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4774 if (r_shadows.integer >= 2)
4777 case R_SHADOW_SHADOWMODE_STENCIL:
4778 for (i = 0;i < r_refdef.scene.numentities;i++)
4780 ent = r_refdef.scene.entities[i];
4781 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4782 R_AnimCache_GetEntity(ent, false, false);
4789 size = 2*r_shadow_shadowmapmaxsize;
4790 scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value;
4791 radius = 0.5f * size / scale;
4793 Math_atov(r_shadows_throwdirection.string, shadowdir);
4794 VectorNormalize(shadowdir);
4795 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4796 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4797 if (fabs(dot1) <= fabs(dot2))
4798 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4800 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4801 VectorNormalize(shadowforward);
4802 CrossProduct(shadowdir, shadowforward, shadowright);
4803 Math_atov(r_shadows_focus.string, shadowfocus);
4804 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4805 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4806 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4807 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4808 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4810 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4812 shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4813 shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4814 shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4815 shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0]));
4816 shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1]));
4817 shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2]));
4819 for (i = 0;i < r_refdef.scene.numentities;i++)
4821 ent = r_refdef.scene.entities[i];
4822 if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs))
4824 // cast shadows from anything of the map (submodels are optional)
4825 if (!ent->animcache_vertex3f && ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4826 R_AnimCache_GetEntity(ent, false, false);
4830 void R_DrawModelShadowMaps(void)
4833 float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2;
4834 entity_render_t *ent;
4835 vec3_t relativelightorigin;
4836 vec3_t relativelightdirection, relativeforward, relativeright;
4837 vec3_t relativeshadowmins, relativeshadowmaxs;
4838 vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus;
4840 matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
4841 r_viewport_t viewport;
4843 float clearcolor[4];
4845 if (!r_refdef.scene.numentities)
4848 switch (r_shadow_shadowmode)
4850 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4856 R_ResetViewRendering3D();
4857 R_Shadow_RenderMode_Begin();
4858 R_Shadow_RenderMode_ActiveLight(NULL);
4860 switch (r_shadow_shadowmode)
4862 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
4863 if (!r_shadow_shadowmap2dtexture)
4864 R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize);
4865 fbo = r_shadow_fbo2d;
4866 r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
4867 r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
4868 r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D;
4874 size = 2*r_shadow_shadowmapmaxsize;
4875 scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size;
4876 radius = 0.5f / scale;
4877 nearclip = -r_shadows_throwdistance.value;
4878 farclip = r_shadows_throwdistance.value;
4879 bias = r_shadow_shadowmapping_bias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size);
4881 r_shadow_shadowmap_parameters[0] = size;
4882 r_shadow_shadowmap_parameters[1] = size;
4883 r_shadow_shadowmap_parameters[2] = 1.0;
4884 r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f);
4886 Math_atov(r_shadows_throwdirection.string, shadowdir);
4887 VectorNormalize(shadowdir);
4888 Math_atov(r_shadows_focus.string, shadowfocus);
4889 VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin);
4890 VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin);
4891 VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin);
4892 VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin);
4893 dot1 = DotProduct(r_refdef.view.forward, shadowdir);
4894 dot2 = DotProduct(r_refdef.view.up, shadowdir);
4895 if (fabs(dot1) <= fabs(dot2))
4896 VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward);
4898 VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward);
4899 VectorNormalize(shadowforward);
4900 VectorM(scale, shadowforward, &m[0]);
4901 if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2])
4903 m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]);
4904 CrossProduct(shadowdir, shadowforward, shadowright);
4905 VectorM(scale, shadowright, &m[4]);
4906 m[7] = 0.5f - DotProduct(shadoworigin, &m[4]);
4907 VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]);
4908 m[11] = 0.5f - DotProduct(shadoworigin, &m[8]);
4909 Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m);
4910 Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix);
4911 R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL);
4913 VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
4915 R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
4916 R_SetupShader_DepthOrShadow();
4917 GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
4920 R_SetViewport(&viewport);
4921 GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
4922 Vector4Set(clearcolor, 1,1,1,1);
4923 // in D3D9 we have to render to a color texture shadowmap
4924 // in GL we render directly to a depth texture only
4925 if (r_shadow_shadowmap2dtexture)
4926 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4928 GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4929 // render into a slightly restricted region so that the borders of the
4930 // shadowmap area fade away, rather than streaking across everything
4931 // outside the usable area
4932 GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
4936 R_Mesh_SetMainRenderTargets();
4937 R_SetupShader_ShowDepth();
4938 GL_ColorMask(1,1,1,1);
4939 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
4942 for (i = 0;i < r_refdef.scene.numentities;i++)
4944 ent = r_refdef.scene.entities[i];
4946 // cast shadows from anything of the map (submodels are optional)
4947 if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
4949 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
4950 Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin);
4951 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
4952 Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward);
4953 Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright);
4954 relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4955 relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4956 relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4957 relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0]));
4958 relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1]));
4959 relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2]));
4960 RSurf_ActiveModelEntity(ent, false, false, false);
4961 ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs);
4962 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
4969 unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4);
4971 qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels);
4973 Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels);
4974 Cvar_SetValueQuick(&r_test, 0);
4979 R_Shadow_RenderMode_End();
4981 Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix);
4982 Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix);
4983 Matrix4x4_CreateScale3(&scalematrix, size, -size, 1);
4984 Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias);
4985 Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix);
4986 Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix);
4988 switch (vid.renderpath)
4990 case RENDERPATH_GL11:
4991 case RENDERPATH_GL13:
4992 case RENDERPATH_GL20:
4993 case RENDERPATH_SOFT:
4994 case RENDERPATH_GLES1:
4995 case RENDERPATH_GLES2:
4997 case RENDERPATH_D3D9:
4998 case RENDERPATH_D3D10:
4999 case RENDERPATH_D3D11:
5000 #ifdef OPENGL_ORIENTATION
5001 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
5002 r_shadow_shadowmapmatrix.m[0][1] *= -1.0f;
5003 r_shadow_shadowmapmatrix.m[0][2] *= -1.0f;
5004 r_shadow_shadowmapmatrix.m[0][3] *= -1.0f;
5006 r_shadow_shadowmapmatrix.m[0][0] *= -1.0f;
5007 r_shadow_shadowmapmatrix.m[1][0] *= -1.0f;
5008 r_shadow_shadowmapmatrix.m[2][0] *= -1.0f;
5009 r_shadow_shadowmapmatrix.m[3][0] *= -1.0f;
5014 r_shadow_usingshadowmaportho = true;
5015 switch (r_shadow_shadowmode)
5017 case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
5018 r_shadow_usingshadowmap2d = true;
5025 void R_DrawModelShadows(void)
5028 float relativethrowdistance;
5029 entity_render_t *ent;
5030 vec3_t relativelightorigin;
5031 vec3_t relativelightdirection;
5032 vec3_t relativeshadowmins, relativeshadowmaxs;
5033 vec3_t tmp, shadowdir;
5035 if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
5038 R_ResetViewRendering3D();
5039 //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
5040 //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5041 R_Shadow_RenderMode_Begin();
5042 R_Shadow_RenderMode_ActiveLight(NULL);
5043 r_shadow_lightscissor[0] = r_refdef.view.x;
5044 r_shadow_lightscissor[1] = vid.height - r_refdef.view.y - r_refdef.view.height;
5045 r_shadow_lightscissor[2] = r_refdef.view.width;
5046 r_shadow_lightscissor[3] = r_refdef.view.height;
5047 R_Shadow_RenderMode_StencilShadowVolumes(false);
5050 if (r_shadows.integer == 2)
5052 Math_atov(r_shadows_throwdirection.string, shadowdir);
5053 VectorNormalize(shadowdir);
5056 R_Shadow_ClearStencil();
5058 for (i = 0;i < r_refdef.scene.numentities;i++)
5060 ent = r_refdef.scene.entities[i];
5062 // cast shadows from anything of the map (submodels are optional)
5063 if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW))
5065 relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix);
5066 VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance);
5067 VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance);
5068 if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction
5069 Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection);
5072 if(ent->entitynumber != 0)
5074 if(ent->entitynumber >= MAX_EDICTS) // csqc entity
5076 // FIXME handle this
5077 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5081 // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities)
5082 int entnum, entnum2, recursion;
5083 entnum = entnum2 = ent->entitynumber;
5084 for(recursion = 32; recursion > 0; --recursion)
5086 entnum2 = cl.entities[entnum].state_current.tagentity;
5087 if(entnum2 >= 1 && entnum2 < cl.num_entities && cl.entities_active[entnum2])
5092 if(recursion && recursion != 32) // if we followed a valid non-empty attachment chain
5094 VectorNegate(cl.entities[entnum].render.modellight_lightdir, relativelightdirection);
5095 // transform into modelspace of OUR entity
5096 Matrix4x4_Transform3x3(&cl.entities[entnum].render.matrix, relativelightdirection, tmp);
5097 Matrix4x4_Transform3x3(&ent->inversematrix, tmp, relativelightdirection);
5100 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5104 VectorNegate(ent->modellight_lightdir, relativelightdirection);
5107 VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin);
5108 RSurf_ActiveModelEntity(ent, false, false, false);
5109 ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs);
5110 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
5114 // not really the right mode, but this will disable any silly stencil features
5115 R_Shadow_RenderMode_End();
5117 // set up ortho view for rendering this pass
5118 //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
5119 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5120 //GL_ScissorTest(true);
5121 //R_EntityMatrix(&identitymatrix);
5122 //R_Mesh_ResetTextureState();
5123 R_ResetViewRendering2D();
5125 // set up a darkening blend on shadowed areas
5126 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
5127 //GL_DepthRange(0, 1);
5128 //GL_DepthTest(false);
5129 //GL_DepthMask(false);
5130 //GL_PolygonOffset(0, 0);CHECKGLERROR
5131 GL_Color(0, 0, 0, r_shadows_darken.value);
5132 //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5133 //GL_DepthFunc(GL_ALWAYS);
5134 R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
5136 // apply the blend to the shadowed areas
5137 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
5138 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5139 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5141 // restore the viewport
5142 R_SetViewport(&r_refdef.view.viewport);
5144 // restore other state to normal
5145 //R_Shadow_RenderMode_End();
5148 void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
5151 vec3_t centerorigin;
5153 // if it's too close, skip it
5154 if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f))
5156 zdist = (DotProduct(rtlight->shadoworigin, r_refdef.view.forward) - DotProduct(r_refdef.view.origin, r_refdef.view.forward));
5159 if (usequery && r_numqueries + 2 <= r_maxqueries)
5161 rtlight->corona_queryindex_allpixels = r_queries[r_numqueries++];
5162 rtlight->corona_queryindex_visiblepixels = r_queries[r_numqueries++];
5163 // 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
5164 VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
5166 switch(vid.renderpath)
5168 case RENDERPATH_GL11:
5169 case RENDERPATH_GL13:
5170 case RENDERPATH_GL20:
5171 case RENDERPATH_GLES1:
5172 case RENDERPATH_GLES2:
5174 // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
5175 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
5176 GL_DepthFunc(GL_ALWAYS);
5177 R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5178 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5179 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5180 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5181 GL_DepthFunc(GL_LEQUAL);
5182 qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
5183 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5184 R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL);
5185 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
5186 qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
5189 case RENDERPATH_D3D9:
5190 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5192 case RENDERPATH_D3D10:
5193 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5195 case RENDERPATH_D3D11:
5196 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5198 case RENDERPATH_SOFT:
5199 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5203 rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
5206 static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
5208 void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
5211 GLint allpixels = 0, visiblepixels = 0;
5212 // now we have to check the query result
5213 if (rtlight->corona_queryindex_visiblepixels)
5215 switch(vid.renderpath)
5217 case RENDERPATH_GL11:
5218 case RENDERPATH_GL13:
5219 case RENDERPATH_GL20:
5220 case RENDERPATH_GLES1:
5221 case RENDERPATH_GLES2:
5223 qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
5224 qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
5227 case RENDERPATH_D3D9:
5228 Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5230 case RENDERPATH_D3D10:
5231 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5233 case RENDERPATH_D3D11:
5234 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5236 case RENDERPATH_SOFT:
5237 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5240 //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
5241 if (visiblepixels < 1 || allpixels < 1)
5243 rtlight->corona_visibility *= bound(0, (float)visiblepixels / (float)allpixels, 1);
5244 cscale *= rtlight->corona_visibility;
5248 // FIXME: these traces should scan all render entities instead of cl.world
5249 if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
5252 VectorScale(rtlight->currentcolor, cscale, color);
5253 if (VectorLength(color) > (1.0f / 256.0f))
5256 qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract;
5259 VectorNegate(color, color);
5260 switch(vid.renderpath)
5262 case RENDERPATH_GL11:
5263 case RENDERPATH_GL13:
5264 case RENDERPATH_GL20:
5265 case RENDERPATH_GLES1:
5266 case RENDERPATH_GLES2:
5267 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
5269 case RENDERPATH_D3D9:
5271 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
5274 case RENDERPATH_D3D10:
5275 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5277 case RENDERPATH_D3D11:
5278 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5280 case RENDERPATH_SOFT:
5281 DPSOFTRAST_BlendSubtract(true);
5285 R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
5286 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);
5287 R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5290 switch(vid.renderpath)
5292 case RENDERPATH_GL11:
5293 case RENDERPATH_GL13:
5294 case RENDERPATH_GL20:
5295 case RENDERPATH_GLES1:
5296 case RENDERPATH_GLES2:
5297 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
5299 case RENDERPATH_D3D9:
5301 IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
5304 case RENDERPATH_D3D10:
5305 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5307 case RENDERPATH_D3D11:
5308 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5310 case RENDERPATH_SOFT:
5311 DPSOFTRAST_BlendSubtract(false);
5318 void R_Shadow_DrawCoronas(void)
5321 qboolean usequery = false;
5326 if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer)
5328 if (r_waterstate.renderingscene)
5330 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
5331 R_EntityMatrix(&identitymatrix);
5333 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5335 // check occlusion of coronas
5336 // use GL_ARB_occlusion_query if available
5337 // otherwise use raytraces
5339 switch (vid.renderpath)
5341 case RENDERPATH_GL11:
5342 case RENDERPATH_GL13:
5343 case RENDERPATH_GL20:
5344 case RENDERPATH_GLES1:
5345 case RENDERPATH_GLES2:
5346 usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
5349 GL_ColorMask(0,0,0,0);
5350 if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
5351 if (r_maxqueries < MAX_OCCLUSION_QUERIES)
5354 r_maxqueries = (range + r_refdef.scene.numlights) * 4;
5355 r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
5357 qglGenQueriesARB(r_maxqueries - i, r_queries + i);
5360 RSurf_ActiveWorldEntity();
5361 GL_BlendFunc(GL_ONE, GL_ZERO);
5362 GL_CullFace(GL_NONE);
5363 GL_DepthMask(false);
5364 GL_DepthRange(0, 1);
5365 GL_PolygonOffset(0, 0);
5367 R_Mesh_ResetTextureState();
5368 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
5371 case RENDERPATH_D3D9:
5373 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5375 case RENDERPATH_D3D10:
5376 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5378 case RENDERPATH_D3D11:
5379 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5381 case RENDERPATH_SOFT:
5383 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5386 for (lightindex = 0;lightindex < range;lightindex++)
5388 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5391 rtlight = &light->rtlight;
5392 rtlight->corona_visibility = 0;
5393 rtlight->corona_queryindex_visiblepixels = 0;
5394 rtlight->corona_queryindex_allpixels = 0;
5395 if (!(rtlight->flags & flag))
5397 if (rtlight->corona <= 0)
5399 if (r_shadow_debuglight.integer >= 0 && r_shadow_debuglight.integer != (int)lightindex)
5401 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5403 for (i = 0;i < r_refdef.scene.numlights;i++)
5405 rtlight = r_refdef.scene.lights[i];
5406 rtlight->corona_visibility = 0;
5407 rtlight->corona_queryindex_visiblepixels = 0;
5408 rtlight->corona_queryindex_allpixels = 0;
5409 if (!(rtlight->flags & flag))
5411 if (rtlight->corona <= 0)
5413 R_BeginCoronaQuery(rtlight, rtlight->radius * rtlight->coronasizescale * r_coronas_occlusionsizescale.value, usequery);
5416 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5418 // now draw the coronas using the query data for intensity info
5419 for (lightindex = 0;lightindex < range;lightindex++)
5421 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5424 rtlight = &light->rtlight;
5425 if (rtlight->corona_visibility <= 0)
5427 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5429 for (i = 0;i < r_refdef.scene.numlights;i++)
5431 rtlight = r_refdef.scene.lights[i];
5432 if (rtlight->corona_visibility <= 0)
5434 if (gl_flashblend.integer)
5435 R_DrawCorona(rtlight, rtlight->corona, rtlight->radius * rtlight->coronasizescale * 2.0f);
5437 R_DrawCorona(rtlight, rtlight->corona * r_coronas.value * 0.25f, rtlight->radius * rtlight->coronasizescale);
5443 dlight_t *R_Shadow_NewWorldLight(void)
5445 return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray);
5448 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)
5451 // validate parameters
5452 if (style < 0 || style >= MAX_LIGHTSTYLES)
5454 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
5460 // copy to light properties
5461 VectorCopy(origin, light->origin);
5462 light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
5463 light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
5464 light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
5466 light->color[0] = max(color[0], 0);
5467 light->color[1] = max(color[1], 0);
5468 light->color[2] = max(color[2], 0);
5470 light->color[0] = color[0];
5471 light->color[1] = color[1];
5472 light->color[2] = color[2];
5473 light->radius = max(radius, 0);
5474 light->style = style;
5475 light->shadow = shadowenable;
5476 light->corona = corona;
5477 strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
5478 light->coronasizescale = coronasizescale;
5479 light->ambientscale = ambientscale;
5480 light->diffusescale = diffusescale;
5481 light->specularscale = specularscale;
5482 light->flags = flags;
5484 // update renderable light data
5485 Matrix4x4_CreateFromQuakeEntity(&matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], light->radius);
5486 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);
5489 void R_Shadow_FreeWorldLight(dlight_t *light)
5491 if (r_shadow_selectedlight == light)
5492 r_shadow_selectedlight = NULL;
5493 R_RTLight_Uncompile(&light->rtlight);
5494 Mem_ExpandableArray_FreeRecord(&r_shadow_worldlightsarray, light);
5497 void R_Shadow_ClearWorldLights(void)
5501 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5502 for (lightindex = 0;lightindex < range;lightindex++)
5504 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5506 R_Shadow_FreeWorldLight(light);
5508 r_shadow_selectedlight = NULL;
5511 void R_Shadow_SelectLight(dlight_t *light)
5513 if (r_shadow_selectedlight)
5514 r_shadow_selectedlight->selected = false;
5515 r_shadow_selectedlight = light;
5516 if (r_shadow_selectedlight)
5517 r_shadow_selectedlight->selected = true;
5520 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5522 // this is never batched (there can be only one)
5524 R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE);
5525 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5526 R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5529 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
5534 skinframe_t *skinframe;
5537 // this is never batched (due to the ent parameter changing every time)
5538 // so numsurfaces == 1 and surfacelist[0] == lightnumber
5539 const dlight_t *light = (dlight_t *)ent;
5542 R_CalcSprite_Vertex3f(vertex3f, light->origin, r_refdef.view.right, r_refdef.view.up, s, -s, -s, s);
5545 VectorScale(light->color, intensity, spritecolor);
5546 if (VectorLength(spritecolor) < 0.1732f)
5547 VectorSet(spritecolor, 0.1f, 0.1f, 0.1f);
5548 if (VectorLength(spritecolor) > 1.0f)
5549 VectorNormalize(spritecolor);
5551 // draw light sprite
5552 if (light->cubemapname[0] && !light->shadow)
5553 skinframe = r_editlights_sprcubemapnoshadowlight;
5554 else if (light->cubemapname[0])
5555 skinframe = r_editlights_sprcubemaplight;
5556 else if (!light->shadow)
5557 skinframe = r_editlights_sprnoshadowlight;
5559 skinframe = r_editlights_sprlight;
5561 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);
5562 R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5564 // draw selection sprite if light is selected
5565 if (light->selected)
5567 RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
5568 R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
5569 // VorteX todo: add normalmode/realtime mode light overlay sprites?
5573 void R_Shadow_DrawLightSprites(void)
5577 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5578 for (lightindex = 0;lightindex < range;lightindex++)
5580 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5582 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight);
5584 if (!r_editlights_lockcursor)
5585 R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
5588 int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color)
5593 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
5594 if (lightindex >= range)
5596 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5599 rtlight = &light->rtlight;
5600 //if (!(rtlight->flags & flag))
5602 VectorCopy(rtlight->shadoworigin, origin);
5603 *radius = rtlight->radius;
5604 VectorCopy(rtlight->color, color);
5608 void R_Shadow_SelectLightInView(void)
5610 float bestrating, rating, temp[3];
5614 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
5618 if (r_editlights_lockcursor)
5620 for (lightindex = 0;lightindex < range;lightindex++)
5622 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5625 VectorSubtract(light->origin, r_refdef.view.origin, temp);
5626 rating = (DotProduct(temp, r_refdef.view.forward) / sqrt(DotProduct(temp, temp)));
5629 rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
5630 if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f)
5632 bestrating = rating;
5637 R_Shadow_SelectLight(best);
5640 void R_Shadow_LoadWorldLights(void)
5642 int n, a, style, shadow, flags;
5643 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
5644 float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
5645 if (cl.worldmodel == NULL)
5647 Con_Print("No map loaded.\n");
5650 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5651 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5661 for (;COM_Parse(t, true) && strcmp(
5662 if (COM_Parse(t, true))
5664 if (com_token[0] == '!')
5667 origin[0] = atof(com_token+1);
5670 origin[0] = atof(com_token);
5675 while (*s && *s != '\n' && *s != '\r')
5681 // check for modifier flags
5688 #if _MSC_VER >= 1400
5689 #define sscanf sscanf_s
5691 cubemapname[sizeof(cubemapname)-1] = 0;
5692 #if MAX_QPATH != 128
5693 #error update this code if MAX_QPATH changes
5695 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
5696 #if _MSC_VER >= 1400
5697 , sizeof(cubemapname)
5699 , &corona, &angles[0], &angles[1], &angles[2], &coronasizescale, &ambientscale, &diffusescale, &specularscale, &flags);
5702 flags = LIGHTFLAG_REALTIMEMODE;
5710 coronasizescale = 0.25f;
5712 VectorClear(angles);
5715 if (a < 9 || !strcmp(cubemapname, "\"\""))
5717 // remove quotes on cubemapname
5718 if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
5721 namelen = strlen(cubemapname) - 2;
5722 memmove(cubemapname, cubemapname + 1, namelen);
5723 cubemapname[namelen] = '\0';
5727 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);
5730 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
5738 Con_Printf("invalid rtlights file \"%s\"\n", name);
5739 Mem_Free(lightsstring);
5743 void R_Shadow_SaveWorldLights(void)
5747 size_t bufchars, bufmaxchars;
5749 char name[MAX_QPATH];
5750 char line[MAX_INPUTLINE];
5751 size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked, assuming the dpsnprintf mess doesn't screw it up...
5752 // I hate lines which are 3 times my screen size :( --blub
5755 if (cl.worldmodel == NULL)
5757 Con_Print("No map loaded.\n");
5760 dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension);
5761 bufchars = bufmaxchars = 0;
5763 for (lightindex = 0;lightindex < range;lightindex++)
5765 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
5768 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
5769 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);
5770 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
5771 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]);
5773 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);
5774 if (bufchars + strlen(line) > bufmaxchars)
5776 bufmaxchars = bufchars + strlen(line) + 2048;
5778 buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
5782 memcpy(buf, oldbuf, bufchars);
5788 memcpy(buf + bufchars, line, strlen(line));
5789 bufchars += strlen(line);
5793 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
5798 void R_Shadow_LoadLightsFile(void)
5801 char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
5802 float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
5803 if (cl.worldmodel == NULL)
5805 Con_Print("No map loaded.\n");
5808 dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension);
5809 lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
5817 while (*s && *s != '\n' && *s != '\r')
5823 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);
5827 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);
5830 radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
5831 radius = bound(15, radius, 4096);
5832 VectorScale(color, (2.0f / (8388608.0f)), color);
5833 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
5841 Con_Printf("invalid lights file \"%s\"\n", name);
5842 Mem_Free(lightsstring);
5846 // tyrlite/hmap2 light types in the delay field
5847 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
5849 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
5861 float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
5862 char key[256], value[MAX_INPUTLINE];
5864 if (cl.worldmodel == NULL)
5866 Con_Print("No map loaded.\n");
5869 // try to load a .ent file first
5870 dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension);
5871 data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
5872 // and if that is not found, fall back to the bsp file entity string
5874 data = cl.worldmodel->brush.entities;
5877 for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++)
5879 type = LIGHTTYPE_MINUSX;
5880 origin[0] = origin[1] = origin[2] = 0;
5881 originhack[0] = originhack[1] = originhack[2] = 0;
5882 angles[0] = angles[1] = angles[2] = 0;
5883 color[0] = color[1] = color[2] = 1;
5884 light[0] = light[1] = light[2] = 1;light[3] = 300;
5885 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
5895 if (!COM_ParseToken_Simple(&data, false, false))
5897 if (com_token[0] == '}')
5898 break; // end of entity
5899 if (com_token[0] == '_')
5900 strlcpy(key, com_token + 1, sizeof(key));
5902 strlcpy(key, com_token, sizeof(key));
5903 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5904 key[strlen(key)-1] = 0;
5905 if (!COM_ParseToken_Simple(&data, false, false))
5907 strlcpy(value, com_token, sizeof(value));
5909 // now that we have the key pair worked out...
5910 if (!strcmp("light", key))
5912 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
5916 light[0] = vec[0] * (1.0f / 256.0f);
5917 light[1] = vec[0] * (1.0f / 256.0f);
5918 light[2] = vec[0] * (1.0f / 256.0f);
5924 light[0] = vec[0] * (1.0f / 255.0f);
5925 light[1] = vec[1] * (1.0f / 255.0f);
5926 light[2] = vec[2] * (1.0f / 255.0f);
5930 else if (!strcmp("delay", key))
5932 else if (!strcmp("origin", key))
5933 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
5934 else if (!strcmp("angle", key))
5935 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
5936 else if (!strcmp("angles", key))
5937 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
5938 else if (!strcmp("color", key))
5939 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
5940 else if (!strcmp("wait", key))
5941 fadescale = atof(value);
5942 else if (!strcmp("classname", key))
5944 if (!strncmp(value, "light", 5))
5947 if (!strcmp(value, "light_fluoro"))
5952 overridecolor[0] = 1;
5953 overridecolor[1] = 1;
5954 overridecolor[2] = 1;
5956 if (!strcmp(value, "light_fluorospark"))
5961 overridecolor[0] = 1;
5962 overridecolor[1] = 1;
5963 overridecolor[2] = 1;
5965 if (!strcmp(value, "light_globe"))
5970 overridecolor[0] = 1;
5971 overridecolor[1] = 0.8;
5972 overridecolor[2] = 0.4;
5974 if (!strcmp(value, "light_flame_large_yellow"))
5979 overridecolor[0] = 1;
5980 overridecolor[1] = 0.5;
5981 overridecolor[2] = 0.1;
5983 if (!strcmp(value, "light_flame_small_yellow"))
5988 overridecolor[0] = 1;
5989 overridecolor[1] = 0.5;
5990 overridecolor[2] = 0.1;
5992 if (!strcmp(value, "light_torch_small_white"))
5997 overridecolor[0] = 1;
5998 overridecolor[1] = 0.5;
5999 overridecolor[2] = 0.1;
6001 if (!strcmp(value, "light_torch_small_walltorch"))
6006 overridecolor[0] = 1;
6007 overridecolor[1] = 0.5;
6008 overridecolor[2] = 0.1;
6012 else if (!strcmp("style", key))
6013 style = atoi(value);
6014 else if (!strcmp("skin", key))
6015 skin = (int)atof(value);
6016 else if (!strcmp("pflags", key))
6017 pflags = (int)atof(value);
6018 //else if (!strcmp("effects", key))
6019 // effects = (int)atof(value);
6020 else if (cl.worldmodel->type == mod_brushq3)
6022 if (!strcmp("scale", key))
6023 lightscale = atof(value);
6024 if (!strcmp("fade", key))
6025 fadescale = atof(value);
6030 if (lightscale <= 0)
6034 if (color[0] == color[1] && color[0] == color[2])
6036 color[0] *= overridecolor[0];
6037 color[1] *= overridecolor[1];
6038 color[2] *= overridecolor[2];
6040 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
6041 color[0] = color[0] * light[0];
6042 color[1] = color[1] * light[1];
6043 color[2] = color[2] * light[2];
6046 case LIGHTTYPE_MINUSX:
6048 case LIGHTTYPE_RECIPX:
6050 VectorScale(color, (1.0f / 16.0f), color);
6052 case LIGHTTYPE_RECIPXX:
6054 VectorScale(color, (1.0f / 16.0f), color);
6057 case LIGHTTYPE_NONE:
6061 case LIGHTTYPE_MINUSXX:
6064 VectorAdd(origin, originhack, origin);
6066 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);
6069 Mem_Free(entfiledata);
6073 void R_Shadow_SetCursorLocationForView(void)
6076 vec3_t dest, endpos;
6078 VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest);
6079 trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true);
6080 if (trace.fraction < 1)
6082 dist = trace.fraction * r_editlights_cursordistance.value;
6083 push = r_editlights_cursorpushback.value;
6087 VectorMA(trace.endpos, push, r_refdef.view.forward, endpos);
6088 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
6092 VectorClear( endpos );
6094 r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6095 r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6096 r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
6099 void R_Shadow_UpdateWorldLightSelection(void)
6101 if (r_editlights.integer)
6103 R_Shadow_SetCursorLocationForView();
6104 R_Shadow_SelectLightInView();
6107 R_Shadow_SelectLight(NULL);
6110 void R_Shadow_EditLights_Clear_f(void)
6112 R_Shadow_ClearWorldLights();
6115 void R_Shadow_EditLights_Reload_f(void)
6119 strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname));
6120 R_Shadow_ClearWorldLights();
6121 R_Shadow_LoadWorldLights();
6122 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6124 R_Shadow_LoadLightsFile();
6125 if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray))
6126 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6130 void R_Shadow_EditLights_Save_f(void)
6134 R_Shadow_SaveWorldLights();
6137 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
6139 R_Shadow_ClearWorldLights();
6140 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
6143 void R_Shadow_EditLights_ImportLightsFile_f(void)
6145 R_Shadow_ClearWorldLights();
6146 R_Shadow_LoadLightsFile();
6149 void R_Shadow_EditLights_Spawn_f(void)
6152 if (!r_editlights.integer)
6154 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6157 if (Cmd_Argc() != 1)
6159 Con_Print("r_editlights_spawn does not take parameters\n");
6162 color[0] = color[1] = color[2] = 1;
6163 R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
6166 void R_Shadow_EditLights_Edit_f(void)
6168 vec3_t origin, angles, color;
6169 vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
6170 int style, shadows, flags, normalmode, realtimemode;
6171 char cubemapname[MAX_INPUTLINE];
6172 if (!r_editlights.integer)
6174 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6177 if (!r_shadow_selectedlight)
6179 Con_Print("No selected light.\n");
6182 VectorCopy(r_shadow_selectedlight->origin, origin);
6183 VectorCopy(r_shadow_selectedlight->angles, angles);
6184 VectorCopy(r_shadow_selectedlight->color, color);
6185 radius = r_shadow_selectedlight->radius;
6186 style = r_shadow_selectedlight->style;
6187 if (r_shadow_selectedlight->cubemapname)
6188 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
6191 shadows = r_shadow_selectedlight->shadow;
6192 corona = r_shadow_selectedlight->corona;
6193 coronasizescale = r_shadow_selectedlight->coronasizescale;
6194 ambientscale = r_shadow_selectedlight->ambientscale;
6195 diffusescale = r_shadow_selectedlight->diffusescale;
6196 specularscale = r_shadow_selectedlight->specularscale;
6197 flags = r_shadow_selectedlight->flags;
6198 normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
6199 realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
6200 if (!strcmp(Cmd_Argv(1), "origin"))
6202 if (Cmd_Argc() != 5)
6204 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6207 origin[0] = atof(Cmd_Argv(2));
6208 origin[1] = atof(Cmd_Argv(3));
6209 origin[2] = atof(Cmd_Argv(4));
6211 else if (!strcmp(Cmd_Argv(1), "originscale"))
6213 if (Cmd_Argc() != 5)
6215 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6218 origin[0] *= atof(Cmd_Argv(2));
6219 origin[1] *= atof(Cmd_Argv(3));
6220 origin[2] *= atof(Cmd_Argv(4));
6222 else if (!strcmp(Cmd_Argv(1), "originx"))
6224 if (Cmd_Argc() != 3)
6226 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6229 origin[0] = atof(Cmd_Argv(2));
6231 else if (!strcmp(Cmd_Argv(1), "originy"))
6233 if (Cmd_Argc() != 3)
6235 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6238 origin[1] = atof(Cmd_Argv(2));
6240 else if (!strcmp(Cmd_Argv(1), "originz"))
6242 if (Cmd_Argc() != 3)
6244 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6247 origin[2] = atof(Cmd_Argv(2));
6249 else if (!strcmp(Cmd_Argv(1), "move"))
6251 if (Cmd_Argc() != 5)
6253 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6256 origin[0] += atof(Cmd_Argv(2));
6257 origin[1] += atof(Cmd_Argv(3));
6258 origin[2] += atof(Cmd_Argv(4));
6260 else if (!strcmp(Cmd_Argv(1), "movex"))
6262 if (Cmd_Argc() != 3)
6264 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6267 origin[0] += atof(Cmd_Argv(2));
6269 else if (!strcmp(Cmd_Argv(1), "movey"))
6271 if (Cmd_Argc() != 3)
6273 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6276 origin[1] += atof(Cmd_Argv(2));
6278 else if (!strcmp(Cmd_Argv(1), "movez"))
6280 if (Cmd_Argc() != 3)
6282 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6285 origin[2] += atof(Cmd_Argv(2));
6287 else if (!strcmp(Cmd_Argv(1), "angles"))
6289 if (Cmd_Argc() != 5)
6291 Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
6294 angles[0] = atof(Cmd_Argv(2));
6295 angles[1] = atof(Cmd_Argv(3));
6296 angles[2] = atof(Cmd_Argv(4));
6298 else if (!strcmp(Cmd_Argv(1), "anglesx"))
6300 if (Cmd_Argc() != 3)
6302 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6305 angles[0] = atof(Cmd_Argv(2));
6307 else if (!strcmp(Cmd_Argv(1), "anglesy"))
6309 if (Cmd_Argc() != 3)
6311 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6314 angles[1] = atof(Cmd_Argv(2));
6316 else if (!strcmp(Cmd_Argv(1), "anglesz"))
6318 if (Cmd_Argc() != 3)
6320 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6323 angles[2] = atof(Cmd_Argv(2));
6325 else if (!strcmp(Cmd_Argv(1), "color"))
6327 if (Cmd_Argc() != 5)
6329 Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
6332 color[0] = atof(Cmd_Argv(2));
6333 color[1] = atof(Cmd_Argv(3));
6334 color[2] = atof(Cmd_Argv(4));
6336 else if (!strcmp(Cmd_Argv(1), "radius"))
6338 if (Cmd_Argc() != 3)
6340 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6343 radius = atof(Cmd_Argv(2));
6345 else if (!strcmp(Cmd_Argv(1), "colorscale"))
6347 if (Cmd_Argc() == 3)
6349 double scale = atof(Cmd_Argv(2));
6356 if (Cmd_Argc() != 5)
6358 Con_Printf("usage: r_editlights_edit %s red green blue (OR grey instead of red green blue)\n", Cmd_Argv(1));
6361 color[0] *= atof(Cmd_Argv(2));
6362 color[1] *= atof(Cmd_Argv(3));
6363 color[2] *= atof(Cmd_Argv(4));
6366 else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
6368 if (Cmd_Argc() != 3)
6370 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6373 radius *= atof(Cmd_Argv(2));
6375 else if (!strcmp(Cmd_Argv(1), "style"))
6377 if (Cmd_Argc() != 3)
6379 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6382 style = atoi(Cmd_Argv(2));
6384 else if (!strcmp(Cmd_Argv(1), "cubemap"))
6388 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6391 if (Cmd_Argc() == 3)
6392 strlcpy(cubemapname, Cmd_Argv(2), sizeof(cubemapname));
6396 else if (!strcmp(Cmd_Argv(1), "shadows"))
6398 if (Cmd_Argc() != 3)
6400 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6403 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6405 else if (!strcmp(Cmd_Argv(1), "corona"))
6407 if (Cmd_Argc() != 3)
6409 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6412 corona = atof(Cmd_Argv(2));
6414 else if (!strcmp(Cmd_Argv(1), "coronasize"))
6416 if (Cmd_Argc() != 3)
6418 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6421 coronasizescale = atof(Cmd_Argv(2));
6423 else if (!strcmp(Cmd_Argv(1), "ambient"))
6425 if (Cmd_Argc() != 3)
6427 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6430 ambientscale = atof(Cmd_Argv(2));
6432 else if (!strcmp(Cmd_Argv(1), "diffuse"))
6434 if (Cmd_Argc() != 3)
6436 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6439 diffusescale = atof(Cmd_Argv(2));
6441 else if (!strcmp(Cmd_Argv(1), "specular"))
6443 if (Cmd_Argc() != 3)
6445 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6448 specularscale = atof(Cmd_Argv(2));
6450 else if (!strcmp(Cmd_Argv(1), "normalmode"))
6452 if (Cmd_Argc() != 3)
6454 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6457 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6459 else if (!strcmp(Cmd_Argv(1), "realtimemode"))
6461 if (Cmd_Argc() != 3)
6463 Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
6466 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
6470 Con_Print("usage: r_editlights_edit [property] [value]\n");
6471 Con_Print("Selected light's properties:\n");
6472 Con_Printf("Origin : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
6473 Con_Printf("Angles : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
6474 Con_Printf("Color : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
6475 Con_Printf("Radius : %f\n", r_shadow_selectedlight->radius);
6476 Con_Printf("Corona : %f\n", r_shadow_selectedlight->corona);
6477 Con_Printf("Style : %i\n", r_shadow_selectedlight->style);
6478 Con_Printf("Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
6479 Con_Printf("Cubemap : %s\n", r_shadow_selectedlight->cubemapname);
6480 Con_Printf("CoronaSize : %f\n", r_shadow_selectedlight->coronasizescale);
6481 Con_Printf("Ambient : %f\n", r_shadow_selectedlight->ambientscale);
6482 Con_Printf("Diffuse : %f\n", r_shadow_selectedlight->diffusescale);
6483 Con_Printf("Specular : %f\n", r_shadow_selectedlight->specularscale);
6484 Con_Printf("NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
6485 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
6488 flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
6489 R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
6492 void R_Shadow_EditLights_EditAll_f(void)
6495 dlight_t *light, *oldselected;
6498 if (!r_editlights.integer)
6500 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
6504 oldselected = r_shadow_selectedlight;
6505 // EditLights doesn't seem to have a "remove" command or something so:
6506 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6507 for (lightindex = 0;lightindex < range;lightindex++)
6509 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6512 R_Shadow_SelectLight(light);
6513 R_Shadow_EditLights_Edit_f();
6515 // return to old selected (to not mess editing once selection is locked)
6516 R_Shadow_SelectLight(oldselected);
6519 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
6521 int lightnumber, lightcount;
6522 size_t lightindex, range;
6526 if (!r_editlights.integer)
6528 x = vid_conwidth.value - 240;
6530 DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0);
6533 range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked
6534 for (lightindex = 0;lightindex < range;lightindex++)
6536 light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex);
6539 if (light == r_shadow_selectedlight)
6540 lightnumber = lightindex;
6543 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;
6544 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;
6546 if (r_shadow_selectedlight == NULL)
6548 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;
6549 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;
6550 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;
6551 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;
6552 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;
6553 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;
6554 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;
6555 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;
6556 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;
6557 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;
6558 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;
6559 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;
6560 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;
6561 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;
6562 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;
6565 void R_Shadow_EditLights_ToggleShadow_f(void)
6567 if (!r_editlights.integer)
6569 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6572 if (!r_shadow_selectedlight)
6574 Con_Print("No selected light.\n");
6577 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);
6580 void R_Shadow_EditLights_ToggleCorona_f(void)
6582 if (!r_editlights.integer)
6584 Con_Print("Cannot spawn light when not in editing mode. Set r_editlights to 1.\n");
6587 if (!r_shadow_selectedlight)
6589 Con_Print("No selected light.\n");
6592 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);
6595 void R_Shadow_EditLights_Remove_f(void)
6597 if (!r_editlights.integer)
6599 Con_Print("Cannot remove light when not in editing mode. Set r_editlights to 1.\n");
6602 if (!r_shadow_selectedlight)
6604 Con_Print("No selected light.\n");
6607 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
6608 r_shadow_selectedlight = NULL;
6611 void R_Shadow_EditLights_Help_f(void)
6614 "Documentation on r_editlights system:\n"
6616 "r_editlights : enable/disable editing mode\n"
6617 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
6618 "r_editlights_cursorpushback : push back cursor this far from surface\n"
6619 "r_editlights_cursorpushoff : push cursor off surface this far\n"
6620 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
6621 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
6623 "r_editlights_help : this help\n"
6624 "r_editlights_clear : remove all lights\n"
6625 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
6626 "r_editlights_lock : lock selection to current light, if already locked - unlock\n"
6627 "r_editlights_save : save to .rtlights file\n"
6628 "r_editlights_spawn : create a light with default settings\n"
6629 "r_editlights_edit command : edit selected light - more documentation below\n"
6630 "r_editlights_remove : remove selected light\n"
6631 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
6632 "r_editlights_importlightentitiesfrommap : reload light entities\n"
6633 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
6635 "origin x y z : set light location\n"
6636 "originx x: set x component of light location\n"
6637 "originy y: set y component of light location\n"
6638 "originz z: set z component of light location\n"
6639 "move x y z : adjust light location\n"
6640 "movex x: adjust x component of light location\n"
6641 "movey y: adjust y component of light location\n"
6642 "movez z: adjust z component of light location\n"
6643 "angles x y z : set light angles\n"
6644 "anglesx x: set x component of light angles\n"
6645 "anglesy y: set y component of light angles\n"
6646 "anglesz z: set z component of light angles\n"
6647 "color r g b : set color of light (can be brighter than 1 1 1)\n"
6648 "radius radius : set radius (size) of light\n"
6649 "colorscale grey : multiply color of light (1 does nothing)\n"
6650 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
6651 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
6652 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
6653 "originscale x y z : multiply origin of light (1 1 1 does nothing)\n"
6654 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
6655 "cubemap basename : set filter cubemap of light (not yet supported)\n"
6656 "shadows 1/0 : turn on/off shadows\n"
6657 "corona n : set corona intensity\n"
6658 "coronasize n : set corona size (0-1)\n"
6659 "ambient n : set ambient intensity (0-1)\n"
6660 "diffuse n : set diffuse intensity (0-1)\n"
6661 "specular n : set specular intensity (0-1)\n"
6662 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
6663 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
6664 "<nothing> : print light properties to console\n"
6668 void R_Shadow_EditLights_CopyInfo_f(void)
6670 if (!r_editlights.integer)
6672 Con_Print("Cannot copy light info when not in editing mode. Set r_editlights to 1.\n");
6675 if (!r_shadow_selectedlight)
6677 Con_Print("No selected light.\n");
6680 VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
6681 VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
6682 r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
6683 r_shadow_bufferlight.style = r_shadow_selectedlight->style;
6684 if (r_shadow_selectedlight->cubemapname)
6685 strlcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname, sizeof(r_shadow_bufferlight.cubemapname));
6687 r_shadow_bufferlight.cubemapname[0] = 0;
6688 r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
6689 r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
6690 r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
6691 r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
6692 r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
6693 r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
6694 r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
6697 void R_Shadow_EditLights_PasteInfo_f(void)
6699 if (!r_editlights.integer)
6701 Con_Print("Cannot paste light info when not in editing mode. Set r_editlights to 1.\n");
6704 if (!r_shadow_selectedlight)
6706 Con_Print("No selected light.\n");
6709 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);
6712 void R_Shadow_EditLights_Lock_f(void)
6714 if (!r_editlights.integer)
6716 Con_Print("Cannot lock on light when not in editing mode. Set r_editlights to 1.\n");
6719 if (r_editlights_lockcursor)
6721 r_editlights_lockcursor = false;
6724 if (!r_shadow_selectedlight)
6726 Con_Print("No selected light to lock on.\n");
6729 r_editlights_lockcursor = true;
6732 void R_Shadow_EditLights_Init(void)
6734 Cvar_RegisterVariable(&r_editlights);
6735 Cvar_RegisterVariable(&r_editlights_cursordistance);
6736 Cvar_RegisterVariable(&r_editlights_cursorpushback);
6737 Cvar_RegisterVariable(&r_editlights_cursorpushoff);
6738 Cvar_RegisterVariable(&r_editlights_cursorgrid);
6739 Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
6740 Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
6741 Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
6742 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)");
6743 Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
6744 Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
6745 Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
6746 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)");
6747 Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
6748 Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
6749 Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
6750 Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
6751 Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
6752 Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
6753 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)");
6754 Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock");
6760 =============================================================================
6764 =============================================================================
6767 void R_LightPoint(vec3_t color, const vec3_t p, const int flags)
6769 int i, numlights, flag;
6770 float f, relativepoint[3], dist, dist2, lightradius2;
6775 if (r_fullbright.integer)
6777 VectorSet(color, 1, 1, 1);
6783 if (flags & LP_LIGHTMAP)
6785 if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6787 VectorClear(diffuse);
6788 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n);
6789 VectorAdd(color, diffuse, color);
6792 VectorSet(color, 1, 1, 1);
6793 color[0] += r_refdef.scene.ambient;
6794 color[1] += r_refdef.scene.ambient;
6795 color[2] += r_refdef.scene.ambient;
6798 if (flags & LP_RTWORLD)
6800 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6801 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6802 for (i = 0; i < numlights; i++)
6804 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6807 light = &dlight->rtlight;
6808 if (!(light->flags & flag))
6811 lightradius2 = light->radius * light->radius;
6812 VectorSubtract(light->shadoworigin, p, relativepoint);
6813 dist2 = VectorLength2(relativepoint);
6814 if (dist2 >= lightradius2)
6816 dist = sqrt(dist2) / light->radius;
6817 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6820 // todo: add to both ambient and diffuse
6821 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6822 VectorMA(color, f, light->currentcolor, color);
6825 if (flags & LP_DYNLIGHT)
6828 for (i = 0;i < r_refdef.scene.numlights;i++)
6830 light = r_refdef.scene.lights[i];
6832 lightradius2 = light->radius * light->radius;
6833 VectorSubtract(light->shadoworigin, p, relativepoint);
6834 dist2 = VectorLength2(relativepoint);
6835 if (dist2 >= lightradius2)
6837 dist = sqrt(dist2) / light->radius;
6838 f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0;
6841 // todo: add to both ambient and diffuse
6842 if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1)
6843 VectorMA(color, f, light->color, color);
6848 void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags)
6850 int i, numlights, flag;
6853 float relativepoint[3];
6862 if (r_fullbright.integer)
6864 VectorSet(ambient, 1, 1, 1);
6865 VectorClear(diffuse);
6866 VectorClear(lightdir);
6870 if (flags == LP_LIGHTMAP)
6872 VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6873 VectorClear(diffuse);
6874 VectorClear(lightdir);
6875 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6876 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir);
6878 VectorSet(ambient, 1, 1, 1);
6882 memset(sample, 0, sizeof(sample));
6883 VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient);
6885 if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
6888 VectorClear(tempambient);
6890 VectorClear(relativepoint);
6891 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint);
6892 VectorScale(tempambient, r_refdef.lightmapintensity, tempambient);
6893 VectorScale(color, r_refdef.lightmapintensity, color);
6894 VectorAdd(sample, tempambient, sample);
6895 VectorMA(sample , 0.5f , color, sample );
6896 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6897 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6898 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6899 // calculate a weighted average light direction as well
6900 intensity = VectorLength(color);
6901 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6904 if (flags & LP_RTWORLD)
6906 flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
6907 numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray);
6908 for (i = 0; i < numlights; i++)
6910 dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i);
6913 light = &dlight->rtlight;
6914 if (!(light->flags & flag))
6917 lightradius2 = light->radius * light->radius;
6918 VectorSubtract(light->shadoworigin, p, relativepoint);
6919 dist2 = VectorLength2(relativepoint);
6920 if (dist2 >= lightradius2)
6922 dist = sqrt(dist2) / light->radius;
6923 intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value;
6924 if (intensity <= 0.0f)
6926 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6928 // scale down intensity to add to both ambient and diffuse
6929 //intensity *= 0.5f;
6930 VectorNormalize(relativepoint);
6931 VectorScale(light->currentcolor, intensity, color);
6932 VectorMA(sample , 0.5f , color, sample );
6933 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6934 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6935 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6936 // calculate a weighted average light direction as well
6937 intensity *= VectorLength(color);
6938 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6942 if (flags & LP_DYNLIGHT)
6945 for (i = 0;i < r_refdef.scene.numlights;i++)
6947 light = r_refdef.scene.lights[i];
6949 lightradius2 = light->radius * light->radius;
6950 VectorSubtract(light->shadoworigin, p, relativepoint);
6951 dist2 = VectorLength2(relativepoint);
6952 if (dist2 >= lightradius2)
6954 dist = sqrt(dist2) / light->radius;
6955 intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value;
6956 if (intensity <= 0.0f)
6958 if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1)
6960 // scale down intensity to add to both ambient and diffuse
6961 //intensity *= 0.5f;
6962 VectorNormalize(relativepoint);
6963 VectorScale(light->currentcolor, intensity, color);
6964 VectorMA(sample , 0.5f , color, sample );
6965 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
6966 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
6967 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
6968 // calculate a weighted average light direction as well
6969 intensity *= VectorLength(color);
6970 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
6974 // calculate the direction we'll use to reduce the sample to a directional light source
6975 VectorCopy(sample + 12, dir);
6976 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
6977 VectorNormalize(dir);
6978 // extract the diffuse color along the chosen direction and scale it
6979 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
6980 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
6981 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
6982 // subtract some of diffuse from ambient
6983 VectorMA(sample, -0.333f, diffuse, ambient);
6984 // store the normalized lightdir
6985 VectorCopy(dir, lightdir);