]> icculus.org git repositories - divverent/darkplaces.git/blob - r_shadow.c
791e073ef0085f89c97717c8032cbc037dd31af6
[divverent/darkplaces.git] / r_shadow.c
1
2 /*
3 Terminology: Stencil Shadow Volume (sometimes called Stencil Shadows)
4 An extrusion of the lit faces, beginning at the original geometry and ending
5 further from the light source than the original geometry (presumably at least
6 as far as the light's radius, if the light has a radius at all), capped at
7 both front and back to avoid any problems (extrusion from dark faces also
8 works but has a different set of problems)
9
10 This is normally rendered using Carmack's Reverse technique, in which
11 backfaces behind zbuffer (zfail) increment the stencil, and frontfaces behind
12 zbuffer (zfail) decrement the stencil, the result is a stencil value of zero
13 where shadows did not intersect the visible geometry, suitable as a stencil
14 mask for rendering lighting everywhere but shadow.
15
16 In our case to hopefully avoid the Creative Labs patent, we draw the backfaces
17 as decrement and the frontfaces as increment, and we redefine the DepthFunc to
18 GL_LESS (the patent uses GL_GEQUAL) which causes zfail when behind surfaces
19 and zpass when infront (the patent draws where zpass with a GL_GEQUAL test),
20 additionally we clear stencil to 128 to avoid the need for the unclamped
21 incr/decr extension (not related to patent).
22
23 Patent warning:
24 This algorithm may be covered by Creative's patent (US Patent #6384822),
25 however that patent is quite specific about increment on backfaces and
26 decrement on frontfaces where zpass with GL_GEQUAL depth test, which is
27 opposite this implementation and partially opposite Carmack's Reverse paper
28 (which uses GL_LESS, but increments on backfaces and decrements on frontfaces).
29
30
31
32 Terminology: Stencil Light Volume (sometimes called Light Volumes)
33 Similar to a Stencil Shadow Volume, but inverted; rather than containing the
34 areas in shadow it contains the areas in light, this can only be built
35 quickly for certain limited cases (such as portal visibility from a point),
36 but is quite useful for some effects (sunlight coming from sky polygons is
37 one possible example, translucent occluders is another example).
38
39
40
41 Terminology: Optimized Stencil Shadow Volume
42 A Stencil Shadow Volume that has been processed sufficiently to ensure it has
43 no duplicate coverage of areas (no need to shadow an area twice), often this
44 greatly improves performance but is an operation too costly to use on moving
45 lights (however completely optimal Stencil Light Volumes can be constructed
46 in some ideal cases).
47
48
49
50 Terminology: Per Pixel Lighting (sometimes abbreviated PPL)
51 Per pixel evaluation of lighting equations, at a bare minimum this involves
52 DOT3 shading of diffuse lighting (per pixel dotproduct of negated incidence
53 vector and surface normal, using a texture of the surface bumps, called a
54 NormalMap) if supported by hardware; in our case there is support for cards
55 which are incapable of DOT3, the quality is quite poor however.  Additionally
56 it is desirable to have specular evaluation per pixel, per vertex
57 normalization of specular halfangle vectors causes noticable distortion but
58 is unavoidable on hardware without GL_ARB_fragment_program or
59 GL_ARB_fragment_shader.
60
61
62
63 Terminology: Normalization CubeMap
64 A cubemap containing normalized dot3-encoded (vectors of length 1 or less
65 encoded as RGB colors) for any possible direction, this technique allows per
66 pixel calculation of incidence vector for per pixel lighting purposes, which
67 would not otherwise be possible per pixel without GL_ARB_fragment_program or
68 GL_ARB_fragment_shader.
69
70
71
72 Terminology: 2D+1D Attenuation Texturing
73 A very crude approximation of light attenuation with distance which results
74 in cylindrical light shapes which fade vertically as a streak (some games
75 such as Doom3 allow this to be rotated to be less noticable in specific
76 cases), the technique is simply modulating lighting by two 2D textures (which
77 can be the same) on different axes of projection (XY and Z, typically), this
78 is the second best technique available without 3D Attenuation Texturing,
79 GL_ARB_fragment_program or GL_ARB_fragment_shader technology.
80
81
82
83 Terminology: 2D+1D Inverse Attenuation Texturing
84 A clever method described in papers on the Abducted engine, this has a squared
85 distance texture (bright on the outside, black in the middle), which is used
86 twice using GL_ADD blending, the result of this is used in an inverse modulate
87 (GL_ONE_MINUS_DST_ALPHA, GL_ZERO) to implement the equation
88 lighting*=(1-((X*X+Y*Y)+(Z*Z))) which is spherical (unlike 2D+1D attenuation
89 texturing).
90
91
92
93 Terminology: 3D Attenuation Texturing
94 A slightly crude approximation of light attenuation with distance, its flaws
95 are limited radius and resolution (performance tradeoffs).
96
97
98
99 Terminology: 3D Attenuation-Normalization Texturing
100 A 3D Attenuation Texture merged with a Normalization CubeMap, by making the
101 vectors shorter the lighting becomes darker, a very effective optimization of
102 diffuse lighting if 3D Attenuation Textures are already used.
103
104
105
106 Terminology: Light Cubemap Filtering
107 A technique for modeling non-uniform light distribution according to
108 direction, for example a lantern may use a cubemap to describe the light
109 emission pattern of the cage around the lantern (as well as soot buildup
110 discoloring the light in certain areas), often also used for softened grate
111 shadows and light shining through a stained glass window (done crudely by
112 texturing the lighting with a cubemap), another good example would be a disco
113 light.  This technique is used heavily in many games (Doom3 does not support
114 this however).
115
116
117
118 Terminology: Light Projection Filtering
119 A technique for modeling shadowing of light passing through translucent
120 surfaces, allowing stained glass windows and other effects to be done more
121 elegantly than possible with Light Cubemap Filtering by applying an occluder
122 texture to the lighting combined with a stencil light volume to limit the lit
123 area, this technique is used by Doom3 for spotlights and flashlights, among
124 other things, this can also be used more generally to render light passing
125 through multiple translucent occluders in a scene (using a light volume to
126 describe the area beyond the occluder, and thus mask off rendering of all
127 other areas).
128
129
130
131 Terminology: Doom3 Lighting
132 A combination of Stencil Shadow Volume, Per Pixel Lighting, Normalization
133 CubeMap, 2D+1D Attenuation Texturing, and Light Projection Filtering, as
134 demonstrated by the game Doom3.
135 */
136
137 #include "quakedef.h"
138 #include "r_shadow.h"
139 #include "cl_collision.h"
140 #include "portals.h"
141 #include "image.h"
142
143 extern void R_Shadow_EditLights_Init(void);
144
145 typedef enum r_shadow_rendermode_e
146 {
147         R_SHADOW_RENDERMODE_NONE,
148         R_SHADOW_RENDERMODE_STENCIL,
149         R_SHADOW_RENDERMODE_STENCILTWOSIDE,
150         R_SHADOW_RENDERMODE_LIGHT_VERTEX,
151         R_SHADOW_RENDERMODE_LIGHT_DOT3,
152         R_SHADOW_RENDERMODE_LIGHT_GLSL,
153         R_SHADOW_RENDERMODE_VISIBLEVOLUMES,
154         R_SHADOW_RENDERMODE_VISIBLELIGHTING,
155 }
156 r_shadow_rendermode_t;
157
158 r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
159 r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE;
160 r_shadow_rendermode_t r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_NONE;
161
162 int maxshadowtriangles;
163 int *shadowelements;
164
165 int maxshadowvertices;
166 float *shadowvertex3f;
167
168 int maxshadowmark;
169 int numshadowmark;
170 int *shadowmark;
171 int *shadowmarklist;
172 int shadowmarkcount;
173
174 int maxvertexupdate;
175 int *vertexupdate;
176 int *vertexremap;
177 int vertexupdatenum;
178
179 int r_shadow_buffer_numleafpvsbytes;
180 unsigned char *r_shadow_buffer_leafpvs;
181 int *r_shadow_buffer_leaflist;
182
183 int r_shadow_buffer_numsurfacepvsbytes;
184 unsigned char *r_shadow_buffer_surfacepvs;
185 int *r_shadow_buffer_surfacelist;
186
187 rtexturepool_t *r_shadow_texturepool;
188 rtexture_t *r_shadow_attenuation2dtexture;
189 rtexture_t *r_shadow_attenuation3dtexture;
190
191 // lights are reloaded when this changes
192 char r_shadow_mapname[MAX_QPATH];
193
194 // used only for light filters (cubemaps)
195 rtexturepool_t *r_shadow_filters_texturepool;
196
197 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"};
198 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"};
199 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"};
200 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)"};
201 cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.25", "how bright the forced flat gloss should look if r_shadow_gloss is 2"};
202 cvar_t r_shadow_glossintensity = {0, "r_shadow_glossintensity", "1", "how bright textured glossmaps should look if r_shadow_gloss is 1 or 2"};
203 cvar_t r_shadow_lightattenuationpower = {0, "r_shadow_lightattenuationpower", "0.5", "changes attenuation texture generation (does not affect r_glsl lighting)"};
204 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "1", "changes attenuation texture generation (does not affect r_glsl lighting)"};
205 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"};
206 cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"};
207 cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"};
208 cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"};
209 cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"};
210 cvar_t r_shadow_realtime_dlight_portalculling = {0, "r_shadow_realtime_dlight_portalculling", "0", "enables portal culling optimizations on dynamic lights (slow!  you probably don't want this!)"};
211 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)"};
212 cvar_t r_shadow_realtime_world_dlightshadows = {CVAR_SAVE, "r_shadow_realtime_world_dlightshadows", "1", "enables shadows from dynamic lights when using full world lighting"};
213 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"};
214 cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"};
215 cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"};
216 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"};
217 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)"};
218 cvar_t r_shadow_shadow_polygonfactor = {0, "r_shadow_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"};
219 cvar_t r_shadow_shadow_polygonoffset = {0, "r_shadow_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)"};
220 cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"};
221 cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"};
222 cvar_t r_editlights = {0, "r_editlights", "0", "enables .rtlights file editing mode"};
223 cvar_t r_editlights_cursordistance = {0, "r_editlights_cursordistance", "1024", "maximum distance of cursor from eye"};
224 cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "how far to pull the cursor back toward the eye"};
225 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"};
226 cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"};
227 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"};
228
229 float r_shadow_attenpower, r_shadow_attenscale;
230
231 rtlight_t *r_shadow_compilingrtlight;
232 dlight_t *r_shadow_worldlightchain;
233 dlight_t *r_shadow_selectedlight;
234 dlight_t r_shadow_bufferlight;
235 vec3_t r_editlights_cursorlocation;
236
237 extern int con_vislines;
238
239 typedef struct cubemapinfo_s
240 {
241         char basename[64];
242         rtexture_t *texture;
243 }
244 cubemapinfo_t;
245
246 #define MAX_CUBEMAPS 256
247 static int numcubemaps;
248 static cubemapinfo_t cubemaps[MAX_CUBEMAPS];
249
250 void R_Shadow_UncompileWorldLights(void);
251 void R_Shadow_ClearWorldLights(void);
252 void R_Shadow_SaveWorldLights(void);
253 void R_Shadow_LoadWorldLights(void);
254 void R_Shadow_LoadLightsFile(void);
255 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
256 void R_Shadow_EditLights_Reload_f(void);
257 void R_Shadow_ValidateCvars(void);
258 static void R_Shadow_MakeTextures(void);
259 void R_Shadow_DrawWorldLightShadowVolume(matrix4x4_t *matrix, dlight_t *light);
260
261 void r_shadow_start(void)
262 {
263         // allocate vertex processing arrays
264         numcubemaps = 0;
265         r_shadow_attenuation2dtexture = NULL;
266         r_shadow_attenuation3dtexture = NULL;
267         r_shadow_texturepool = NULL;
268         r_shadow_filters_texturepool = NULL;
269         R_Shadow_ValidateCvars();
270         R_Shadow_MakeTextures();
271         maxshadowtriangles = 0;
272         shadowelements = NULL;
273         maxshadowvertices = 0;
274         shadowvertex3f = NULL;
275         maxvertexupdate = 0;
276         vertexupdate = NULL;
277         vertexremap = NULL;
278         vertexupdatenum = 0;
279         maxshadowmark = 0;
280         numshadowmark = 0;
281         shadowmark = NULL;
282         shadowmarklist = NULL;
283         shadowmarkcount = 0;
284         r_shadow_buffer_numleafpvsbytes = 0;
285         r_shadow_buffer_leafpvs = NULL;
286         r_shadow_buffer_leaflist = NULL;
287         r_shadow_buffer_numsurfacepvsbytes = 0;
288         r_shadow_buffer_surfacepvs = NULL;
289         r_shadow_buffer_surfacelist = NULL;
290 }
291
292 void r_shadow_shutdown(void)
293 {
294         R_Shadow_UncompileWorldLights();
295         numcubemaps = 0;
296         r_shadow_attenuation2dtexture = NULL;
297         r_shadow_attenuation3dtexture = NULL;
298         R_FreeTexturePool(&r_shadow_texturepool);
299         R_FreeTexturePool(&r_shadow_filters_texturepool);
300         maxshadowtriangles = 0;
301         if (shadowelements)
302                 Mem_Free(shadowelements);
303         shadowelements = NULL;
304         if (shadowvertex3f)
305                 Mem_Free(shadowvertex3f);
306         shadowvertex3f = NULL;
307         maxvertexupdate = 0;
308         if (vertexupdate)
309                 Mem_Free(vertexupdate);
310         vertexupdate = NULL;
311         if (vertexremap)
312                 Mem_Free(vertexremap);
313         vertexremap = NULL;
314         vertexupdatenum = 0;
315         maxshadowmark = 0;
316         numshadowmark = 0;
317         if (shadowmark)
318                 Mem_Free(shadowmark);
319         shadowmark = NULL;
320         if (shadowmarklist)
321                 Mem_Free(shadowmarklist);
322         shadowmarklist = NULL;
323         shadowmarkcount = 0;
324         r_shadow_buffer_numleafpvsbytes = 0;
325         if (r_shadow_buffer_leafpvs)
326                 Mem_Free(r_shadow_buffer_leafpvs);
327         r_shadow_buffer_leafpvs = NULL;
328         if (r_shadow_buffer_leaflist)
329                 Mem_Free(r_shadow_buffer_leaflist);
330         r_shadow_buffer_leaflist = NULL;
331         r_shadow_buffer_numsurfacepvsbytes = 0;
332         if (r_shadow_buffer_surfacepvs)
333                 Mem_Free(r_shadow_buffer_surfacepvs);
334         r_shadow_buffer_surfacepvs = NULL;
335         if (r_shadow_buffer_surfacelist)
336                 Mem_Free(r_shadow_buffer_surfacelist);
337         r_shadow_buffer_surfacelist = NULL;
338 }
339
340 void r_shadow_newmap(void)
341 {
342 }
343
344 void R_Shadow_Help_f(void)
345 {
346         Con_Printf(
347 "Documentation on r_shadow system:\n"
348 "Settings:\n"
349 "r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n"
350 "r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n"
351 "r_shadow_debuglight : render only this light number (-1 = all)\n"
352 "r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n"
353 "r_shadow_gloss2intensity : brightness of forced gloss\n"
354 "r_shadow_glossintensity : brightness of textured gloss\n"
355 "r_shadow_lightattenuationpower : used to generate attenuation texture\n"
356 "r_shadow_lightattenuationscale : used to generate attenuation texture\n"
357 "r_shadow_lightintensityscale : scale rendering brightness of all lights\n"
358 "r_shadow_portallight : use portal visibility for static light precomputation\n"
359 "r_shadow_projectdistance : shadow volume projection distance\n"
360 "r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n"
361 "r_shadow_realtime_dlight_shadows : cast shadows from dlights\n"
362 "r_shadow_realtime_dlight_portalculling : work hard to reduce graphics work\n"
363 "r_shadow_realtime_world : use high quality world lighting mode\n"
364 "r_shadow_realtime_world_dlightshadows : cast shadows from dlights\n"
365 "r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n"
366 "r_shadow_realtime_world_shadows : cast shadows from world lights\n"
367 "r_shadow_realtime_world_compile : compile surface/visibility information\n"
368 "r_shadow_realtime_world_compileshadow : compile shadow geometry\n"
369 "r_shadow_scissor : use scissor optimization\n"
370 "r_shadow_shadow_polygonfactor : nudge shadow volumes closer/further\n"
371 "r_shadow_shadow_polygonoffset : nudge shadow volumes closer/further\n"
372 "r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n"
373 "r_showlighting : useful for performance testing; bright = slow!\n"
374 "r_showshadowvolumes : useful for performance testing; bright = slow!\n"
375 "Commands:\n"
376 "r_shadow_help : this help\n"
377         );
378 }
379
380 void R_Shadow_Init(void)
381 {
382         Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture);
383         Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap);
384         Cvar_RegisterVariable(&r_shadow_debuglight);
385         Cvar_RegisterVariable(&r_shadow_gloss);
386         Cvar_RegisterVariable(&r_shadow_gloss2intensity);
387         Cvar_RegisterVariable(&r_shadow_glossintensity);
388         Cvar_RegisterVariable(&r_shadow_lightattenuationpower);
389         Cvar_RegisterVariable(&r_shadow_lightattenuationscale);
390         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
391         Cvar_RegisterVariable(&r_shadow_portallight);
392         Cvar_RegisterVariable(&r_shadow_projectdistance);
393         Cvar_RegisterVariable(&r_shadow_realtime_dlight);
394         Cvar_RegisterVariable(&r_shadow_realtime_dlight_shadows);
395         Cvar_RegisterVariable(&r_shadow_realtime_dlight_portalculling);
396         Cvar_RegisterVariable(&r_shadow_realtime_world);
397         Cvar_RegisterVariable(&r_shadow_realtime_world_dlightshadows);
398         Cvar_RegisterVariable(&r_shadow_realtime_world_lightmaps);
399         Cvar_RegisterVariable(&r_shadow_realtime_world_shadows);
400         Cvar_RegisterVariable(&r_shadow_realtime_world_compile);
401         Cvar_RegisterVariable(&r_shadow_realtime_world_compileshadow);
402         Cvar_RegisterVariable(&r_shadow_scissor);
403         Cvar_RegisterVariable(&r_shadow_shadow_polygonfactor);
404         Cvar_RegisterVariable(&r_shadow_shadow_polygonoffset);
405         Cvar_RegisterVariable(&r_shadow_texture3d);
406         Cvar_RegisterVariable(&gl_ext_stenciltwoside);
407         if (gamemode == GAME_TENEBRAE)
408         {
409                 Cvar_SetValue("r_shadow_gloss", 2);
410                 Cvar_SetValue("r_shadow_bumpscale_basetexture", 4);
411         }
412         Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system");
413         R_Shadow_EditLights_Init();
414         r_shadow_worldlightchain = NULL;
415         maxshadowtriangles = 0;
416         shadowelements = NULL;
417         maxshadowvertices = 0;
418         shadowvertex3f = NULL;
419         maxvertexupdate = 0;
420         vertexupdate = NULL;
421         vertexremap = NULL;
422         vertexupdatenum = 0;
423         maxshadowmark = 0;
424         numshadowmark = 0;
425         shadowmark = NULL;
426         shadowmarklist = NULL;
427         shadowmarkcount = 0;
428         r_shadow_buffer_numleafpvsbytes = 0;
429         r_shadow_buffer_leafpvs = NULL;
430         r_shadow_buffer_leaflist = NULL;
431         r_shadow_buffer_numsurfacepvsbytes = 0;
432         r_shadow_buffer_surfacepvs = NULL;
433         r_shadow_buffer_surfacelist = NULL;
434         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
435 }
436
437 matrix4x4_t matrix_attenuationxyz =
438 {
439         {
440                 {0.5, 0.0, 0.0, 0.5},
441                 {0.0, 0.5, 0.0, 0.5},
442                 {0.0, 0.0, 0.5, 0.5},
443                 {0.0, 0.0, 0.0, 1.0}
444         }
445 };
446
447 matrix4x4_t matrix_attenuationz =
448 {
449         {
450                 {0.0, 0.0, 0.5, 0.5},
451                 {0.0, 0.0, 0.0, 0.5},
452                 {0.0, 0.0, 0.0, 0.5},
453                 {0.0, 0.0, 0.0, 1.0}
454         }
455 };
456
457 void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles)
458 {
459         // make sure shadowelements is big enough for this volume
460         if (maxshadowtriangles < numtriangles)
461         {
462                 maxshadowtriangles = numtriangles;
463                 if (shadowelements)
464                         Mem_Free(shadowelements);
465                 shadowelements = (int *)Mem_Alloc(r_main_mempool, maxshadowtriangles * sizeof(int[24]));
466         }
467         // make sure shadowvertex3f is big enough for this volume
468         if (maxshadowvertices < numvertices)
469         {
470                 maxshadowvertices = numvertices;
471                 if (shadowvertex3f)
472                         Mem_Free(shadowvertex3f);
473                 shadowvertex3f = (float *)Mem_Alloc(r_main_mempool, maxshadowvertices * sizeof(float[6]));
474         }
475 }
476
477 static void R_Shadow_EnlargeLeafSurfaceBuffer(int numleafs, int numsurfaces)
478 {
479         int numleafpvsbytes = (((numleafs + 7) >> 3) + 255) & ~255;
480         int numsurfacepvsbytes = (((numsurfaces + 7) >> 3) + 255) & ~255;
481         if (r_shadow_buffer_numleafpvsbytes < numleafpvsbytes)
482         {
483                 if (r_shadow_buffer_leafpvs)
484                         Mem_Free(r_shadow_buffer_leafpvs);
485                 if (r_shadow_buffer_leaflist)
486                         Mem_Free(r_shadow_buffer_leaflist);
487                 r_shadow_buffer_numleafpvsbytes = numleafpvsbytes;
488                 r_shadow_buffer_leafpvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes);
489                 r_shadow_buffer_leaflist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numleafpvsbytes * 8 * sizeof(*r_shadow_buffer_leaflist));
490         }
491         if (r_shadow_buffer_numsurfacepvsbytes < numsurfacepvsbytes)
492         {
493                 if (r_shadow_buffer_surfacepvs)
494                         Mem_Free(r_shadow_buffer_surfacepvs);
495                 if (r_shadow_buffer_surfacelist)
496                         Mem_Free(r_shadow_buffer_surfacelist);
497                 r_shadow_buffer_numsurfacepvsbytes = numsurfacepvsbytes;
498                 r_shadow_buffer_surfacepvs = (unsigned char *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes);
499                 r_shadow_buffer_surfacelist = (int *)Mem_Alloc(r_main_mempool, r_shadow_buffer_numsurfacepvsbytes * 8 * sizeof(*r_shadow_buffer_surfacelist));
500         }
501 }
502
503 void R_Shadow_PrepareShadowMark(int numtris)
504 {
505         // make sure shadowmark is big enough for this volume
506         if (maxshadowmark < numtris)
507         {
508                 maxshadowmark = numtris;
509                 if (shadowmark)
510                         Mem_Free(shadowmark);
511                 if (shadowmarklist)
512                         Mem_Free(shadowmarklist);
513                 shadowmark = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmark));
514                 shadowmarklist = (int *)Mem_Alloc(r_main_mempool, maxshadowmark * sizeof(*shadowmarklist));
515                 shadowmarkcount = 0;
516         }
517         shadowmarkcount++;
518         // if shadowmarkcount wrapped we clear the array and adjust accordingly
519         if (shadowmarkcount == 0)
520         {
521                 shadowmarkcount = 1;
522                 memset(shadowmark, 0, maxshadowmark * sizeof(*shadowmark));
523         }
524         numshadowmark = 0;
525 }
526
527 int R_Shadow_ConstructShadowVolume(int innumvertices, int innumtris, const int *inelement3i, const int *inneighbor3i, const float *invertex3f, int *outnumvertices, int *outelement3i, float *outvertex3f, const float *projectorigin, float projectdistance, int numshadowmarktris, const int *shadowmarktris)
528 {
529         int i, j;
530         int outtriangles = 0, outvertices = 0;
531         const int *element;
532         const float *vertex;
533
534         if (maxvertexupdate < innumvertices)
535         {
536                 maxvertexupdate = innumvertices;
537                 if (vertexupdate)
538                         Mem_Free(vertexupdate);
539                 if (vertexremap)
540                         Mem_Free(vertexremap);
541                 vertexupdate = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
542                 vertexremap = (int *)Mem_Alloc(r_main_mempool, maxvertexupdate * sizeof(int));
543                 vertexupdatenum = 0;
544         }
545         vertexupdatenum++;
546         if (vertexupdatenum == 0)
547         {
548                 vertexupdatenum = 1;
549                 memset(vertexupdate, 0, maxvertexupdate * sizeof(int));
550                 memset(vertexremap, 0, maxvertexupdate * sizeof(int));
551         }
552
553         for (i = 0;i < numshadowmarktris;i++)
554                 shadowmark[shadowmarktris[i]] = shadowmarkcount;
555
556         for (i = 0;i < numshadowmarktris;i++)
557         {
558                 element = inelement3i + shadowmarktris[i] * 3;
559                 // make sure the vertices are created
560                 for (j = 0;j < 3;j++)
561                 {
562                         if (vertexupdate[element[j]] != vertexupdatenum)
563                         {
564                                 float ratio, direction[3];
565                                 vertexupdate[element[j]] = vertexupdatenum;
566                                 vertexremap[element[j]] = outvertices;
567                                 vertex = invertex3f + element[j] * 3;
568                                 // project one copy of the vertex to the sphere radius of the light
569                                 // (FIXME: would projecting it to the light box be better?)
570                                 VectorSubtract(vertex, projectorigin, direction);
571                                 ratio = projectdistance / VectorLength(direction);
572                                 VectorCopy(vertex, outvertex3f);
573                                 VectorMA(projectorigin, ratio, direction, (outvertex3f + 3));
574                                 outvertex3f += 6;
575                                 outvertices += 2;
576                         }
577                 }
578         }
579
580         for (i = 0;i < numshadowmarktris;i++)
581         {
582                 int remappedelement[3];
583                 int markindex;
584                 const int *neighbortriangle;
585
586                 markindex = shadowmarktris[i] * 3;
587                 element = inelement3i + markindex;
588                 neighbortriangle = inneighbor3i + markindex;
589                 // output the front and back triangles
590                 outelement3i[0] = vertexremap[element[0]];
591                 outelement3i[1] = vertexremap[element[1]];
592                 outelement3i[2] = vertexremap[element[2]];
593                 outelement3i[3] = vertexremap[element[2]] + 1;
594                 outelement3i[4] = vertexremap[element[1]] + 1;
595                 outelement3i[5] = vertexremap[element[0]] + 1;
596
597                 outelement3i += 6;
598                 outtriangles += 2;
599                 // output the sides (facing outward from this triangle)
600                 if (shadowmark[neighbortriangle[0]] != shadowmarkcount)
601                 {
602                         remappedelement[0] = vertexremap[element[0]];
603                         remappedelement[1] = vertexremap[element[1]];
604                         outelement3i[0] = remappedelement[1];
605                         outelement3i[1] = remappedelement[0];
606                         outelement3i[2] = remappedelement[0] + 1;
607                         outelement3i[3] = remappedelement[1];
608                         outelement3i[4] = remappedelement[0] + 1;
609                         outelement3i[5] = remappedelement[1] + 1;
610
611                         outelement3i += 6;
612                         outtriangles += 2;
613                 }
614                 if (shadowmark[neighbortriangle[1]] != shadowmarkcount)
615                 {
616                         remappedelement[1] = vertexremap[element[1]];
617                         remappedelement[2] = vertexremap[element[2]];
618                         outelement3i[0] = remappedelement[2];
619                         outelement3i[1] = remappedelement[1];
620                         outelement3i[2] = remappedelement[1] + 1;
621                         outelement3i[3] = remappedelement[2];
622                         outelement3i[4] = remappedelement[1] + 1;
623                         outelement3i[5] = remappedelement[2] + 1;
624
625                         outelement3i += 6;
626                         outtriangles += 2;
627                 }
628                 if (shadowmark[neighbortriangle[2]] != shadowmarkcount)
629                 {
630                         remappedelement[0] = vertexremap[element[0]];
631                         remappedelement[2] = vertexremap[element[2]];
632                         outelement3i[0] = remappedelement[0];
633                         outelement3i[1] = remappedelement[2];
634                         outelement3i[2] = remappedelement[2] + 1;
635                         outelement3i[3] = remappedelement[0];
636                         outelement3i[4] = remappedelement[2] + 1;
637                         outelement3i[5] = remappedelement[0] + 1;
638
639                         outelement3i += 6;
640                         outtriangles += 2;
641                 }
642         }
643         if (outnumvertices)
644                 *outnumvertices = outvertices;
645         return outtriangles;
646 }
647
648 void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, const int *elements, const int *neighbors, const vec3_t projectorigin, float projectdistance, int nummarktris, const int *marktris)
649 {
650         int tris, outverts;
651         if (projectdistance < 0.1)
652         {
653                 Con_Printf("R_Shadow_Volume: projectdistance %f\n");
654                 return;
655         }
656         if (!numverts || !nummarktris)
657                 return;
658         // make sure shadowelements is big enough for this volume
659         if (maxshadowtriangles < nummarktris || maxshadowvertices < numverts)
660                 R_Shadow_ResizeShadowArrays((numverts + 255) & ~255, (nummarktris + 255) & ~255);
661         tris = R_Shadow_ConstructShadowVolume(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdistance, nummarktris, marktris);
662         r_refdef.stats.lights_dynamicshadowtriangles += tris;
663         R_Shadow_RenderVolume(outverts, tris, shadowvertex3f, shadowelements);
664 }
665
666 void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *invertex3f, const int *elements, const vec3_t projectorigin, const vec3_t lightmins, const vec3_t lightmaxs, const vec3_t surfacemins, const vec3_t surfacemaxs)
667 {
668         int t, tend;
669         const int *e;
670         const float *v[3];
671         if (!BoxesOverlap(lightmins, lightmaxs, surfacemins, surfacemaxs))
672                 return;
673         tend = firsttriangle + numtris;
674         if (surfacemins[0] >= lightmins[0] && surfacemaxs[0] <= lightmaxs[0]
675          && surfacemins[1] >= lightmins[1] && surfacemaxs[1] <= lightmaxs[1]
676          && surfacemins[2] >= lightmins[2] && surfacemaxs[2] <= lightmaxs[2])
677         {
678                 // surface box entirely inside light box, no box cull
679                 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
680                         if (PointInfrontOfTriangle(projectorigin, invertex3f + e[0] * 3, invertex3f + e[1] * 3, invertex3f + e[2] * 3))
681                                 shadowmarklist[numshadowmark++] = t;
682         }
683         else
684         {
685                 // surface box not entirely inside light box, cull each triangle
686                 for (t = firsttriangle, e = elements + t * 3;t < tend;t++, e += 3)
687                 {
688                         v[0] = invertex3f + e[0] * 3;
689                         v[1] = invertex3f + e[1] * 3;
690                         v[2] = invertex3f + e[2] * 3;
691                         if (PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2])
692                          && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0]))
693                          && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0]))
694                          && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1]))
695                          && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1]))
696                          && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2]))
697                          && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
698                                 shadowmarklist[numshadowmark++] = t;
699                 }
700         }
701 }
702
703 void R_Shadow_RenderVolume(int numvertices, int numtriangles, const float *vertex3f, const int *element3i)
704 {
705         if (r_shadow_compilingrtlight)
706         {
707                 // if we're compiling an rtlight, capture the mesh
708                 Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, NULL, NULL, NULL, vertex3f, NULL, NULL, NULL, NULL, numtriangles, element3i);
709                 return;
710         }
711         r_refdef.stats.lights_shadowtriangles += numtriangles;
712         CHECKGLERROR
713         R_Mesh_VertexPointer(vertex3f);
714         GL_LockArrays(0, numvertices);
715         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
716         {
717                 // decrement stencil if backface is behind depthbuffer
718                 qglCullFace(GL_BACK);CHECKGLERROR // quake is backwards, this culls front faces
719                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
720                 R_Mesh_Draw(0, numvertices, numtriangles, element3i);
721                 // increment stencil if frontface is behind depthbuffer
722                 qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
723                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
724         }
725         R_Mesh_Draw(0, numvertices, numtriangles, element3i);
726         GL_LockArrays(0, 0);
727         CHECKGLERROR
728 }
729
730 static void R_Shadow_MakeTextures(void)
731 {
732         int x, y, z, d;
733         float v[3], intensity;
734         unsigned char *data;
735         R_FreeTexturePool(&r_shadow_texturepool);
736         r_shadow_texturepool = R_AllocTexturePool();
737         r_shadow_attenpower = r_shadow_lightattenuationpower.value;
738         r_shadow_attenscale = r_shadow_lightattenuationscale.value;
739 #define ATTEN2DSIZE 64
740 #define ATTEN3DSIZE 32
741         data = (unsigned char *)Mem_Alloc(tempmempool, max(ATTEN3DSIZE*ATTEN3DSIZE*ATTEN3DSIZE*4, ATTEN2DSIZE*ATTEN2DSIZE*4));
742         for (y = 0;y < ATTEN2DSIZE;y++)
743         {
744                 for (x = 0;x < ATTEN2DSIZE;x++)
745                 {
746                         v[0] = ((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
747                         v[1] = ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375);
748                         v[2] = 0;
749                         intensity = 1.0f - sqrt(DotProduct(v, v));
750                         if (intensity > 0)
751                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
752                         d = (int)bound(0, intensity, 255);
753                         data[(y*ATTEN2DSIZE+x)*4+0] = d;
754                         data[(y*ATTEN2DSIZE+x)*4+1] = d;
755                         data[(y*ATTEN2DSIZE+x)*4+2] = d;
756                         data[(y*ATTEN2DSIZE+x)*4+3] = d;
757                 }
758         }
759         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
760         if (r_shadow_texture3d.integer && gl_texture3d)
761         {
762                 for (z = 0;z < ATTEN3DSIZE;z++)
763                 {
764                         for (y = 0;y < ATTEN3DSIZE;y++)
765                         {
766                                 for (x = 0;x < ATTEN3DSIZE;x++)
767                                 {
768                                         v[0] = ((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
769                                         v[1] = ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
770                                         v[2] = ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375);
771                                         intensity = 1.0f - sqrt(DotProduct(v, v));
772                                         if (intensity > 0)
773                                                 intensity = pow(intensity, r_shadow_attenpower) * r_shadow_attenscale * 256.0f;
774                                         d = (int)bound(0, intensity, 255);
775                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+0] = d;
776                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+1] = d;
777                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+2] = d;
778                                         data[((z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x)*4+3] = d;
779                                 }
780                         }
781                 }
782                 r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA, NULL);
783         }
784         Mem_Free(data);
785 }
786
787 void R_Shadow_ValidateCvars(void)
788 {
789         if (r_shadow_texture3d.integer && !gl_texture3d)
790                 Cvar_SetValueQuick(&r_shadow_texture3d, 0);
791         if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside)
792                 Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
793 }
794
795 // light currently being rendered
796 rtlight_t *r_shadow_rtlight;
797
798 // this is the location of the light in entity space
799 vec3_t r_shadow_entitylightorigin;
800 // this transforms entity coordinates to light filter cubemap coordinates
801 // (also often used for other purposes)
802 matrix4x4_t r_shadow_entitytolight;
803 // based on entitytolight this transforms -1 to +1 to 0 to 1 for purposes
804 // of attenuation texturing in full 3D (Z result often ignored)
805 matrix4x4_t r_shadow_entitytoattenuationxyz;
806 // this transforms only the Z to S, and T is always 0.5
807 matrix4x4_t r_shadow_entitytoattenuationz;
808
809 void R_Shadow_RenderMode_Begin(void)
810 {
811         R_Shadow_ValidateCvars();
812
813         if (!r_shadow_attenuation2dtexture
814          || (!r_shadow_attenuation3dtexture && r_shadow_texture3d.integer)
815          || r_shadow_lightattenuationpower.value != r_shadow_attenpower
816          || r_shadow_lightattenuationscale.value != r_shadow_attenscale)
817                 R_Shadow_MakeTextures();
818
819         CHECKGLERROR
820         R_Mesh_ColorPointer(NULL);
821         R_Mesh_ResetTextureState();
822         GL_BlendFunc(GL_ONE, GL_ZERO);
823         GL_DepthMask(false);
824         GL_DepthTest(true);
825         GL_Color(0, 0, 0, 1);
826         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
827         qglEnable(GL_CULL_FACE);CHECKGLERROR
828         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
829
830         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
831
832         if (gl_ext_stenciltwoside.integer)
833                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCILTWOSIDE;
834         else
835                 r_shadow_shadowingrendermode = R_SHADOW_RENDERMODE_STENCIL;
836
837         if (r_glsl.integer && gl_support_fragment_shader)
838                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
839         else if (gl_dot3arb && gl_texturecubemap && r_textureunits.integer >= 2 && gl_combine.integer && gl_stencil)
840                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3;
841         else
842                 r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX;
843 }
844
845 void R_Shadow_RenderMode_ActiveLight(rtlight_t *rtlight)
846 {
847         r_shadow_rtlight = rtlight;
848 }
849
850 void R_Shadow_RenderMode_Reset(void)
851 {
852         CHECKGLERROR
853         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
854         {
855                 qglUseProgramObjectARB(0);CHECKGLERROR
856         }
857         else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
858         {
859                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
860         }
861         R_Mesh_ColorPointer(NULL);
862         R_Mesh_ResetTextureState();
863 }
864
865 void R_Shadow_RenderMode_StencilShadowVolumes(void)
866 {
867         CHECKGLERROR
868         R_Shadow_RenderMode_Reset();
869         GL_Color(1, 1, 1, 1);
870         GL_ColorMask(0, 0, 0, 0);
871         GL_BlendFunc(GL_ONE, GL_ZERO);
872         GL_DepthMask(false);
873         GL_DepthTest(true);
874         qglPolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
875         qglDepthFunc(GL_LESS);CHECKGLERROR
876         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
877         qglEnable(GL_STENCIL_TEST);CHECKGLERROR
878         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
879         r_shadow_rendermode = r_shadow_shadowingrendermode;
880         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCILTWOSIDE)
881         {
882                 qglDisable(GL_CULL_FACE);CHECKGLERROR
883                 qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
884                 qglActiveStencilFaceEXT(GL_BACK);CHECKGLERROR // quake is backwards, this is front faces
885                 qglStencilMask(~0);CHECKGLERROR
886                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
887                 qglActiveStencilFaceEXT(GL_FRONT);CHECKGLERROR // quake is backwards, this is back faces
888                 qglStencilMask(~0);CHECKGLERROR
889                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
890         }
891         else
892         {
893                 qglEnable(GL_CULL_FACE);CHECKGLERROR
894                 qglStencilMask(~0);CHECKGLERROR
895                 // this is changed by every shadow render so its value here is unimportant
896                 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
897         }
898         GL_Clear(GL_STENCIL_BUFFER_BIT);
899         r_refdef.stats.lights_clears++;
900 }
901
902 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent)
903 {
904         CHECKGLERROR
905         R_Shadow_RenderMode_Reset();
906         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
907         GL_DepthMask(false);
908         GL_DepthTest(true);
909         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
910         //qglDisable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
911         GL_Color(1, 1, 1, 1);
912         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
913         if (transparent)
914         {
915                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
916         }
917         else
918         {
919                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
920         }
921         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
922         qglEnable(GL_CULL_FACE);CHECKGLERROR
923         if (stenciltest)
924         {
925                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
926         }
927         else
928         {
929                 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
930         }
931         qglStencilMask(~0);CHECKGLERROR
932         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
933         // only draw light where this geometry was already rendered AND the
934         // stencil is 128 (values other than this mean shadow)
935         qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR
936         r_shadow_rendermode = r_shadow_lightingrendermode;
937         // do global setup needed for the chosen lighting mode
938         if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
939         {
940                 R_Mesh_TexBind(0, R_GetTexture(r_texture_blanknormalmap)); // normal
941                 R_Mesh_TexBind(1, R_GetTexture(r_texture_white)); // diffuse
942                 R_Mesh_TexBind(2, R_GetTexture(r_texture_white)); // gloss
943                 R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap)); // light filter
944                 R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation)); // fog
945                 R_Mesh_TexBind(5, R_GetTexture(r_texture_white)); // pants
946                 R_Mesh_TexBind(6, R_GetTexture(r_texture_white)); // shirt
947                 R_Mesh_TexBind(7, R_GetTexture(r_texture_white)); // lightmap
948                 R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap)); // deluxemap
949                 R_Mesh_TexBind(9, R_GetTexture(r_texture_black)); // glow
950                 //R_Mesh_TexMatrix(3, r_shadow_entitytolight); // light filter matrix
951                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
952                 GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 0);
953                 CHECKGLERROR
954         }
955 }
956
957 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
958 {
959         CHECKGLERROR
960         R_Shadow_RenderMode_Reset();
961         GL_BlendFunc(GL_ONE, GL_ONE);
962         GL_DepthMask(false);
963         GL_DepthTest(!r_showdisabledepthtest.integer);
964         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
965         GL_Color(0.0, 0.0125, 0.1, 1);
966         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
967         qglDepthFunc(GL_GEQUAL);CHECKGLERROR
968         qglCullFace(GL_FRONT);CHECKGLERROR // this culls back
969         qglDisable(GL_CULL_FACE);CHECKGLERROR
970         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
971         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES;
972 }
973
974 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
975 {
976         CHECKGLERROR
977         R_Shadow_RenderMode_Reset();
978         GL_BlendFunc(GL_ONE, GL_ONE);
979         GL_DepthMask(false);
980         GL_DepthTest(!r_showdisabledepthtest.integer);
981         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
982         GL_Color(0.1, 0.0125, 0, 1);
983         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
984         if (transparent)
985         {
986                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
987         }
988         else
989         {
990                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
991         }
992         qglCullFace(GL_FRONT);CHECKGLERROR // this culls back
993         qglEnable(GL_CULL_FACE);CHECKGLERROR
994         if (stenciltest)
995         {
996                 qglEnable(GL_STENCIL_TEST);CHECKGLERROR
997         }
998         else
999         {
1000                 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1001         }
1002         r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
1003 }
1004
1005 void R_Shadow_RenderMode_End(void)
1006 {
1007         CHECKGLERROR
1008         R_Shadow_RenderMode_Reset();
1009         R_Shadow_RenderMode_ActiveLight(NULL);
1010         GL_BlendFunc(GL_ONE, GL_ZERO);
1011         GL_DepthMask(true);
1012         GL_DepthTest(true);
1013         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1014         //qglDisable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
1015         GL_Color(1, 1, 1, 1);
1016         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
1017         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1018         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1019         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
1020         qglEnable(GL_CULL_FACE);CHECKGLERROR
1021         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1022         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1023         if (gl_support_stenciltwoside)
1024         {
1025                 qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
1026         }
1027         qglStencilMask(~0);CHECKGLERROR
1028         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1029         r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE;
1030 }
1031
1032 qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
1033 {
1034         int i, ix1, iy1, ix2, iy2;
1035         float x1, y1, x2, y2;
1036         vec4_t v, v2;
1037         rmesh_t mesh;
1038         mplane_t planes[11];
1039         float vertex3f[256*3];
1040
1041         // if view is inside the light box, just say yes it's visible
1042         if (BoxesOverlap(r_view.origin, r_view.origin, mins, maxs))
1043         {
1044                 GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1045                 return false;
1046         }
1047
1048         // create a temporary brush describing the area the light can affect in worldspace
1049         VectorNegate(r_view.frustum[0].normal, planes[ 0].normal);planes[ 0].dist = -r_view.frustum[0].dist;
1050         VectorNegate(r_view.frustum[1].normal, planes[ 1].normal);planes[ 1].dist = -r_view.frustum[1].dist;
1051         VectorNegate(r_view.frustum[2].normal, planes[ 2].normal);planes[ 2].dist = -r_view.frustum[2].dist;
1052         VectorNegate(r_view.frustum[3].normal, planes[ 3].normal);planes[ 3].dist = -r_view.frustum[3].dist;
1053         VectorNegate(r_view.frustum[4].normal, planes[ 4].normal);planes[ 4].dist = -r_view.frustum[4].dist;
1054         VectorSet   (planes[ 5].normal,  1, 0, 0);         planes[ 5].dist =  maxs[0];
1055         VectorSet   (planes[ 6].normal, -1, 0, 0);         planes[ 6].dist = -mins[0];
1056         VectorSet   (planes[ 7].normal, 0,  1, 0);         planes[ 7].dist =  maxs[1];
1057         VectorSet   (planes[ 8].normal, 0, -1, 0);         planes[ 8].dist = -mins[1];
1058         VectorSet   (planes[ 9].normal, 0, 0,  1);         planes[ 9].dist =  maxs[2];
1059         VectorSet   (planes[10].normal, 0, 0, -1);         planes[10].dist = -mins[2];
1060
1061         // turn the brush into a mesh
1062         memset(&mesh, 0, sizeof(rmesh_t));
1063         mesh.maxvertices = 256;
1064         mesh.vertex3f = vertex3f;
1065         mesh.epsilon2 = (1.0f / (32.0f * 32.0f));
1066         R_Mesh_AddBrushMeshFromPlanes(&mesh, 11, planes);
1067
1068         // if that mesh is empty, the light is not visible at all
1069         if (!mesh.numvertices)
1070                 return true;
1071
1072         if (!r_shadow_scissor.integer)
1073                 return false;
1074
1075         // if that mesh is not empty, check what area of the screen it covers
1076         x1 = y1 = x2 = y2 = 0;
1077         v[3] = 1.0f;
1078         for (i = 0;i < mesh.numvertices;i++)
1079         {
1080                 VectorCopy(mesh.vertex3f + i * 3, v);
1081                 GL_TransformToScreen(v, v2);
1082                 //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]);
1083                 if (i)
1084                 {
1085                         if (x1 > v2[0]) x1 = v2[0];
1086                         if (x2 < v2[0]) x2 = v2[0];
1087                         if (y1 > v2[1]) y1 = v2[1];
1088                         if (y2 < v2[1]) y2 = v2[1];
1089                 }
1090                 else
1091                 {
1092                         x1 = x2 = v2[0];
1093                         y1 = y2 = v2[1];
1094                 }
1095         }
1096
1097         // now convert the scissor rectangle to integer screen coordinates
1098         ix1 = (int)(x1 - 1.0f);
1099         iy1 = (int)(y1 - 1.0f);
1100         ix2 = (int)(x2 + 1.0f);
1101         iy2 = (int)(y2 + 1.0f);
1102         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
1103
1104         // clamp it to the screen
1105         if (ix1 < r_view.x) ix1 = r_view.x;
1106         if (iy1 < r_view.y) iy1 = r_view.y;
1107         if (ix2 > r_view.x + r_view.width) ix2 = r_view.x + r_view.width;
1108         if (iy2 > r_view.y + r_view.height) iy2 = r_view.y + r_view.height;
1109
1110         // if it is inside out, it's not visible
1111         if (ix2 <= ix1 || iy2 <= iy1)
1112                 return true;
1113
1114         // the light area is visible, set up the scissor rectangle
1115         GL_Scissor(ix1, vid.height - iy2, ix2 - ix1, iy2 - iy1);
1116         //qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);CHECKGLERROR
1117         //qglEnable(GL_SCISSOR_TEST);CHECKGLERROR
1118         r_refdef.stats.lights_scissored++;
1119         return false;
1120 }
1121
1122 static void R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(const msurface_t *surface, const float *diffusecolor, const float *ambientcolor)
1123 {
1124         int numverts = surface->num_vertices;
1125         float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1126         float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1127         float *color4f = rsurface_array_color4f + 4 * surface->num_firstvertex;
1128         float dist, dot, distintensity, shadeintensity, v[3], n[3];
1129         if (r_textureunits.integer >= 3)
1130         {
1131                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1132                 {
1133                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1134                         Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1135                         if ((dot = DotProduct(n, v)) < 0)
1136                         {
1137                                 shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1138                                 color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]);
1139                                 color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]);
1140                                 color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]);
1141                                 if (r_refdef.fogenabled)
1142                                 {
1143                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1144                                         VectorScale(color4f, f, color4f);
1145                                 }
1146                         }
1147                         else
1148                                 VectorClear(color4f);
1149                         color4f[3] = 1;
1150                 }
1151         }
1152         else if (r_textureunits.integer >= 2)
1153         {
1154                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1155                 {
1156                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1157                         if ((dist = fabs(v[2])) < 1)
1158                         {
1159                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1160                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1161                                 if ((dot = DotProduct(n, v)) < 0)
1162                                 {
1163                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1164                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1165                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1166                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1167                                 }
1168                                 else
1169                                 {
1170                                         color4f[0] = ambientcolor[0] * distintensity;
1171                                         color4f[1] = ambientcolor[1] * distintensity;
1172                                         color4f[2] = ambientcolor[2] * distintensity;
1173                                 }
1174                                 if (r_refdef.fogenabled)
1175                                 {
1176                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1177                                         VectorScale(color4f, f, color4f);
1178                                 }
1179                         }
1180                         else
1181                                 VectorClear(color4f);
1182                         color4f[3] = 1;
1183                 }
1184         }
1185         else
1186         {
1187                 for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4)
1188                 {
1189                         Matrix4x4_Transform(&r_shadow_entitytolight, vertex3f, v);
1190                         if ((dist = DotProduct(v, v)) < 1)
1191                         {
1192                                 dist = sqrt(dist);
1193                                 distintensity = pow(1 - dist, r_shadow_attenpower) * r_shadow_attenscale;
1194                                 Matrix4x4_Transform3x3(&r_shadow_entitytolight, normal3f, n);
1195                                 if ((dot = DotProduct(n, v)) < 0)
1196                                 {
1197                                         shadeintensity = -dot / sqrt(VectorLength2(v) * VectorLength2(n));
1198                                         color4f[0] = (ambientcolor[0] + shadeintensity * diffusecolor[0]) * distintensity;
1199                                         color4f[1] = (ambientcolor[1] + shadeintensity * diffusecolor[1]) * distintensity;
1200                                         color4f[2] = (ambientcolor[2] + shadeintensity * diffusecolor[2]) * distintensity;
1201                                 }
1202                                 else
1203                                 {
1204                                         color4f[0] = ambientcolor[0] * distintensity;
1205                                         color4f[1] = ambientcolor[1] * distintensity;
1206                                         color4f[2] = ambientcolor[2] * distintensity;
1207                                 }
1208                                 if (r_refdef.fogenabled)
1209                                 {
1210                                         float f = VERTEXFOGTABLE(VectorDistance(v, rsurface_modelorg));
1211                                         VectorScale(color4f, f, color4f);
1212                                 }
1213                         }
1214                         else
1215                                 VectorClear(color4f);
1216                         color4f[3] = 1;
1217                 }
1218         }
1219 }
1220
1221 // TODO: use glTexGen instead of feeding vertices to texcoordpointer?
1222
1223 static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int numsurfaces, msurface_t **surfacelist)
1224 {
1225         int surfacelistindex;
1226         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1227         {
1228                 const msurface_t *surface = surfacelist[surfacelistindex];
1229                 int i;
1230                 float *out3f = rsurface_array_texcoord3f + 3 * surface->num_firstvertex;
1231                 const float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1232                 const float *svector3f = rsurface_svector3f + 3 * surface->num_firstvertex;
1233                 const float *tvector3f = rsurface_tvector3f + 3 * surface->num_firstvertex;
1234                 const float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1235                 float lightdir[3];
1236                 for (i = 0;i < surface->num_vertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1237                 {
1238                         VectorSubtract(r_shadow_entitylightorigin, vertex3f, lightdir);
1239                         // the cubemap normalizes this for us
1240                         out3f[0] = DotProduct(svector3f, lightdir);
1241                         out3f[1] = DotProduct(tvector3f, lightdir);
1242                         out3f[2] = DotProduct(normal3f, lightdir);
1243                 }
1244         }
1245 }
1246
1247 static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int numsurfaces, msurface_t **surfacelist)
1248 {
1249         int surfacelistindex;
1250         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1251         {
1252                 const msurface_t *surface = surfacelist[surfacelistindex];
1253                 int i;
1254                 float *out3f = rsurface_array_texcoord3f + 3 * surface->num_firstvertex;
1255                 const float *vertex3f = rsurface_vertex3f + 3 * surface->num_firstvertex;
1256                 const float *svector3f = rsurface_svector3f + 3 * surface->num_firstvertex;
1257                 const float *tvector3f = rsurface_tvector3f + 3 * surface->num_firstvertex;
1258                 const float *normal3f = rsurface_normal3f + 3 * surface->num_firstvertex;
1259                 float lightdir[3], eyedir[3], halfdir[3];
1260                 for (i = 0;i < surface->num_vertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3)
1261                 {
1262                         VectorSubtract(r_shadow_entitylightorigin, vertex3f, lightdir);
1263                         VectorNormalize(lightdir);
1264                         VectorSubtract(rsurface_modelorg, vertex3f, eyedir);
1265                         VectorNormalize(eyedir);
1266                         VectorAdd(lightdir, eyedir, halfdir);
1267                         // the cubemap normalizes this for us
1268                         out3f[0] = DotProduct(svector3f, halfdir);
1269                         out3f[1] = DotProduct(tvector3f, halfdir);
1270                         out3f[2] = DotProduct(normal3f, halfdir);
1271                 }
1272         }
1273 }
1274
1275 static void R_Shadow_RenderSurfacesLighting_VisibleLighting(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1276 {
1277         // used to display how many times a surface is lit for level design purposes
1278         GL_Color(0.1, 0.025, 0, 1);
1279         R_Mesh_ColorPointer(NULL);
1280         R_Mesh_ResetTextureState();
1281         RSurf_PrepareVerticesForBatch(false, false, numsurfaces, surfacelist);
1282         RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1283         GL_LockArrays(0, 0);
1284 }
1285
1286 static void R_Shadow_RenderSurfacesLighting_Light_GLSL(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1287 {
1288         // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
1289         RSurf_PrepareVerticesForBatch(true, true, numsurfaces, surfacelist);
1290         R_SetupSurfaceShader(lightcolorbase, false);
1291         R_Mesh_TexCoordPointer(0, 2, rsurface_model->surfmesh.data_texcoordtexture2f);
1292         R_Mesh_TexCoordPointer(1, 3, rsurface_svector3f);
1293         R_Mesh_TexCoordPointer(2, 3, rsurface_tvector3f);
1294         R_Mesh_TexCoordPointer(3, 3, rsurface_normal3f);
1295         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
1296         {
1297                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
1298         }
1299         RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1300         GL_LockArrays(0, 0);
1301         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
1302         {
1303                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1304         }
1305 }
1306
1307 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(int numsurfaces, msurface_t **surfacelist, float r, float g, float b)
1308 {
1309         // shared final code for all the dot3 layers
1310         int renders;
1311         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 0);
1312         for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--)
1313         {
1314                 GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1);
1315                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1316                 GL_LockArrays(0, 0);
1317         }
1318 }
1319
1320 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale)
1321 {
1322         rmeshstate_t m;
1323         // colorscale accounts for how much we multiply the brightness
1324         // during combine.
1325         //
1326         // mult is how many times the final pass of the lighting will be
1327         // performed to get more brightness than otherwise possible.
1328         //
1329         // Limit mult to 64 for sanity sake.
1330         GL_Color(1,1,1,1);
1331         if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4)
1332         {
1333                 // 3 3D combine path (Geforce3, Radeon 8500)
1334                 memset(&m, 0, sizeof(m));
1335                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1336                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1337                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1338                 m.tex[1] = R_GetTexture(basetexture);
1339                 m.pointer_texcoord[1] = rsurface_model->surfmesh.data_texcoordtexture2f;
1340                 m.texmatrix[1] = rsurface_texture->currenttexmatrix;
1341                 m.texcubemap[2] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1342                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1343                 m.texmatrix[2] = r_shadow_entitytolight;
1344                 GL_BlendFunc(GL_ONE, GL_ONE);
1345         }
1346         else if (r_shadow_texture3d.integer && r_shadow_rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2)
1347         {
1348                 // 2 3D combine path (Geforce3, original Radeon)
1349                 memset(&m, 0, sizeof(m));
1350                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1351                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1352                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1353                 m.tex[1] = R_GetTexture(basetexture);
1354                 m.pointer_texcoord[1] = rsurface_model->surfmesh.data_texcoordtexture2f;
1355                 m.texmatrix[1] = rsurface_texture->currenttexmatrix;
1356                 GL_BlendFunc(GL_ONE, GL_ONE);
1357         }
1358         else if (r_textureunits.integer >= 4 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1359         {
1360                 // 4 2D combine path (Geforce3, Radeon 8500)
1361                 memset(&m, 0, sizeof(m));
1362                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1363                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1364                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1365                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1366                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1367                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1368                 m.tex[2] = R_GetTexture(basetexture);
1369                 m.pointer_texcoord[2] = rsurface_model->surfmesh.data_texcoordtexture2f;
1370                 m.texmatrix[2] = rsurface_texture->currenttexmatrix;
1371                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1372                 {
1373                         m.texcubemap[3] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1374                         m.pointer_texcoord3f[3] = rsurface_vertex3f;
1375                         m.texmatrix[3] = r_shadow_entitytolight;
1376                 }
1377                 GL_BlendFunc(GL_ONE, GL_ONE);
1378         }
1379         else if (r_textureunits.integer >= 3 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1380         {
1381                 // 3 2D combine path (Geforce3, original Radeon)
1382                 memset(&m, 0, sizeof(m));
1383                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1384                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1385                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1386                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1387                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1388                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1389                 m.tex[2] = R_GetTexture(basetexture);
1390                 m.pointer_texcoord[2] = rsurface_model->surfmesh.data_texcoordtexture2f;
1391                 m.texmatrix[2] = rsurface_texture->currenttexmatrix;
1392                 GL_BlendFunc(GL_ONE, GL_ONE);
1393         }
1394         else
1395         {
1396                 // 2/2/2 2D combine path (any dot3 card)
1397                 memset(&m, 0, sizeof(m));
1398                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1399                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1400                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1401                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1402                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1403                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1404                 R_Mesh_TextureState(&m);
1405                 GL_ColorMask(0,0,0,1);
1406                 GL_BlendFunc(GL_ONE, GL_ZERO);
1407                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1408                 GL_LockArrays(0, 0);
1409
1410                 // second pass
1411                 memset(&m, 0, sizeof(m));
1412                 m.tex[0] = R_GetTexture(basetexture);
1413                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1414                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1415                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1416                 {
1417                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1418                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1419                         m.texmatrix[1] = r_shadow_entitytolight;
1420                 }
1421                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1422         }
1423         // this final code is shared
1424         R_Mesh_TextureState(&m);
1425         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1426 }
1427
1428 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale)
1429 {
1430         rmeshstate_t m;
1431         // colorscale accounts for how much we multiply the brightness
1432         // during combine.
1433         //
1434         // mult is how many times the final pass of the lighting will be
1435         // performed to get more brightness than otherwise possible.
1436         //
1437         // Limit mult to 64 for sanity sake.
1438         GL_Color(1,1,1,1);
1439         // generate normalization cubemap texcoords
1440         R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(numsurfaces, surfacelist);
1441         if (r_shadow_texture3d.integer && r_textureunits.integer >= 4)
1442         {
1443                 // 3/2 3D combine path (Geforce3, Radeon 8500)
1444                 memset(&m, 0, sizeof(m));
1445                 m.tex[0] = R_GetTexture(normalmaptexture);
1446                 m.texcombinergb[0] = GL_REPLACE;
1447                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1448                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1449                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1450                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1451                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1452                 m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture);
1453                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1454                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1455                 R_Mesh_TextureState(&m);
1456                 GL_ColorMask(0,0,0,1);
1457                 GL_BlendFunc(GL_ONE, GL_ZERO);
1458                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1459                 GL_LockArrays(0, 0);
1460
1461                 // second pass
1462                 memset(&m, 0, sizeof(m));
1463                 m.tex[0] = R_GetTexture(basetexture);
1464                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1465                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1466                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1467                 {
1468                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1469                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1470                         m.texmatrix[1] = r_shadow_entitytolight;
1471                 }
1472                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1473         }
1474         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1475         {
1476                 // 1/2/2 3D combine path (original Radeon)
1477                 memset(&m, 0, sizeof(m));
1478                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1479                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1480                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1481                 R_Mesh_TextureState(&m);
1482                 GL_ColorMask(0,0,0,1);
1483                 GL_BlendFunc(GL_ONE, GL_ZERO);
1484                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1485                 GL_LockArrays(0, 0);
1486
1487                 // second pass
1488                 memset(&m, 0, sizeof(m));
1489                 m.tex[0] = R_GetTexture(normalmaptexture);
1490                 m.texcombinergb[0] = GL_REPLACE;
1491                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1492                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1493                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1494                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1495                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1496                 R_Mesh_TextureState(&m);
1497                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1498                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1499                 GL_LockArrays(0, 0);
1500
1501                 // second pass
1502                 memset(&m, 0, sizeof(m));
1503                 m.tex[0] = R_GetTexture(basetexture);
1504                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1505                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1506                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1507                 {
1508                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1509                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1510                         m.texmatrix[1] = r_shadow_entitytolight;
1511                 }
1512                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1513         }
1514         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube)
1515         {
1516                 // 2/2 3D combine path (original Radeon)
1517                 memset(&m, 0, sizeof(m));
1518                 m.tex[0] = R_GetTexture(normalmaptexture);
1519                 m.texcombinergb[0] = GL_REPLACE;
1520                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1521                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1522                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1523                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1524                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1525                 R_Mesh_TextureState(&m);
1526                 GL_ColorMask(0,0,0,1);
1527                 GL_BlendFunc(GL_ONE, GL_ZERO);
1528                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1529                 GL_LockArrays(0, 0);
1530
1531                 // second pass
1532                 memset(&m, 0, sizeof(m));
1533                 m.tex[0] = R_GetTexture(basetexture);
1534                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1535                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1536                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1537                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1538                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1539                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1540         }
1541         else if (r_textureunits.integer >= 4)
1542         {
1543                 // 4/2 2D combine path (Geforce3, Radeon 8500)
1544                 memset(&m, 0, sizeof(m));
1545                 m.tex[0] = R_GetTexture(normalmaptexture);
1546                 m.texcombinergb[0] = GL_REPLACE;
1547                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1548                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1549                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1550                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1551                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1552                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1553                 m.pointer_texcoord3f[2] = rsurface_vertex3f;
1554                 m.texmatrix[2] = r_shadow_entitytoattenuationxyz;
1555                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
1556                 m.pointer_texcoord3f[3] = rsurface_vertex3f;
1557                 m.texmatrix[3] = r_shadow_entitytoattenuationz;
1558                 R_Mesh_TextureState(&m);
1559                 GL_ColorMask(0,0,0,1);
1560                 GL_BlendFunc(GL_ONE, GL_ZERO);
1561                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1562                 GL_LockArrays(0, 0);
1563
1564                 // second pass
1565                 memset(&m, 0, sizeof(m));
1566                 m.tex[0] = R_GetTexture(basetexture);
1567                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1568                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1569                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1570                 {
1571                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1572                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1573                         m.texmatrix[1] = r_shadow_entitytolight;
1574                 }
1575                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1576         }
1577         else
1578         {
1579                 // 2/2/2 2D combine path (any dot3 card)
1580                 memset(&m, 0, sizeof(m));
1581                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1582                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1583                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1584                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1585                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1586                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1587                 R_Mesh_TextureState(&m);
1588                 GL_ColorMask(0,0,0,1);
1589                 GL_BlendFunc(GL_ONE, GL_ZERO);
1590                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1591                 GL_LockArrays(0, 0);
1592
1593                 // second pass
1594                 memset(&m, 0, sizeof(m));
1595                 m.tex[0] = R_GetTexture(normalmaptexture);
1596                 m.texcombinergb[0] = GL_REPLACE;
1597                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1598                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1599                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1600                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1601                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1602                 R_Mesh_TextureState(&m);
1603                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1604                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1605                 GL_LockArrays(0, 0);
1606
1607                 // second pass
1608                 memset(&m, 0, sizeof(m));
1609                 m.tex[0] = R_GetTexture(basetexture);
1610                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1611                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1612                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1613                 {
1614                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1615                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1616                         m.texmatrix[1] = r_shadow_entitytolight;
1617                 }
1618                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1619         }
1620         // this final code is shared
1621         R_Mesh_TextureState(&m);
1622         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1623 }
1624
1625 static void R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale)
1626 {
1627         rmeshstate_t m;
1628         // FIXME: detect blendsquare!
1629         //if (!gl_support_blendsquare)
1630         //      return;
1631         GL_Color(1,1,1,1);
1632         // generate normalization cubemap texcoords
1633         R_Shadow_GenTexCoords_Specular_NormalCubeMap(numsurfaces, surfacelist);
1634         if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1635         {
1636                 // 2/0/0/1/2 3D combine blendsquare path
1637                 memset(&m, 0, sizeof(m));
1638                 m.tex[0] = R_GetTexture(normalmaptexture);
1639                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1640                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1641                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1642                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1643                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1644                 R_Mesh_TextureState(&m);
1645                 GL_ColorMask(0,0,0,1);
1646                 // this squares the result
1647                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1648                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1649                 GL_LockArrays(0, 0);
1650
1651                 // second and third pass
1652                 R_Mesh_ResetTextureState();
1653                 // square alpha in framebuffer a few times to make it shiny
1654                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1655                 // these comments are a test run through this math for intensity 0.5
1656                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1657                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1658                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1659                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1660                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1661                 GL_LockArrays(0, 0);
1662
1663                 // fourth pass
1664                 memset(&m, 0, sizeof(m));
1665                 m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture);
1666                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1667                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1668                 R_Mesh_TextureState(&m);
1669                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1670                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1671                 GL_LockArrays(0, 0);
1672
1673                 // fifth pass
1674                 memset(&m, 0, sizeof(m));
1675                 m.tex[0] = R_GetTexture(glosstexture);
1676                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1677                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1678                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1679                 {
1680                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1681                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1682                         m.texmatrix[1] = r_shadow_entitytolight;
1683                 }
1684                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1685         }
1686         else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && r_shadow_rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare!
1687         {
1688                 // 2/0/0/2 3D combine blendsquare path
1689                 memset(&m, 0, sizeof(m));
1690                 m.tex[0] = R_GetTexture(normalmaptexture);
1691                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1692                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1693                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1694                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1695                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1696                 R_Mesh_TextureState(&m);
1697                 GL_ColorMask(0,0,0,1);
1698                 // this squares the result
1699                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1700                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1701                 GL_LockArrays(0, 0);
1702
1703                 // second and third pass
1704                 R_Mesh_ResetTextureState();
1705                 // square alpha in framebuffer a few times to make it shiny
1706                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1707                 // these comments are a test run through this math for intensity 0.5
1708                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1709                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1710                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1711                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1712                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1713                 GL_LockArrays(0, 0);
1714
1715                 // fourth pass
1716                 memset(&m, 0, sizeof(m));
1717                 m.tex[0] = R_GetTexture(glosstexture);
1718                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1719                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1720                 m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture);
1721                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1722                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1723                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1724         }
1725         else
1726         {
1727                 // 2/0/0/2/2 2D combine blendsquare path
1728                 memset(&m, 0, sizeof(m));
1729                 m.tex[0] = R_GetTexture(normalmaptexture);
1730                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1731                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1732                 m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube);
1733                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
1734                 m.pointer_texcoord3f[1] = rsurface_array_texcoord3f;
1735                 R_Mesh_TextureState(&m);
1736                 GL_ColorMask(0,0,0,1);
1737                 // this squares the result
1738                 GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO);
1739                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1740                 GL_LockArrays(0, 0);
1741
1742                 // second and third pass
1743                 R_Mesh_ResetTextureState();
1744                 // square alpha in framebuffer a few times to make it shiny
1745                 GL_BlendFunc(GL_ZERO, GL_DST_ALPHA);
1746                 // these comments are a test run through this math for intensity 0.5
1747                 // 0.5 * 0.5 = 0.25 (done by the BlendFunc earlier)
1748                 // 0.25 * 0.25 = 0.0625 (this is another pass)
1749                 // 0.0625 * 0.0625 = 0.00390625 (this is another pass)
1750                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1751                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1752                 GL_LockArrays(0, 0);
1753
1754                 // fourth pass
1755                 memset(&m, 0, sizeof(m));
1756                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
1757                 m.pointer_texcoord3f[0] = rsurface_vertex3f;
1758                 m.texmatrix[0] = r_shadow_entitytoattenuationxyz;
1759                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1760                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1761                 m.texmatrix[1] = r_shadow_entitytoattenuationz;
1762                 R_Mesh_TextureState(&m);
1763                 GL_BlendFunc(GL_DST_ALPHA, GL_ZERO);
1764                 RSurf_DrawBatch_Simple(numsurfaces, surfacelist);
1765                 GL_LockArrays(0, 0);
1766
1767                 // fifth pass
1768                 memset(&m, 0, sizeof(m));
1769                 m.tex[0] = R_GetTexture(glosstexture);
1770                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1771                 m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1772                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
1773                 {
1774                         m.texcubemap[1] = R_GetTexture(r_shadow_rtlight->currentcubemap);
1775                         m.pointer_texcoord3f[1] = rsurface_vertex3f;
1776                         m.texmatrix[1] = r_shadow_entitytolight;
1777                 }
1778                 GL_BlendFunc(GL_DST_ALPHA, GL_ONE);
1779         }
1780         // this final code is shared
1781         R_Mesh_TextureState(&m);
1782         R_Shadow_RenderSurfacesLighting_Light_Dot3_Finalize(numsurfaces, surfacelist, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale);
1783 }
1784
1785 static void R_Shadow_RenderSurfacesLighting_Light_Dot3(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1786 {
1787         // ARB path (any Geforce, any Radeon)
1788         qboolean doambient = r_shadow_rtlight->ambientscale > 0;
1789         qboolean dodiffuse = r_shadow_rtlight->diffusescale > 0;
1790         qboolean dospecular = specularscale > 0;
1791         if (!doambient && !dodiffuse && !dospecular)
1792                 return;
1793         RSurf_PrepareVerticesForBatch(true, true, numsurfaces, surfacelist);
1794         R_Mesh_ColorPointer(NULL);
1795         if (doambient)
1796                 R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorbase, basetexture, r_shadow_rtlight->ambientscale);
1797         if (dodiffuse)
1798                 R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorbase, basetexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1799         if (dopants)
1800         {
1801                 if (doambient)
1802                         R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorpants, pantstexture, r_shadow_rtlight->ambientscale);
1803                 if (dodiffuse)
1804                         R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorpants, pantstexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1805         }
1806         if (doshirt)
1807         {
1808                 if (doambient)
1809                         R_Shadow_RenderSurfacesLighting_Light_Dot3_AmbientPass(numsurfaces, surfacelist, lightcolorshirt, shirttexture, r_shadow_rtlight->ambientscale);
1810                 if (dodiffuse)
1811                         R_Shadow_RenderSurfacesLighting_Light_Dot3_DiffusePass(numsurfaces, surfacelist, lightcolorshirt, shirttexture, normalmaptexture, r_shadow_rtlight->diffusescale);
1812         }
1813         if (dospecular)
1814                 R_Shadow_RenderSurfacesLighting_Light_Dot3_SpecularPass(numsurfaces, surfacelist, lightcolorbase, glosstexture, normalmaptexture, specularscale);
1815 }
1816
1817 void R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(const model_t *model, int numsurfaces, msurface_t **surfacelist, vec3_t diffusecolor2, vec3_t ambientcolor2)
1818 {
1819         int surfacelistindex;
1820         int renders;
1821         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1822         {
1823                 const msurface_t *surface = surfacelist[surfacelistindex];
1824                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Shading(surface, diffusecolor2, ambientcolor2);
1825         }
1826         for (renders = 0;renders < 64;renders++)
1827         {
1828                 const int *e;
1829                 int stop;
1830                 int firstvertex;
1831                 int lastvertex;
1832                 int newnumtriangles;
1833                 int *newe;
1834                 int newelements[3072];
1835                 stop = true;
1836                 firstvertex = 0;
1837                 lastvertex = 0;
1838                 newnumtriangles = 0;
1839                 newe = newelements;
1840                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1841                 {
1842                         const msurface_t *surface = surfacelist[surfacelistindex];
1843                         const int *elements = rsurface_model->surfmesh.data_element3i + surface->num_firsttriangle * 3;
1844                         int i;
1845                         // due to low fillrate on the cards this vertex lighting path is
1846                         // designed for, we manually cull all triangles that do not
1847                         // contain a lit vertex
1848                         // this builds batches of triangles from multiple surfaces and
1849                         // renders them at once
1850                         for (i = 0, e = elements;i < surface->num_triangles;i++, e += 3)
1851                         {
1852                                 if (VectorLength2(rsurface_array_color4f + e[0] * 4) + VectorLength2(rsurface_array_color4f + e[1] * 4) + VectorLength2(rsurface_array_color4f + e[2] * 4) >= 0.01)
1853                                 {
1854                                         if (newnumtriangles)
1855                                         {
1856                                                 firstvertex = min(firstvertex, e[0]);
1857                                                 lastvertex = max(lastvertex, e[0]);
1858                                         }
1859                                         else
1860                                         {
1861                                                 firstvertex = e[0];
1862                                                 lastvertex = e[0];
1863                                         }
1864                                         firstvertex = min(firstvertex, e[1]);
1865                                         lastvertex = max(lastvertex, e[1]);
1866                                         firstvertex = min(firstvertex, e[2]);
1867                                         lastvertex = max(lastvertex, e[2]);
1868                                         newe[0] = e[0];
1869                                         newe[1] = e[1];
1870                                         newe[2] = e[2];
1871                                         newnumtriangles++;
1872                                         newe += 3;
1873                                         if (newnumtriangles >= 1024)
1874                                         {
1875                                                 GL_LockArrays(firstvertex, lastvertex - firstvertex + 1);
1876                                                 R_Mesh_Draw(firstvertex, lastvertex - firstvertex + 1, newnumtriangles, newelements);
1877                                                 newnumtriangles = 0;
1878                                                 newe = newelements;
1879                                                 stop = false;
1880                                         }
1881                                 }
1882                         }
1883                 }
1884                 if (newnumtriangles >= 1)
1885                 {
1886                         GL_LockArrays(firstvertex, lastvertex - firstvertex + 1);
1887                         R_Mesh_Draw(firstvertex, lastvertex - firstvertex + 1, newnumtriangles, newelements);
1888                         stop = false;
1889                 }
1890                 GL_LockArrays(0, 0);
1891                 // if we couldn't find any lit triangles, exit early
1892                 if (stop)
1893                         break;
1894                 // now reduce the intensity for the next overbright pass
1895                 // we have to clamp to 0 here incase the drivers have improper
1896                 // handling of negative colors
1897                 // (some old drivers even have improper handling of >1 color)
1898                 stop = true;
1899                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1900                 {
1901                         int i;
1902                         float *c;
1903                         const msurface_t *surface = surfacelist[surfacelistindex];
1904                         for (i = 0, c = rsurface_array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
1905                         {
1906                                 if (c[0] > 1 || c[1] > 1 || c[2] > 1)
1907                                 {
1908                                         c[0] = max(0, c[0] - 1);
1909                                         c[1] = max(0, c[1] - 1);
1910                                         c[2] = max(0, c[2] - 1);
1911                                         stop = false;
1912                                 }
1913                                 else
1914                                         VectorClear(c);
1915                         }
1916                 }
1917                 // another check...
1918                 if (stop)
1919                         break;
1920         }
1921 }
1922
1923 static void R_Shadow_RenderSurfacesLighting_Light_Vertex(int numsurfaces, msurface_t **surfacelist, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float specularscale, qboolean dopants, qboolean doshirt)
1924 {
1925         // OpenGL 1.1 path (anything)
1926         model_t *model = rsurface_entity->model;
1927         float ambientcolorbase[3], diffusecolorbase[3];
1928         float ambientcolorpants[3], diffusecolorpants[3];
1929         float ambientcolorshirt[3], diffusecolorshirt[3];
1930         rmeshstate_t m;
1931         VectorScale(lightcolorbase, r_shadow_rtlight->ambientscale * 2, ambientcolorbase);
1932         VectorScale(lightcolorbase, r_shadow_rtlight->diffusescale * 2, diffusecolorbase);
1933         VectorScale(lightcolorpants, r_shadow_rtlight->ambientscale * 2, ambientcolorpants);
1934         VectorScale(lightcolorpants, r_shadow_rtlight->diffusescale * 2, diffusecolorpants);
1935         VectorScale(lightcolorshirt, r_shadow_rtlight->ambientscale * 2, ambientcolorshirt);
1936         VectorScale(lightcolorshirt, r_shadow_rtlight->diffusescale * 2, diffusecolorshirt);
1937         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
1938         R_Mesh_ColorPointer(rsurface_array_color4f);
1939         memset(&m, 0, sizeof(m));
1940         m.tex[0] = R_GetTexture(basetexture);
1941         m.texmatrix[0] = rsurface_texture->currenttexmatrix;
1942         m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
1943         if (r_textureunits.integer >= 2)
1944         {
1945                 // voodoo2 or TNT
1946                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
1947                 m.texmatrix[1] = r_shadow_entitytoattenuationxyz;
1948                 m.pointer_texcoord3f[1] = rsurface_vertex3f;
1949                 if (r_textureunits.integer >= 3)
1950                 {
1951                         // Voodoo4 or Kyro (or Geforce3/Radeon with gl_combine off)
1952                         m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
1953                         m.texmatrix[2] = r_shadow_entitytoattenuationz;
1954                         m.pointer_texcoord3f[2] = rsurface_vertex3f;
1955                 }
1956         }
1957         R_Mesh_TextureState(&m);
1958         RSurf_PrepareVerticesForBatch(true, false, numsurfaces, surfacelist);
1959         R_Mesh_TexBind(0, R_GetTexture(basetexture));
1960         R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorbase, ambientcolorbase);
1961         if (dopants)
1962         {
1963                 R_Mesh_TexBind(0, R_GetTexture(pantstexture));
1964                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorpants, ambientcolorpants);
1965         }
1966         if (doshirt)
1967         {
1968                 R_Mesh_TexBind(0, R_GetTexture(shirttexture));
1969                 R_Shadow_RenderSurfacesLighting_Light_Vertex_Pass(model, numsurfaces, surfacelist, diffusecolorshirt, ambientcolorshirt);
1970         }
1971 }
1972
1973 void R_Shadow_RenderSurfacesLighting(int numsurfaces, msurface_t **surfacelist)
1974 {
1975         // FIXME: support MATERIALFLAG_NODEPTHTEST
1976         vec3_t lightcolorbase, lightcolorpants, lightcolorshirt;
1977         // calculate colors to render this texture with
1978         lightcolorbase[0] = r_shadow_rtlight->currentcolor[0] * rsurface_entity->colormod[0] * rsurface_texture->currentalpha;
1979         lightcolorbase[1] = r_shadow_rtlight->currentcolor[1] * rsurface_entity->colormod[1] * rsurface_texture->currentalpha;
1980         lightcolorbase[2] = r_shadow_rtlight->currentcolor[2] * rsurface_entity->colormod[2] * rsurface_texture->currentalpha;
1981         if ((r_shadow_rtlight->ambientscale + r_shadow_rtlight->diffusescale) * VectorLength2(lightcolorbase) + (r_shadow_rtlight->specularscale * rsurface_texture->specularscale) * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f))
1982                 return;
1983         if ((rsurface_texture->textureflags & Q3TEXTUREFLAG_TWOSIDED) || (rsurface_entity->flags & RENDER_NOCULLFACE))
1984         {
1985                 qglDisable(GL_CULL_FACE);CHECKGLERROR
1986         }
1987         else
1988         {
1989                 qglEnable(GL_CULL_FACE);CHECKGLERROR
1990         }
1991         if (rsurface_texture->colormapping)
1992         {
1993                 qboolean dopants = rsurface_texture->skin.pants != NULL && VectorLength2(rsurface_entity->colormap_pantscolor) >= (1.0f / 1048576.0f);
1994                 qboolean doshirt = rsurface_texture->skin.shirt != NULL && VectorLength2(rsurface_entity->colormap_shirtcolor) >= (1.0f / 1048576.0f);
1995                 if (dopants)
1996                 {
1997                         lightcolorpants[0] = lightcolorbase[0] * rsurface_entity->colormap_pantscolor[0];
1998                         lightcolorpants[1] = lightcolorbase[1] * rsurface_entity->colormap_pantscolor[1];
1999                         lightcolorpants[2] = lightcolorbase[2] * rsurface_entity->colormap_pantscolor[2];
2000                 }
2001                 else
2002                         VectorClear(lightcolorpants);
2003                 if (doshirt)
2004                 {
2005                         lightcolorshirt[0] = lightcolorbase[0] * rsurface_entity->colormap_shirtcolor[0];
2006                         lightcolorshirt[1] = lightcolorbase[1] * rsurface_entity->colormap_shirtcolor[1];
2007                         lightcolorshirt[2] = lightcolorbase[2] * rsurface_entity->colormap_shirtcolor[2];
2008                 }
2009                 else
2010                         VectorClear(lightcolorshirt);
2011                 switch (r_shadow_rendermode)
2012                 {
2013                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2014                         R_Shadow_RenderSurfacesLighting_VisibleLighting(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2015                         break;
2016                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2017                         R_Shadow_RenderSurfacesLighting_Light_GLSL(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2018                         break;
2019                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2020                         R_Shadow_RenderSurfacesLighting_Light_Dot3(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2021                         break;
2022                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2023                         R_Shadow_RenderSurfacesLighting_Light_Vertex(numsurfaces, surfacelist, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface_texture->basetexture, rsurface_texture->skin.pants, rsurface_texture->skin.shirt, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, dopants, doshirt);
2024                         break;
2025                 default:
2026                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2027                         break;
2028                 }
2029         }
2030         else
2031         {
2032                 switch (r_shadow_rendermode)
2033                 {
2034                 case R_SHADOW_RENDERMODE_VISIBLELIGHTING:
2035                         R_Shadow_RenderSurfacesLighting_VisibleLighting(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2036                         break;
2037                 case R_SHADOW_RENDERMODE_LIGHT_GLSL:
2038                         R_Shadow_RenderSurfacesLighting_Light_GLSL(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2039                         break;
2040                 case R_SHADOW_RENDERMODE_LIGHT_DOT3:
2041                         R_Shadow_RenderSurfacesLighting_Light_Dot3(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2042                         break;
2043                 case R_SHADOW_RENDERMODE_LIGHT_VERTEX:
2044                         R_Shadow_RenderSurfacesLighting_Light_Vertex(numsurfaces, surfacelist, lightcolorbase, vec3_origin, vec3_origin, rsurface_texture->basetexture, r_texture_black, r_texture_black, rsurface_texture->skin.nmap, rsurface_texture->glosstexture, r_shadow_rtlight->specularscale * rsurface_texture->specularscale, false, false);
2045                         break;
2046                 default:
2047                         Con_Printf("R_Shadow_RenderSurfacesLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode);
2048                         break;
2049                 }
2050         }
2051 }
2052
2053 void R_RTLight_Update(dlight_t *light, int isstatic)
2054 {
2055         int j, k;
2056         float scale;
2057         rtlight_t *rtlight = &light->rtlight;
2058         R_RTLight_Uncompile(rtlight);
2059         memset(rtlight, 0, sizeof(*rtlight));
2060
2061         VectorCopy(light->origin, rtlight->shadoworigin);
2062         VectorCopy(light->color, rtlight->color);
2063         rtlight->radius = light->radius;
2064         //rtlight->cullradius = rtlight->radius;
2065         //rtlight->cullradius2 = rtlight->radius * rtlight->radius;
2066         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2067         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2068         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2069         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2070         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2071         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2072         rtlight->cubemapname[0] = 0;
2073         if (light->cubemapname[0])
2074                 strcpy(rtlight->cubemapname, light->cubemapname);
2075         else if (light->cubemapnum > 0)
2076                 sprintf(rtlight->cubemapname, "cubemaps/%i", light->cubemapnum);
2077         rtlight->shadow = light->shadow;
2078         rtlight->corona = light->corona;
2079         rtlight->style = light->style;
2080         rtlight->isstatic = isstatic;
2081         rtlight->coronasizescale = light->coronasizescale;
2082         rtlight->ambientscale = light->ambientscale;
2083         rtlight->diffusescale = light->diffusescale;
2084         rtlight->specularscale = light->specularscale;
2085         rtlight->flags = light->flags;
2086         Matrix4x4_Invert_Simple(&rtlight->matrix_worldtolight, &light->matrix);
2087         // ConcatScale won't work here because this needs to scale rotate and
2088         // translate, not just rotate
2089         scale = 1.0f / rtlight->radius;
2090         for (k = 0;k < 3;k++)
2091                 for (j = 0;j < 4;j++)
2092                         rtlight->matrix_worldtolight.m[k][j] *= scale;
2093 }
2094
2095 // compiles rtlight geometry
2096 // (undone by R_FreeCompiledRTLight, which R_UpdateLight calls)
2097 void R_RTLight_Compile(rtlight_t *rtlight)
2098 {
2099         int shadowmeshes, shadowtris, numleafs, numleafpvsbytes, numsurfaces;
2100         entity_render_t *ent = r_refdef.worldentity;
2101         model_t *model = r_refdef.worldmodel;
2102         unsigned char *data;
2103
2104         // compile the light
2105         rtlight->compiled = true;
2106         rtlight->static_numleafs = 0;
2107         rtlight->static_numleafpvsbytes = 0;
2108         rtlight->static_leaflist = NULL;
2109         rtlight->static_leafpvs = NULL;
2110         rtlight->static_numsurfaces = 0;
2111         rtlight->static_surfacelist = NULL;
2112         rtlight->cullmins[0] = rtlight->shadoworigin[0] - rtlight->radius;
2113         rtlight->cullmins[1] = rtlight->shadoworigin[1] - rtlight->radius;
2114         rtlight->cullmins[2] = rtlight->shadoworigin[2] - rtlight->radius;
2115         rtlight->cullmaxs[0] = rtlight->shadoworigin[0] + rtlight->radius;
2116         rtlight->cullmaxs[1] = rtlight->shadoworigin[1] + rtlight->radius;
2117         rtlight->cullmaxs[2] = rtlight->shadoworigin[2] + rtlight->radius;
2118
2119         if (model && model->GetLightInfo)
2120         {
2121                 // this variable must be set for the CompileShadowVolume code
2122                 r_shadow_compilingrtlight = rtlight;
2123                 R_Shadow_EnlargeLeafSurfaceBuffer(model->brush.num_leafs, model->num_surfaces);
2124                 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);
2125                 numleafpvsbytes = (model->brush.num_leafs + 7) >> 3;
2126                 data = (unsigned char *)Mem_Alloc(r_main_mempool, sizeof(int) * numleafs + numleafpvsbytes + sizeof(int) * numsurfaces);
2127                 rtlight->static_numleafs = numleafs;
2128                 rtlight->static_numleafpvsbytes = numleafpvsbytes;
2129                 rtlight->static_leaflist = (int *)data;data += sizeof(int) * numleafs;
2130                 rtlight->static_leafpvs = (unsigned char *)data;data += numleafpvsbytes;
2131                 rtlight->static_numsurfaces = numsurfaces;
2132                 rtlight->static_surfacelist = (int *)data;data += sizeof(int) * numsurfaces;
2133                 if (numleafs)
2134                         memcpy(rtlight->static_leaflist, r_shadow_buffer_leaflist, rtlight->static_numleafs * sizeof(*rtlight->static_leaflist));
2135                 if (numleafpvsbytes)
2136                         memcpy(rtlight->static_leafpvs, r_shadow_buffer_leafpvs, rtlight->static_numleafpvsbytes);
2137                 if (numsurfaces)
2138                         memcpy(rtlight->static_surfacelist, r_shadow_buffer_surfacelist, rtlight->static_numsurfaces * sizeof(*rtlight->static_surfacelist));
2139                 if (model->CompileShadowVolume && rtlight->shadow)
2140                         model->CompileShadowVolume(ent, rtlight->shadoworigin, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist);
2141                 // now we're done compiling the rtlight
2142                 r_shadow_compilingrtlight = NULL;
2143         }
2144
2145
2146         // use smallest available cullradius - box radius or light radius
2147         //rtlight->cullradius = RadiusFromBoundsAndOrigin(rtlight->cullmins, rtlight->cullmaxs, rtlight->shadoworigin);
2148         //rtlight->cullradius = min(rtlight->cullradius, rtlight->radius);
2149
2150         shadowmeshes = 0;
2151         shadowtris = 0;
2152         if (rtlight->static_meshchain_shadow)
2153         {
2154                 shadowmesh_t *mesh;
2155                 for (mesh = rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2156                 {
2157                         shadowmeshes++;
2158                         shadowtris += mesh->numtriangles;
2159                 }
2160         }
2161
2162         if (developer.integer >= 10)
2163                 Con_Printf("static light built: %f %f %f : %f %f %f box, %i shadow volume triangles (in %i meshes)\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], shadowtris, shadowmeshes);
2164 }
2165
2166 void R_RTLight_Uncompile(rtlight_t *rtlight)
2167 {
2168         if (rtlight->compiled)
2169         {
2170                 if (rtlight->static_meshchain_shadow)
2171                         Mod_ShadowMesh_Free(rtlight->static_meshchain_shadow);
2172                 rtlight->static_meshchain_shadow = NULL;
2173                 // these allocations are grouped
2174                 if (rtlight->static_leaflist)
2175                         Mem_Free(rtlight->static_leaflist);
2176                 rtlight->static_numleafs = 0;
2177                 rtlight->static_numleafpvsbytes = 0;
2178                 rtlight->static_leaflist = NULL;
2179                 rtlight->static_leafpvs = NULL;
2180                 rtlight->static_numsurfaces = 0;
2181                 rtlight->static_surfacelist = NULL;
2182                 rtlight->compiled = false;
2183         }
2184 }
2185
2186 void R_Shadow_UncompileWorldLights(void)
2187 {
2188         dlight_t *light;
2189         for (light = r_shadow_worldlightchain;light;light = light->next)
2190                 R_RTLight_Uncompile(&light->rtlight);
2191 }
2192
2193 void R_Shadow_DrawEntityShadow(entity_render_t *ent, int numsurfaces, int *surfacelist)
2194 {
2195         model_t *model = ent->model;
2196         vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs;
2197         vec_t relativeshadowradius;
2198         if (ent == r_refdef.worldentity)
2199         {
2200                 if (r_shadow_rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer)
2201                 {
2202                         shadowmesh_t *mesh;
2203                         R_Mesh_Matrix(&ent->matrix);
2204                         CHECKGLERROR
2205                         for (mesh = r_shadow_rtlight->static_meshchain_shadow;mesh;mesh = mesh->next)
2206                         {
2207                                 r_refdef.stats.lights_shadowtriangles += mesh->numtriangles;
2208                                 R_Mesh_VertexPointer(mesh->vertex3f);
2209                                 GL_LockArrays(0, mesh->numverts);
2210                                 if (r_shadow_rendermode == R_SHADOW_RENDERMODE_STENCIL)
2211                                 {
2212                                         // decrement stencil if backface is behind depthbuffer
2213                                         qglCullFace(GL_BACK);CHECKGLERROR // quake is backwards, this culls front faces
2214                                         qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
2215                                         R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2216                                         // increment stencil if frontface is behind depthbuffer
2217                                         qglCullFace(GL_FRONT);CHECKGLERROR // quake is backwards, this culls back faces
2218                                         qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
2219                                 }
2220                                 R_Mesh_Draw(0, mesh->numverts, mesh->numtriangles, mesh->element3i);
2221                                 GL_LockArrays(0, 0);
2222                         }
2223                         CHECKGLERROR
2224                 }
2225                 else if (numsurfaces)
2226                 {
2227                         R_Mesh_Matrix(&ent->matrix);
2228                         model->DrawShadowVolume(ent, r_shadow_rtlight->shadoworigin, r_shadow_rtlight->radius, numsurfaces, surfacelist, r_shadow_rtlight->cullmins, r_shadow_rtlight->cullmaxs);
2229                 }
2230         }
2231         else
2232         {
2233                 Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, relativeshadoworigin);
2234                 relativeshadowradius = r_shadow_rtlight->radius / ent->scale;
2235                 relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius;
2236                 relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius;
2237                 relativeshadowmins[2] = relativeshadoworigin[2] - relativeshadowradius;
2238                 relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius;
2239                 relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius;
2240                 relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius;
2241                 R_Mesh_Matrix(&ent->matrix);
2242                 model->DrawShadowVolume(ent, relativeshadoworigin, relativeshadowradius, model->nummodelsurfaces, model->surfacelist, relativeshadowmins, relativeshadowmaxs);
2243         }
2244 }
2245
2246 void R_Shadow_SetupEntityLight(const entity_render_t *ent)
2247 {
2248         // set up properties for rendering light onto this entity
2249         RSurf_ActiveEntity(ent, true, true);
2250         Matrix4x4_Concat(&r_shadow_entitytolight, &r_shadow_rtlight->matrix_worldtolight, &ent->matrix);
2251         Matrix4x4_Concat(&r_shadow_entitytoattenuationxyz, &matrix_attenuationxyz, &r_shadow_entitytolight);
2252         Matrix4x4_Concat(&r_shadow_entitytoattenuationz, &matrix_attenuationz, &r_shadow_entitytolight);
2253         Matrix4x4_Transform(&ent->inversematrix, r_shadow_rtlight->shadoworigin, r_shadow_entitylightorigin);
2254         if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
2255                 R_Mesh_TexMatrix(3, &r_shadow_entitytolight);
2256 }
2257
2258 void R_Shadow_DrawEntityLight(entity_render_t *ent, int numsurfaces, int *surfacelist)
2259 {
2260         model_t *model = ent->model;
2261         if (!model->DrawLight)
2262                 return;
2263         R_Shadow_SetupEntityLight(ent);
2264         if (ent == r_refdef.worldentity)
2265                 model->DrawLight(ent, numsurfaces, surfacelist);
2266         else
2267                 model->DrawLight(ent, model->nummodelsurfaces, model->surfacelist);
2268 }
2269
2270 void R_DrawRTLight(rtlight_t *rtlight, qboolean visible)
2271 {
2272         int i, usestencil;
2273         float f;
2274         int numleafs, numsurfaces;
2275         int *leaflist, *surfacelist;
2276         unsigned char *leafpvs;
2277         int numlightentities;
2278         int numshadowentities;
2279         entity_render_t *lightentities[MAX_EDICTS];
2280         entity_render_t *shadowentities[MAX_EDICTS];
2281
2282         // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights)
2283         // skip lights that are basically invisible (color 0 0 0)
2284         if (VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f))
2285                 return;
2286
2287         // loading is done before visibility checks because loading should happen
2288         // all at once at the start of a level, not when it stalls gameplay.
2289         // (especially important to benchmarks)
2290         // compile light
2291         if (rtlight->isstatic && !rtlight->compiled && r_shadow_realtime_world_compile.integer)
2292                 R_RTLight_Compile(rtlight);
2293         // load cubemap
2294         rtlight->currentcubemap = rtlight->cubemapname[0] ? R_Shadow_Cubemap(rtlight->cubemapname) : r_texture_whitecube;
2295
2296         // look up the light style value at this time
2297         f = (rtlight->style >= 0 ? r_refdef.lightstylevalue[rtlight->style] : 128) * (1.0f / 256.0f) * r_shadow_lightintensityscale.value;
2298         VectorScale(rtlight->color, f, rtlight->currentcolor);
2299         /*
2300         if (rtlight->selected)
2301         {
2302                 f = 2 + sin(realtime * M_PI * 4.0);
2303                 VectorScale(rtlight->currentcolor, f, rtlight->currentcolor);
2304         }
2305         */
2306
2307         // if lightstyle is currently off, don't draw the light
2308         if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f))
2309                 return;
2310
2311         // if the light box is offscreen, skip it
2312         if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2313                 return;
2314
2315         if (rtlight->compiled && r_shadow_realtime_world_compile.integer)
2316         {
2317                 // compiled light, world available and can receive realtime lighting
2318                 // retrieve leaf information
2319                 numleafs = rtlight->static_numleafs;
2320                 leaflist = rtlight->static_leaflist;
2321                 leafpvs = rtlight->static_leafpvs;
2322                 numsurfaces = rtlight->static_numsurfaces;
2323                 surfacelist = rtlight->static_surfacelist;
2324         }
2325         else if (r_refdef.worldmodel && r_refdef.worldmodel->GetLightInfo)
2326         {
2327                 // dynamic light, world available and can receive realtime lighting
2328                 // calculate lit surfaces and leafs
2329                 R_Shadow_EnlargeLeafSurfaceBuffer(r_refdef.worldmodel->brush.num_leafs, r_refdef.worldmodel->num_surfaces);
2330                 r_refdef.worldmodel->GetLightInfo(r_refdef.worldentity, 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);
2331                 leaflist = r_shadow_buffer_leaflist;
2332                 leafpvs = r_shadow_buffer_leafpvs;
2333                 surfacelist = r_shadow_buffer_surfacelist;
2334                 // if the reduced leaf bounds are offscreen, skip it
2335                 if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs))
2336                         return;
2337         }
2338         else
2339         {
2340                 // no world
2341                 numleafs = 0;
2342                 leaflist = NULL;
2343                 leafpvs = NULL;
2344                 numsurfaces = 0;
2345                 surfacelist = NULL;
2346         }
2347         // check if light is illuminating any visible leafs
2348         if (numleafs)
2349         {
2350                 for (i = 0;i < numleafs;i++)
2351                         if (r_viewcache.world_leafvisible[leaflist[i]])
2352                                 break;
2353                 if (i == numleafs)
2354                         return;
2355         }
2356         // set up a scissor rectangle for this light
2357         if (R_Shadow_ScissorForBBox(rtlight->cullmins, rtlight->cullmaxs))
2358                 return;
2359
2360         // make a list of lit entities and shadow casting entities
2361         numlightentities = 0;
2362         numshadowentities = 0;
2363         // don't count the world unless some surfaces are actually lit
2364         if (numsurfaces)
2365         {
2366                 lightentities[numlightentities++] = r_refdef.worldentity;
2367                 shadowentities[numshadowentities++] = r_refdef.worldentity;
2368         }
2369         // add dynamic entities that are lit by the light
2370         if (r_drawentities.integer)
2371         {
2372                 for (i = 0;i < r_refdef.numentities;i++)
2373                 {
2374                         model_t *model;
2375                         entity_render_t *ent = r_refdef.entities[i];
2376                         if (BoxesOverlap(ent->mins, ent->maxs, rtlight->cullmins, rtlight->cullmaxs)
2377                          && (model = ent->model)
2378                          && !(ent->flags & RENDER_TRANSPARENT)
2379                          && (r_refdef.worldmodel == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS == NULL || r_refdef.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.worldmodel, leafpvs, ent->mins, ent->maxs)))
2380                         {
2381                                 // about the VectorDistance2 - light emitting entities should not cast their own shadow
2382                                 if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(ent->origin, rtlight->shadoworigin) > 0.1)
2383                                         shadowentities[numshadowentities++] = ent;
2384                                 if (r_viewcache.entityvisible[i] && (ent->flags & RENDER_LIGHT) && model->DrawLight)
2385                                         lightentities[numlightentities++] = ent;
2386                         }
2387                 }
2388         }
2389
2390         // return if there's nothing at all to light
2391         if (!numlightentities)
2392                 return;
2393
2394         // don't let sound skip if going slow
2395         if (r_refdef.extraupdate)
2396                 S_ExtraUpdate ();
2397
2398         // make this the active rtlight for rendering purposes
2399         R_Shadow_RenderMode_ActiveLight(rtlight);
2400         // count this light in the r_speeds
2401         r_refdef.stats.lights++;
2402
2403         usestencil = false;
2404         if (numshadowentities && rtlight->shadow && (rtlight->isstatic ? r_refdef.rtworldshadows : r_refdef.rtdlightshadows))
2405         {
2406                 // draw stencil shadow volumes to mask off pixels that are in shadow
2407                 // so that they won't receive lighting
2408                 if (gl_stencil)
2409                 {
2410                         usestencil = true;
2411                         R_Shadow_RenderMode_StencilShadowVolumes();
2412                         for (i = 0;i < numshadowentities;i++)
2413                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2414                 }
2415
2416                 // optionally draw visible shape of the shadow volumes
2417                 // for performance analysis by level designers
2418                 if (r_showshadowvolumes.integer)
2419                 {
2420                         R_Shadow_RenderMode_VisibleShadowVolumes();
2421                         for (i = 0;i < numshadowentities;i++)
2422                                 R_Shadow_DrawEntityShadow(shadowentities[i], numsurfaces, surfacelist);
2423                 }
2424         }
2425
2426         if (numlightentities)
2427         {
2428                 // draw lighting in the unmasked areas
2429                 R_Shadow_RenderMode_Lighting(usestencil, false);
2430                 for (i = 0;i < numlightentities;i++)
2431                         R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2432
2433                 // optionally draw the illuminated areas
2434                 // for performance analysis by level designers
2435                 if (r_showlighting.integer)
2436                 {
2437                         R_Shadow_RenderMode_VisibleLighting(usestencil && !r_showdisabledepthtest.integer, false);
2438                         for (i = 0;i < numlightentities;i++)
2439                                 R_Shadow_DrawEntityLight(lightentities[i], numsurfaces, surfacelist);
2440                 }
2441         }
2442 }
2443
2444 void R_ShadowVolumeLighting(qboolean visible)
2445 {
2446         int lnum, flag;
2447         dlight_t *light;
2448
2449         if (r_refdef.worldmodel && strncmp(r_refdef.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname)))
2450                 R_Shadow_EditLights_Reload_f();
2451
2452         R_Shadow_RenderMode_Begin();
2453
2454         flag = r_refdef.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE;
2455         if (r_shadow_debuglight.integer >= 0)
2456         {
2457                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2458                         if (lnum == r_shadow_debuglight.integer && (light->flags & flag))
2459                                 R_DrawRTLight(&light->rtlight, visible);
2460         }
2461         else
2462                 for (lnum = 0, light = r_shadow_worldlightchain;light;lnum++, light = light->next)
2463                         if (light->flags & flag)
2464                                 R_DrawRTLight(&light->rtlight, visible);
2465         if (r_refdef.rtdlight)
2466                 for (lnum = 0;lnum < r_refdef.numlights;lnum++)
2467                         R_DrawRTLight(&r_refdef.lights[lnum]->rtlight, visible);
2468
2469         R_Shadow_RenderMode_End();
2470 }
2471
2472 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
2473 typedef struct suffixinfo_s
2474 {
2475         char *suffix;
2476         qboolean flipx, flipy, flipdiagonal;
2477 }
2478 suffixinfo_t;
2479 static suffixinfo_t suffix[3][6] =
2480 {
2481         {
2482                 {"px",   false, false, false},
2483                 {"nx",   false, false, false},
2484                 {"py",   false, false, false},
2485                 {"ny",   false, false, false},
2486                 {"pz",   false, false, false},
2487                 {"nz",   false, false, false}
2488         },
2489         {
2490                 {"posx", false, false, false},
2491                 {"negx", false, false, false},
2492                 {"posy", false, false, false},
2493                 {"negy", false, false, false},
2494                 {"posz", false, false, false},
2495                 {"negz", false, false, false}
2496         },
2497         {
2498                 {"rt",    true, false,  true},
2499                 {"lf",   false,  true,  true},
2500                 {"ft",    true,  true, false},
2501                 {"bk",   false, false, false},
2502                 {"up",    true, false,  true},
2503                 {"dn",    true, false,  true}
2504         }
2505 };
2506
2507 static int componentorder[4] = {0, 1, 2, 3};
2508
2509 rtexture_t *R_Shadow_LoadCubemap(const char *basename)
2510 {
2511         int i, j, cubemapsize;
2512         unsigned char *cubemappixels, *image_rgba;
2513         rtexture_t *cubemaptexture;
2514         char name[256];
2515         // must start 0 so the first loadimagepixels has no requested width/height
2516         cubemapsize = 0;
2517         cubemappixels = NULL;
2518         cubemaptexture = NULL;
2519         // keep trying different suffix groups (posx, px, rt) until one loads
2520         for (j = 0;j < 3 && !cubemappixels;j++)
2521         {
2522                 // load the 6 images in the suffix group
2523                 for (i = 0;i < 6;i++)
2524                 {
2525                         // generate an image name based on the base and and suffix
2526                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
2527                         // load it
2528                         if ((image_rgba = loadimagepixels(name, false, cubemapsize, cubemapsize)))
2529                         {
2530                                 // an image loaded, make sure width and height are equal
2531                                 if (image_width == image_height)
2532                                 {
2533                                         // if this is the first image to load successfully, allocate the cubemap memory
2534                                         if (!cubemappixels && image_width >= 1)
2535                                         {
2536                                                 cubemapsize = image_width;
2537                                                 // note this clears to black, so unavailable sides are black
2538                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
2539                                         }
2540                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
2541                                         if (cubemappixels)
2542                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_rgba, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
2543                                 }
2544                                 else
2545                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
2546                                 // free the image
2547                                 Mem_Free(image_rgba);
2548                         }
2549                 }
2550         }
2551         // if a cubemap loaded, upload it
2552         if (cubemappixels)
2553         {
2554                 if (!r_shadow_filters_texturepool)
2555                         r_shadow_filters_texturepool = R_AllocTexturePool();
2556                 cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
2557                 Mem_Free(cubemappixels);
2558         }
2559         else
2560         {
2561                 Con_Printf("Failed to load Cubemap \"%s\", tried ", basename);
2562                 for (j = 0;j < 3;j++)
2563                         for (i = 0;i < 6;i++)
2564                                 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
2565                 Con_Print(" and was unable to find any of them.\n");
2566         }
2567         return cubemaptexture;
2568 }
2569
2570 rtexture_t *R_Shadow_Cubemap(const char *basename)
2571 {
2572         int i;
2573         for (i = 0;i < numcubemaps;i++)
2574                 if (!strcasecmp(cubemaps[i].basename, basename))
2575                         return cubemaps[i].texture;
2576         if (i >= MAX_CUBEMAPS)
2577                 return r_texture_whitecube;
2578         numcubemaps++;
2579         strcpy(cubemaps[i].basename, basename);
2580         cubemaps[i].texture = R_Shadow_LoadCubemap(cubemaps[i].basename);
2581         if (!cubemaps[i].texture)
2582                 cubemaps[i].texture = r_texture_whitecube;
2583         return cubemaps[i].texture;
2584 }
2585
2586 void R_Shadow_FreeCubemaps(void)
2587 {
2588         numcubemaps = 0;
2589         R_FreeTexturePool(&r_shadow_filters_texturepool);
2590 }
2591
2592 dlight_t *R_Shadow_NewWorldLight(void)
2593 {
2594         dlight_t *light;
2595         light = (dlight_t *)Mem_Alloc(r_main_mempool, sizeof(dlight_t));
2596         light->next = r_shadow_worldlightchain;
2597         r_shadow_worldlightchain = light;
2598         return light;
2599 }
2600
2601 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)
2602 {
2603         VectorCopy(origin, light->origin);
2604         light->angles[0] = angles[0] - 360 * floor(angles[0] / 360);
2605         light->angles[1] = angles[1] - 360 * floor(angles[1] / 360);
2606         light->angles[2] = angles[2] - 360 * floor(angles[2] / 360);
2607         light->color[0] = max(color[0], 0);
2608         light->color[1] = max(color[1], 0);
2609         light->color[2] = max(color[2], 0);
2610         light->radius = max(radius, 0);
2611         light->style = style;
2612         if (light->style < 0 || light->style >= MAX_LIGHTSTYLES)
2613         {
2614                 Con_Printf("R_Shadow_NewWorldLight: invalid light style number %i, must be >= 0 and < %i\n", light->style, MAX_LIGHTSTYLES);
2615                 light->style = 0;
2616         }
2617         light->shadow = shadowenable;
2618         light->corona = corona;
2619         if (!cubemapname)
2620                 cubemapname = "";
2621         strlcpy(light->cubemapname, cubemapname, sizeof(light->cubemapname));
2622         light->coronasizescale = coronasizescale;
2623         light->ambientscale = ambientscale;
2624         light->diffusescale = diffusescale;
2625         light->specularscale = specularscale;
2626         light->flags = flags;
2627         Matrix4x4_CreateFromQuakeEntity(&light->matrix, light->origin[0], light->origin[1], light->origin[2], light->angles[0], light->angles[1], light->angles[2], 1);
2628
2629         R_RTLight_Update(light, true);
2630 }
2631
2632 void R_Shadow_FreeWorldLight(dlight_t *light)
2633 {
2634         dlight_t **lightpointer;
2635         R_RTLight_Uncompile(&light->rtlight);
2636         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
2637         if (*lightpointer != light)
2638                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain");
2639         *lightpointer = light->next;
2640         Mem_Free(light);
2641 }
2642
2643 void R_Shadow_ClearWorldLights(void)
2644 {
2645         while (r_shadow_worldlightchain)
2646                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
2647         r_shadow_selectedlight = NULL;
2648         R_Shadow_FreeCubemaps();
2649 }
2650
2651 void R_Shadow_SelectLight(dlight_t *light)
2652 {
2653         if (r_shadow_selectedlight)
2654                 r_shadow_selectedlight->selected = false;
2655         r_shadow_selectedlight = light;
2656         if (r_shadow_selectedlight)
2657                 r_shadow_selectedlight->selected = true;
2658 }
2659
2660 void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2661 {
2662         // this is never batched (there can be only one)
2663         float scale = r_editlights_cursorgrid.value * 0.5f;
2664         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[1]->tex, NULL, false, r_editlights_cursorlocation, r_view.right, r_view.up, scale, -scale, -scale, scale, 1, 1, 1, 0.5f);
2665 }
2666
2667 void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2668 {
2669         // this is never batched (due to the ent parameter changing every time)
2670         // so numsurfaces == 1 and surfacelist[0] == lightnumber
2671         float intensity;
2672         const dlight_t *light = (dlight_t *)ent;
2673         intensity = 0.5;
2674         if (light->selected)
2675                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
2676         if (!light->shadow)
2677                 intensity *= 0.5f;
2678         R_DrawSprite(GL_SRC_ALPHA, GL_ONE, r_crosshairs[surfacelist[0]]->tex, NULL, false, light->origin, r_view.right, r_view.up, 8, -8, -8, 8, intensity, intensity, intensity, 0.5);
2679 }
2680
2681 void R_Shadow_DrawLightSprites(void)
2682 {
2683         int i;
2684         dlight_t *light;
2685
2686         for (i = 0, light = r_shadow_worldlightchain;light;i++, light = light->next)
2687                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 1+(i % 5), &light->rtlight);
2688         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL);
2689 }
2690
2691 void R_Shadow_SelectLightInView(void)
2692 {
2693         float bestrating, rating, temp[3];
2694         dlight_t *best, *light;
2695         best = NULL;
2696         bestrating = 0;
2697         for (light = r_shadow_worldlightchain;light;light = light->next)
2698         {
2699                 VectorSubtract(light->origin, r_view.origin, temp);
2700                 rating = (DotProduct(temp, r_view.forward) / sqrt(DotProduct(temp, temp)));
2701                 if (rating >= 0.95)
2702                 {
2703                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
2704                         if (bestrating < rating && CL_TraceBox(light->origin, vec3_origin, vec3_origin, r_view.origin, true, NULL, SUPERCONTENTS_SOLID, false).fraction == 1.0f)
2705                         {
2706                                 bestrating = rating;
2707                                 best = light;
2708                         }
2709                 }
2710         }
2711         R_Shadow_SelectLight(best);
2712 }
2713
2714 void R_Shadow_LoadWorldLights(void)
2715 {
2716         int n, a, style, shadow, flags;
2717         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH], cubemapname[MAX_QPATH];
2718         float origin[3], radius, color[3], angles[3], corona, coronasizescale, ambientscale, diffusescale, specularscale;
2719         if (r_refdef.worldmodel == NULL)
2720         {
2721                 Con_Print("No map loaded.\n");
2722                 return;
2723         }
2724         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2725         strlcat (name, ".rtlights", sizeof (name));
2726         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2727         if (lightsstring)
2728         {
2729                 s = lightsstring;
2730                 n = 0;
2731                 while (*s)
2732                 {
2733                         t = s;
2734                         /*
2735                         shadow = true;
2736                         for (;COM_Parse(t, true) && strcmp(
2737                         if (COM_Parse(t, true))
2738                         {
2739                                 if (com_token[0] == '!')
2740                                 {
2741                                         shadow = false;
2742                                         origin[0] = atof(com_token+1);
2743                                 }
2744                                 else
2745                                         origin[0] = atof(com_token);
2746                                 if (Com_Parse(t
2747                         }
2748                         */
2749                         t = s;
2750                         while (*s && *s != '\n' && *s != '\r')
2751                                 s++;
2752                         if (!*s)
2753                                 break;
2754                         tempchar = *s;
2755                         shadow = true;
2756                         // check for modifier flags
2757                         if (*t == '!')
2758                         {
2759                                 shadow = false;
2760                                 t++;
2761                         }
2762                         *s = 0;
2763                         a = sscanf(t, "%f %f %f %f %f %f %f %d %s %f %f %f %f %f %f %f %f %i", &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);
2764                         *s = tempchar;
2765                         if (a < 18)
2766                                 flags = LIGHTFLAG_REALTIMEMODE;
2767                         if (a < 17)
2768                                 specularscale = 1;
2769                         if (a < 16)
2770                                 diffusescale = 1;
2771                         if (a < 15)
2772                                 ambientscale = 0;
2773                         if (a < 14)
2774                                 coronasizescale = 0.25f;
2775                         if (a < 13)
2776                                 VectorClear(angles);
2777                         if (a < 10)
2778                                 corona = 0;
2779                         if (a < 9 || !strcmp(cubemapname, "\"\""))
2780                                 cubemapname[0] = 0;
2781                         // remove quotes on cubemapname
2782                         if (cubemapname[0] == '"' && cubemapname[strlen(cubemapname) - 1] == '"')
2783                         {
2784                                 cubemapname[strlen(cubemapname)-1] = 0;
2785                                 strcpy(cubemapname, cubemapname + 1);
2786                         }
2787                         if (a < 8)
2788                         {
2789                                 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);
2790                                 break;
2791                         }
2792                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, corona, style, shadow, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
2793                         if (*s == '\r')
2794                                 s++;
2795                         if (*s == '\n')
2796                                 s++;
2797                         n++;
2798                 }
2799                 if (*s)
2800                         Con_Printf("invalid rtlights file \"%s\"\n", name);
2801                 Mem_Free(lightsstring);
2802         }
2803 }
2804
2805 void R_Shadow_SaveWorldLights(void)
2806 {
2807         dlight_t *light;
2808         size_t bufchars, bufmaxchars;
2809         char *buf, *oldbuf;
2810         char name[MAX_QPATH];
2811         char line[MAX_INPUTLINE];
2812         if (!r_shadow_worldlightchain)
2813                 return;
2814         if (r_refdef.worldmodel == NULL)
2815         {
2816                 Con_Print("No map loaded.\n");
2817                 return;
2818         }
2819         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2820         strlcat (name, ".rtlights", sizeof (name));
2821         bufchars = bufmaxchars = 0;
2822         buf = NULL;
2823         for (light = r_shadow_worldlightchain;light;light = light->next)
2824         {
2825                 if (light->coronasizescale != 0.25f || light->ambientscale != 0 || light->diffusescale != 1 || light->specularscale != 1 || light->flags != LIGHTFLAG_REALTIMEMODE)
2826                         sprintf(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);
2827                 else if (light->cubemapname[0] || light->corona || light->angles[0] || light->angles[1] || light->angles[2])
2828                         sprintf(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]);
2829                 else
2830                         sprintf(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);
2831                 if (bufchars + strlen(line) > bufmaxchars)
2832                 {
2833                         bufmaxchars = bufchars + strlen(line) + 2048;
2834                         oldbuf = buf;
2835                         buf = (char *)Mem_Alloc(tempmempool, bufmaxchars);
2836                         if (oldbuf)
2837                         {
2838                                 if (bufchars)
2839                                         memcpy(buf, oldbuf, bufchars);
2840                                 Mem_Free(oldbuf);
2841                         }
2842                 }
2843                 if (strlen(line))
2844                 {
2845                         memcpy(buf + bufchars, line, strlen(line));
2846                         bufchars += strlen(line);
2847                 }
2848         }
2849         if (bufchars)
2850                 FS_WriteFile(name, buf, (fs_offset_t)bufchars);
2851         if (buf)
2852                 Mem_Free(buf);
2853 }
2854
2855 void R_Shadow_LoadLightsFile(void)
2856 {
2857         int n, a, style;
2858         char tempchar, *lightsstring, *s, *t, name[MAX_QPATH];
2859         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
2860         if (r_refdef.worldmodel == NULL)
2861         {
2862                 Con_Print("No map loaded.\n");
2863                 return;
2864         }
2865         FS_StripExtension (r_refdef.worldmodel->name, name, sizeof (name));
2866         strlcat (name, ".lights", sizeof (name));
2867         lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL);
2868         if (lightsstring)
2869         {
2870                 s = lightsstring;
2871                 n = 0;
2872                 while (*s)
2873                 {
2874                         t = s;
2875                         while (*s && *s != '\n' && *s != '\r')
2876                                 s++;
2877                         if (!*s)
2878                                 break;
2879                         tempchar = *s;
2880                         *s = 0;
2881                         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);
2882                         *s = tempchar;
2883                         if (a < 14)
2884                         {
2885                                 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);
2886                                 break;
2887                         }
2888                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
2889                         radius = bound(15, radius, 4096);
2890                         VectorScale(color, (2.0f / (8388608.0f)), color);
2891                         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, vec3_origin, color, radius, 0, style, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
2892                         if (*s == '\r')
2893                                 s++;
2894                         if (*s == '\n')
2895                                 s++;
2896                         n++;
2897                 }
2898                 if (*s)
2899                         Con_Printf("invalid lights file \"%s\"\n", name);
2900                 Mem_Free(lightsstring);
2901         }
2902 }
2903
2904 // tyrlite/hmap2 light types in the delay field
2905 typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, LIGHTTYPE_NONE, LIGHTTYPE_SUN, LIGHTTYPE_MINUSXX} lighttype_t;
2906
2907 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
2908 {
2909         int entnum, style, islight, skin, pflags, effects, type, n;
2910         char *entfiledata;
2911         const char *data;
2912         float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4];
2913         char key[256], value[MAX_INPUTLINE];
2914
2915         if (r_refdef.worldmodel == NULL)
2916         {
2917                 Con_Print("No map loaded.\n");
2918                 return;
2919         }
2920         // try to load a .ent file first
2921         FS_StripExtension (r_refdef.worldmodel->name, key, sizeof (key));
2922         strlcat (key, ".ent", sizeof (key));
2923         data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL);
2924         // and if that is not found, fall back to the bsp file entity string
2925         if (!data)
2926                 data = r_refdef.worldmodel->brush.entities;
2927         if (!data)
2928                 return;
2929         for (entnum = 0;COM_ParseToken(&data, false) && com_token[0] == '{';entnum++)
2930         {
2931                 type = LIGHTTYPE_MINUSX;
2932                 origin[0] = origin[1] = origin[2] = 0;
2933                 originhack[0] = originhack[1] = originhack[2] = 0;
2934                 angles[0] = angles[1] = angles[2] = 0;
2935                 color[0] = color[1] = color[2] = 1;
2936                 light[0] = light[1] = light[2] = 1;light[3] = 300;
2937                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
2938                 fadescale = 1;
2939                 lightscale = 1;
2940                 style = 0;
2941                 skin = 0;
2942                 pflags = 0;
2943                 effects = 0;
2944                 islight = false;
2945                 while (1)
2946                 {
2947                         if (!COM_ParseToken(&data, false))
2948                                 break; // error
2949                         if (com_token[0] == '}')
2950                                 break; // end of entity
2951                         if (com_token[0] == '_')
2952                                 strcpy(key, com_token + 1);
2953                         else
2954                                 strcpy(key, com_token);
2955                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
2956                                 key[strlen(key)-1] = 0;
2957                         if (!COM_ParseToken(&data, false))
2958                                 break; // error
2959                         strcpy(value, com_token);
2960
2961                         // now that we have the key pair worked out...
2962                         if (!strcmp("light", key))
2963                         {
2964                                 n = sscanf(value, "%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]);
2965                                 if (n == 1)
2966                                 {
2967                                         // quake
2968                                         light[0] = vec[0] * (1.0f / 256.0f);
2969                                         light[1] = vec[0] * (1.0f / 256.0f);
2970                                         light[2] = vec[0] * (1.0f / 256.0f);
2971                                         light[3] = vec[0];
2972                                 }
2973                                 else if (n == 4)
2974                                 {
2975                                         // halflife
2976                                         light[0] = vec[0] * (1.0f / 255.0f);
2977                                         light[1] = vec[1] * (1.0f / 255.0f);
2978                                         light[2] = vec[2] * (1.0f / 255.0f);
2979                                         light[3] = vec[3];
2980                                 }
2981                         }
2982                         else if (!strcmp("delay", key))
2983                                 type = atoi(value);
2984                         else if (!strcmp("origin", key))
2985                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
2986                         else if (!strcmp("angle", key))
2987                                 angles[0] = 0, angles[1] = atof(value), angles[2] = 0;
2988                         else if (!strcmp("angles", key))
2989                                 sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
2990                         else if (!strcmp("color", key))
2991                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
2992                         else if (!strcmp("wait", key))
2993                                 fadescale = atof(value);
2994                         else if (!strcmp("classname", key))
2995                         {
2996                                 if (!strncmp(value, "light", 5))
2997                                 {
2998                                         islight = true;
2999                                         if (!strcmp(value, "light_fluoro"))
3000                                         {
3001                                                 originhack[0] = 0;
3002                                                 originhack[1] = 0;
3003                                                 originhack[2] = 0;
3004                                                 overridecolor[0] = 1;
3005                                                 overridecolor[1] = 1;
3006                                                 overridecolor[2] = 1;
3007                                         }
3008                                         if (!strcmp(value, "light_fluorospark"))
3009                                         {
3010                                                 originhack[0] = 0;
3011                                                 originhack[1] = 0;
3012                                                 originhack[2] = 0;
3013                                                 overridecolor[0] = 1;
3014                                                 overridecolor[1] = 1;
3015                                                 overridecolor[2] = 1;
3016                                         }
3017                                         if (!strcmp(value, "light_globe"))
3018                                         {
3019                                                 originhack[0] = 0;
3020                                                 originhack[1] = 0;
3021                                                 originhack[2] = 0;
3022                                                 overridecolor[0] = 1;
3023                                                 overridecolor[1] = 0.8;
3024                                                 overridecolor[2] = 0.4;
3025                                         }
3026                                         if (!strcmp(value, "light_flame_large_yellow"))
3027                                         {
3028                                                 originhack[0] = 0;
3029                                                 originhack[1] = 0;
3030                                                 originhack[2] = 0;
3031                                                 overridecolor[0] = 1;
3032                                                 overridecolor[1] = 0.5;
3033                                                 overridecolor[2] = 0.1;
3034                                         }
3035                                         if (!strcmp(value, "light_flame_small_yellow"))
3036                                         {
3037                                                 originhack[0] = 0;
3038                                                 originhack[1] = 0;
3039                                                 originhack[2] = 0;
3040                                                 overridecolor[0] = 1;
3041                                                 overridecolor[1] = 0.5;
3042                                                 overridecolor[2] = 0.1;
3043                                         }
3044                                         if (!strcmp(value, "light_torch_small_white"))
3045                                         {
3046                                                 originhack[0] = 0;
3047                                                 originhack[1] = 0;
3048                                                 originhack[2] = 0;
3049                                                 overridecolor[0] = 1;
3050                                                 overridecolor[1] = 0.5;
3051                                                 overridecolor[2] = 0.1;
3052                                         }
3053                                         if (!strcmp(value, "light_torch_small_walltorch"))
3054                                         {
3055                                                 originhack[0] = 0;
3056                                                 originhack[1] = 0;
3057                                                 originhack[2] = 0;
3058                                                 overridecolor[0] = 1;
3059                                                 overridecolor[1] = 0.5;
3060                                                 overridecolor[2] = 0.1;
3061                                         }
3062                                 }
3063                         }
3064                         else if (!strcmp("style", key))
3065                                 style = atoi(value);
3066                         else if (!strcmp("skin", key))
3067                                 skin = (int)atof(value);
3068                         else if (!strcmp("pflags", key))
3069                                 pflags = (int)atof(value);
3070                         else if (!strcmp("effects", key))
3071                                 effects = (int)atof(value);
3072                         else if (r_refdef.worldmodel->type == mod_brushq3)
3073                         {
3074                                 if (!strcmp("scale", key))
3075                                         lightscale = atof(value);
3076                                 if (!strcmp("fade", key))
3077                                         fadescale = atof(value);
3078                         }
3079                 }
3080                 if (!islight)
3081                         continue;
3082                 if (lightscale <= 0)
3083                         lightscale = 1;
3084                 if (fadescale <= 0)
3085                         fadescale = 1;
3086                 if (color[0] == color[1] && color[0] == color[2])
3087                 {
3088                         color[0] *= overridecolor[0];
3089                         color[1] *= overridecolor[1];
3090                         color[2] *= overridecolor[2];
3091                 }
3092                 radius = light[3] * r_editlights_quakelightsizescale.value * lightscale / fadescale;
3093                 color[0] = color[0] * light[0];
3094                 color[1] = color[1] * light[1];
3095                 color[2] = color[2] * light[2];
3096                 switch (type)
3097                 {
3098                 case LIGHTTYPE_MINUSX:
3099                         break;
3100                 case LIGHTTYPE_RECIPX:
3101                         radius *= 2;
3102                         VectorScale(color, (1.0f / 16.0f), color);
3103                         break;
3104                 case LIGHTTYPE_RECIPXX:
3105                         radius *= 2;
3106                         VectorScale(color, (1.0f / 16.0f), color);
3107                         break;
3108                 default:
3109                 case LIGHTTYPE_NONE:
3110                         break;
3111                 case LIGHTTYPE_SUN:
3112                         break;
3113                 case LIGHTTYPE_MINUSXX:
3114                         break;
3115                 }
3116                 VectorAdd(origin, originhack, origin);
3117                 if (radius >= 1)
3118                         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);
3119         }
3120         if (entfiledata)
3121                 Mem_Free(entfiledata);
3122 }
3123
3124
3125 void R_Shadow_SetCursorLocationForView(void)
3126 {
3127         vec_t dist, push;
3128         vec3_t dest, endpos;
3129         trace_t trace;
3130         VectorMA(r_view.origin, r_editlights_cursordistance.value, r_view.forward, dest);
3131         trace = CL_TraceBox(r_view.origin, vec3_origin, vec3_origin, dest, true, NULL, SUPERCONTENTS_SOLID, false);
3132         if (trace.fraction < 1)
3133         {
3134                 dist = trace.fraction * r_editlights_cursordistance.value;
3135                 push = r_editlights_cursorpushback.value;
3136                 if (push > dist)
3137                         push = dist;
3138                 push = -push;
3139                 VectorMA(trace.endpos, push, r_view.forward, endpos);
3140                 VectorMA(endpos, r_editlights_cursorpushoff.value, trace.plane.normal, endpos);
3141         }
3142         else
3143         {
3144                 VectorClear( endpos );
3145         }
3146         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3147         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3148         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
3149 }
3150
3151 void R_Shadow_UpdateWorldLightSelection(void)
3152 {
3153         if (r_editlights.integer)
3154         {
3155                 R_Shadow_SetCursorLocationForView();
3156                 R_Shadow_SelectLightInView();
3157                 R_Shadow_DrawLightSprites();
3158         }
3159         else
3160                 R_Shadow_SelectLight(NULL);
3161 }
3162
3163 void R_Shadow_EditLights_Clear_f(void)
3164 {
3165         R_Shadow_ClearWorldLights();
3166 }
3167
3168 void R_Shadow_EditLights_Reload_f(void)
3169 {
3170         if (!r_refdef.worldmodel)
3171                 return;
3172         strlcpy(r_shadow_mapname, r_refdef.worldmodel->name, sizeof(r_shadow_mapname));
3173         R_Shadow_ClearWorldLights();
3174         R_Shadow_LoadWorldLights();
3175         if (r_shadow_worldlightchain == NULL)
3176         {
3177                 R_Shadow_LoadLightsFile();
3178                 if (r_shadow_worldlightchain == NULL)
3179                         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
3180         }
3181 }
3182
3183 void R_Shadow_EditLights_Save_f(void)
3184 {
3185         if (!r_refdef.worldmodel)
3186                 return;
3187         R_Shadow_SaveWorldLights();
3188 }
3189
3190 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
3191 {
3192         R_Shadow_ClearWorldLights();
3193         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
3194 }
3195
3196 void R_Shadow_EditLights_ImportLightsFile_f(void)
3197 {
3198         R_Shadow_ClearWorldLights();
3199         R_Shadow_LoadLightsFile();
3200 }
3201
3202 void R_Shadow_EditLights_Spawn_f(void)
3203 {
3204         vec3_t color;
3205         if (!r_editlights.integer)
3206         {
3207                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3208                 return;
3209         }
3210         if (Cmd_Argc() != 1)
3211         {
3212                 Con_Print("r_editlights_spawn does not take parameters\n");
3213                 return;
3214         }
3215         color[0] = color[1] = color[2] = 1;
3216         R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE);
3217 }
3218
3219 void R_Shadow_EditLights_Edit_f(void)
3220 {
3221         vec3_t origin, angles, color;
3222         vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale;
3223         int style, shadows, flags, normalmode, realtimemode;
3224         char cubemapname[MAX_INPUTLINE];
3225         if (!r_editlights.integer)
3226         {
3227                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3228                 return;
3229         }
3230         if (!r_shadow_selectedlight)
3231         {
3232                 Con_Print("No selected light.\n");
3233                 return;
3234         }
3235         VectorCopy(r_shadow_selectedlight->origin, origin);
3236         VectorCopy(r_shadow_selectedlight->angles, angles);
3237         VectorCopy(r_shadow_selectedlight->color, color);
3238         radius = r_shadow_selectedlight->radius;
3239         style = r_shadow_selectedlight->style;
3240         if (r_shadow_selectedlight->cubemapname)
3241                 strlcpy(cubemapname, r_shadow_selectedlight->cubemapname, sizeof(cubemapname));
3242         else
3243                 cubemapname[0] = 0;
3244         shadows = r_shadow_selectedlight->shadow;
3245         corona = r_shadow_selectedlight->corona;
3246         coronasizescale = r_shadow_selectedlight->coronasizescale;
3247         ambientscale = r_shadow_selectedlight->ambientscale;
3248         diffusescale = r_shadow_selectedlight->diffusescale;
3249         specularscale = r_shadow_selectedlight->specularscale;
3250         flags = r_shadow_selectedlight->flags;
3251         normalmode = (flags & LIGHTFLAG_NORMALMODE) != 0;
3252         realtimemode = (flags & LIGHTFLAG_REALTIMEMODE) != 0;
3253         if (!strcmp(Cmd_Argv(1), "origin"))
3254         {
3255                 if (Cmd_Argc() != 5)
3256                 {
3257                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3258                         return;
3259                 }
3260                 origin[0] = atof(Cmd_Argv(2));
3261                 origin[1] = atof(Cmd_Argv(3));
3262                 origin[2] = atof(Cmd_Argv(4));
3263         }
3264         else if (!strcmp(Cmd_Argv(1), "originx"))
3265         {
3266                 if (Cmd_Argc() != 3)
3267                 {
3268                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3269                         return;
3270                 }
3271                 origin[0] = atof(Cmd_Argv(2));
3272         }
3273         else if (!strcmp(Cmd_Argv(1), "originy"))
3274         {
3275                 if (Cmd_Argc() != 3)
3276                 {
3277                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3278                         return;
3279                 }
3280                 origin[1] = atof(Cmd_Argv(2));
3281         }
3282         else if (!strcmp(Cmd_Argv(1), "originz"))
3283         {
3284                 if (Cmd_Argc() != 3)
3285                 {
3286                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3287                         return;
3288                 }
3289                 origin[2] = atof(Cmd_Argv(2));
3290         }
3291         else if (!strcmp(Cmd_Argv(1), "move"))
3292         {
3293                 if (Cmd_Argc() != 5)
3294                 {
3295                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3296                         return;
3297                 }
3298                 origin[0] += atof(Cmd_Argv(2));
3299                 origin[1] += atof(Cmd_Argv(3));
3300                 origin[2] += atof(Cmd_Argv(4));
3301         }
3302         else if (!strcmp(Cmd_Argv(1), "movex"))
3303         {
3304                 if (Cmd_Argc() != 3)
3305                 {
3306                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3307                         return;
3308                 }
3309                 origin[0] += atof(Cmd_Argv(2));
3310         }
3311         else if (!strcmp(Cmd_Argv(1), "movey"))
3312         {
3313                 if (Cmd_Argc() != 3)
3314                 {
3315                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3316                         return;
3317                 }
3318                 origin[1] += atof(Cmd_Argv(2));
3319         }
3320         else if (!strcmp(Cmd_Argv(1), "movez"))
3321         {
3322                 if (Cmd_Argc() != 3)
3323                 {
3324                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3325                         return;
3326                 }
3327                 origin[2] += atof(Cmd_Argv(2));
3328         }
3329         else if (!strcmp(Cmd_Argv(1), "angles"))
3330         {
3331                 if (Cmd_Argc() != 5)
3332                 {
3333                         Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1));
3334                         return;
3335                 }
3336                 angles[0] = atof(Cmd_Argv(2));
3337                 angles[1] = atof(Cmd_Argv(3));
3338                 angles[2] = atof(Cmd_Argv(4));
3339         }
3340         else if (!strcmp(Cmd_Argv(1), "anglesx"))
3341         {
3342                 if (Cmd_Argc() != 3)
3343                 {
3344                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3345                         return;
3346                 }
3347                 angles[0] = atof(Cmd_Argv(2));
3348         }
3349         else if (!strcmp(Cmd_Argv(1), "anglesy"))
3350         {
3351                 if (Cmd_Argc() != 3)
3352                 {
3353                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3354                         return;
3355                 }
3356                 angles[1] = atof(Cmd_Argv(2));
3357         }
3358         else if (!strcmp(Cmd_Argv(1), "anglesz"))
3359         {
3360                 if (Cmd_Argc() != 3)
3361                 {
3362                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3363                         return;
3364                 }
3365                 angles[2] = atof(Cmd_Argv(2));
3366         }
3367         else if (!strcmp(Cmd_Argv(1), "color"))
3368         {
3369                 if (Cmd_Argc() != 5)
3370                 {
3371                         Con_Printf("usage: r_editlights_edit %s red green blue\n", Cmd_Argv(1));
3372                         return;
3373                 }
3374                 color[0] = atof(Cmd_Argv(2));
3375                 color[1] = atof(Cmd_Argv(3));
3376                 color[2] = atof(Cmd_Argv(4));
3377         }
3378         else if (!strcmp(Cmd_Argv(1), "radius"))
3379         {
3380                 if (Cmd_Argc() != 3)
3381                 {
3382                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3383                         return;
3384                 }
3385                 radius = atof(Cmd_Argv(2));
3386         }
3387         else if (!strcmp(Cmd_Argv(1), "colorscale"))
3388         {
3389                 if (Cmd_Argc() == 3)
3390                 {
3391                         double scale = atof(Cmd_Argv(2));
3392                         color[0] *= scale;
3393                         color[1] *= scale;
3394                         color[2] *= scale;
3395                 }
3396                 else
3397                 {
3398                         if (Cmd_Argc() != 5)
3399                         {
3400                                 Con_Printf("usage: r_editlights_edit %s red green blue  (OR grey instead of red green blue)\n", Cmd_Argv(1));
3401                                 return;
3402                         }
3403                         color[0] *= atof(Cmd_Argv(2));
3404                         color[1] *= atof(Cmd_Argv(3));
3405                         color[2] *= atof(Cmd_Argv(4));
3406                 }
3407         }
3408         else if (!strcmp(Cmd_Argv(1), "radiusscale") || !strcmp(Cmd_Argv(1), "sizescale"))
3409         {
3410                 if (Cmd_Argc() != 3)
3411                 {
3412                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3413                         return;
3414                 }
3415                 radius *= atof(Cmd_Argv(2));
3416         }
3417         else if (!strcmp(Cmd_Argv(1), "style"))
3418         {
3419                 if (Cmd_Argc() != 3)
3420                 {
3421                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3422                         return;
3423                 }
3424                 style = atoi(Cmd_Argv(2));
3425         }
3426         else if (!strcmp(Cmd_Argv(1), "cubemap"))
3427         {
3428                 if (Cmd_Argc() > 3)
3429                 {
3430                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3431                         return;
3432                 }
3433                 if (Cmd_Argc() == 3)
3434                         strcpy(cubemapname, Cmd_Argv(2));
3435                 else
3436                         cubemapname[0] = 0;
3437         }
3438         else if (!strcmp(Cmd_Argv(1), "shadows"))
3439         {
3440                 if (Cmd_Argc() != 3)
3441                 {
3442                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3443                         return;
3444                 }
3445                 shadows = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
3446         }
3447         else if (!strcmp(Cmd_Argv(1), "corona"))
3448         {
3449                 if (Cmd_Argc() != 3)
3450                 {
3451                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3452                         return;
3453                 }
3454                 corona = atof(Cmd_Argv(2));
3455         }
3456         else if (!strcmp(Cmd_Argv(1), "coronasize"))
3457         {
3458                 if (Cmd_Argc() != 3)
3459                 {
3460                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3461                         return;
3462                 }
3463                 coronasizescale = atof(Cmd_Argv(2));
3464         }
3465         else if (!strcmp(Cmd_Argv(1), "ambient"))
3466         {
3467                 if (Cmd_Argc() != 3)
3468                 {
3469                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3470                         return;
3471                 }
3472                 ambientscale = atof(Cmd_Argv(2));
3473         }
3474         else if (!strcmp(Cmd_Argv(1), "diffuse"))
3475         {
3476                 if (Cmd_Argc() != 3)
3477                 {
3478                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3479                         return;
3480                 }
3481                 diffusescale = atof(Cmd_Argv(2));
3482         }
3483         else if (!strcmp(Cmd_Argv(1), "specular"))
3484         {
3485                 if (Cmd_Argc() != 3)
3486                 {
3487                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3488                         return;
3489                 }
3490                 specularscale = atof(Cmd_Argv(2));
3491         }
3492         else if (!strcmp(Cmd_Argv(1), "normalmode"))
3493         {
3494                 if (Cmd_Argc() != 3)
3495                 {
3496                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3497                         return;
3498                 }
3499                 normalmode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
3500         }
3501         else if (!strcmp(Cmd_Argv(1), "realtimemode"))
3502         {
3503                 if (Cmd_Argc() != 3)
3504                 {
3505                         Con_Printf("usage: r_editlights_edit %s value\n", Cmd_Argv(1));
3506                         return;
3507                 }
3508                 realtimemode = Cmd_Argv(2)[0] == 'y' || Cmd_Argv(2)[0] == 'Y' || Cmd_Argv(2)[0] == 't' || atoi(Cmd_Argv(2));
3509         }
3510         else
3511         {
3512                 Con_Print("usage: r_editlights_edit [property] [value]\n");
3513                 Con_Print("Selected light's properties:\n");
3514                 Con_Printf("Origin       : %f %f %f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);
3515                 Con_Printf("Angles       : %f %f %f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);
3516                 Con_Printf("Color        : %f %f %f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);
3517                 Con_Printf("Radius       : %f\n", r_shadow_selectedlight->radius);
3518                 Con_Printf("Corona       : %f\n", r_shadow_selectedlight->corona);
3519                 Con_Printf("Style        : %i\n", r_shadow_selectedlight->style);
3520                 Con_Printf("Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");
3521                 Con_Printf("Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);
3522                 Con_Printf("CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);
3523                 Con_Printf("Ambient      : %f\n", r_shadow_selectedlight->ambientscale);
3524                 Con_Printf("Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);
3525                 Con_Printf("Specular     : %f\n", r_shadow_selectedlight->specularscale);
3526                 Con_Printf("NormalMode   : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");
3527                 Con_Printf("RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");
3528                 return;
3529         }
3530         flags = (normalmode ? LIGHTFLAG_NORMALMODE : 0) | (realtimemode ? LIGHTFLAG_REALTIMEMODE : 0);
3531         R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags);
3532 }
3533
3534 void R_Shadow_EditLights_EditAll_f(void)
3535 {
3536         dlight_t *light;
3537
3538         if (!r_editlights.integer)
3539         {
3540                 Con_Print("Cannot edit lights when not in editing mode. Set r_editlights to 1.\n");
3541                 return;
3542         }
3543
3544         for (light = r_shadow_worldlightchain;light;light = light->next)
3545         {
3546                 R_Shadow_SelectLight(light);
3547                 R_Shadow_EditLights_Edit_f();
3548         }
3549 }
3550
3551 void R_Shadow_EditLights_DrawSelectedLightProperties(void)
3552 {
3553         int lightnumber, lightcount;
3554         dlight_t *light;
3555         float x, y;
3556         char temp[256];
3557         if (!r_editlights.integer)
3558                 return;
3559         x = 0;
3560         y = con_vislines;
3561         lightnumber = -1;
3562         lightcount = 0;
3563         for (lightcount = 0, light = r_shadow_worldlightchain;light;lightcount++, light = light->next)
3564                 if (light == r_shadow_selectedlight)
3565                         lightnumber = lightcount;
3566         sprintf(temp, "Cursor  %f %f %f  Total Lights %i", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2], lightcount);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3567         if (r_shadow_selectedlight == NULL)
3568                 return;
3569         sprintf(temp, "Light #%i properties", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3570         sprintf(temp, "Origin       : %f %f %f\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);y += 8;
3571         sprintf(temp, "Angles       : %f %f %f\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);y += 8;
3572         sprintf(temp, "Color        : %f %f %f\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);y += 8;
3573         sprintf(temp, "Radius       : %f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3574         sprintf(temp, "Corona       : %f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3575         sprintf(temp, "Style        : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3576         sprintf(temp, "Shadows      : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3577         sprintf(temp, "Cubemap      : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3578         sprintf(temp, "CoronaSize   : %f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3579         sprintf(temp, "Ambient      : %f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3580         sprintf(temp, "Diffuse      : %f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3581         sprintf(temp, "Specular     : %f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0);y += 8;
3582         sprintf(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);y += 8;
3583         sprintf(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);y += 8;
3584 }
3585
3586 void R_Shadow_EditLights_ToggleShadow_f(void)
3587 {
3588         if (!r_editlights.integer)
3589         {
3590                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3591                 return;
3592         }
3593         if (!r_shadow_selectedlight)
3594         {
3595                 Con_Print("No selected light.\n");
3596                 return;
3597         }
3598         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);
3599 }
3600
3601 void R_Shadow_EditLights_ToggleCorona_f(void)
3602 {
3603         if (!r_editlights.integer)
3604         {
3605                 Con_Print("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
3606                 return;
3607         }
3608         if (!r_shadow_selectedlight)
3609         {
3610                 Con_Print("No selected light.\n");
3611                 return;
3612         }
3613         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);
3614 }
3615
3616 void R_Shadow_EditLights_Remove_f(void)
3617 {
3618         if (!r_editlights.integer)
3619         {
3620                 Con_Print("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
3621                 return;
3622         }
3623         if (!r_shadow_selectedlight)
3624         {
3625                 Con_Print("No selected light.\n");
3626                 return;
3627         }
3628         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
3629         r_shadow_selectedlight = NULL;
3630 }
3631
3632 void R_Shadow_EditLights_Help_f(void)
3633 {
3634         Con_Print(
3635 "Documentation on r_editlights system:\n"
3636 "Settings:\n"
3637 "r_editlights : enable/disable editing mode\n"
3638 "r_editlights_cursordistance : maximum distance of cursor from eye\n"
3639 "r_editlights_cursorpushback : push back cursor this far from surface\n"
3640 "r_editlights_cursorpushoff : push cursor off surface this far\n"
3641 "r_editlights_cursorgrid : snap cursor to grid of this size\n"
3642 "r_editlights_quakelightsizescale : imported quake light entity size scaling\n"
3643 "Commands:\n"
3644 "r_editlights_help : this help\n"
3645 "r_editlights_clear : remove all lights\n"
3646 "r_editlights_reload : reload .rtlights, .lights file, or entities\n"
3647 "r_editlights_save : save to .rtlights file\n"
3648 "r_editlights_spawn : create a light with default settings\n"
3649 "r_editlights_edit command : edit selected light - more documentation below\n"
3650 "r_editlights_remove : remove selected light\n"
3651 "r_editlights_toggleshadow : toggles on/off selected light's shadow property\n"
3652 "r_editlights_importlightentitiesfrommap : reload light entities\n"
3653 "r_editlights_importlightsfile : reload .light file (produced by hlight)\n"
3654 "Edit commands:\n"
3655 "origin x y z : set light location\n"
3656 "originx x: set x component of light location\n"
3657 "originy y: set y component of light location\n"
3658 "originz z: set z component of light location\n"
3659 "move x y z : adjust light location\n"
3660 "movex x: adjust x component of light location\n"
3661 "movey y: adjust y component of light location\n"
3662 "movez z: adjust z component of light location\n"
3663 "angles x y z : set light angles\n"
3664 "anglesx x: set x component of light angles\n"
3665 "anglesy y: set y component of light angles\n"
3666 "anglesz z: set z component of light angles\n"
3667 "color r g b : set color of light (can be brighter than 1 1 1)\n"
3668 "radius radius : set radius (size) of light\n"
3669 "colorscale grey : multiply color of light (1 does nothing)\n"
3670 "colorscale r g b : multiply color of light (1 1 1 does nothing)\n"
3671 "radiusscale scale : multiply radius (size) of light (1 does nothing)\n"
3672 "sizescale scale : multiply radius (size) of light (1 does nothing)\n"
3673 "style style : set lightstyle of light (flickering patterns, switches, etc)\n"
3674 "cubemap basename : set filter cubemap of light (not yet supported)\n"
3675 "shadows 1/0 : turn on/off shadows\n"
3676 "corona n : set corona intensity\n"
3677 "coronasize n : set corona size (0-1)\n"
3678 "ambient n : set ambient intensity (0-1)\n"
3679 "diffuse n : set diffuse intensity (0-1)\n"
3680 "specular n : set specular intensity (0-1)\n"
3681 "normalmode 1/0 : turn on/off rendering of this light in rtworld 0 mode\n"
3682 "realtimemode 1/0 : turn on/off rendering of this light in rtworld 1 mode\n"
3683 "<nothing> : print light properties to console\n"
3684         );
3685 }
3686
3687 void R_Shadow_EditLights_CopyInfo_f(void)
3688 {
3689         if (!r_editlights.integer)
3690         {
3691                 Con_Print("Cannot copy light info when not in editing mode.  Set r_editlights to 1.\n");
3692                 return;
3693         }
3694         if (!r_shadow_selectedlight)
3695         {
3696                 Con_Print("No selected light.\n");
3697                 return;
3698         }
3699         VectorCopy(r_shadow_selectedlight->angles, r_shadow_bufferlight.angles);
3700         VectorCopy(r_shadow_selectedlight->color, r_shadow_bufferlight.color);
3701         r_shadow_bufferlight.radius = r_shadow_selectedlight->radius;
3702         r_shadow_bufferlight.style = r_shadow_selectedlight->style;
3703         if (r_shadow_selectedlight->cubemapname)
3704                 strcpy(r_shadow_bufferlight.cubemapname, r_shadow_selectedlight->cubemapname);
3705         else
3706                 r_shadow_bufferlight.cubemapname[0] = 0;
3707         r_shadow_bufferlight.shadow = r_shadow_selectedlight->shadow;
3708         r_shadow_bufferlight.corona = r_shadow_selectedlight->corona;
3709         r_shadow_bufferlight.coronasizescale = r_shadow_selectedlight->coronasizescale;
3710         r_shadow_bufferlight.ambientscale = r_shadow_selectedlight->ambientscale;
3711         r_shadow_bufferlight.diffusescale = r_shadow_selectedlight->diffusescale;
3712         r_shadow_bufferlight.specularscale = r_shadow_selectedlight->specularscale;
3713         r_shadow_bufferlight.flags = r_shadow_selectedlight->flags;
3714 }
3715
3716 void R_Shadow_EditLights_PasteInfo_f(void)
3717 {
3718         if (!r_editlights.integer)
3719         {
3720                 Con_Print("Cannot paste light info when not in editing mode.  Set r_editlights to 1.\n");
3721                 return;
3722         }
3723         if (!r_shadow_selectedlight)
3724         {
3725                 Con_Print("No selected light.\n");
3726                 return;
3727         }
3728         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);
3729 }
3730
3731 void R_Shadow_EditLights_Init(void)
3732 {
3733         Cvar_RegisterVariable(&r_editlights);
3734         Cvar_RegisterVariable(&r_editlights_cursordistance);
3735         Cvar_RegisterVariable(&r_editlights_cursorpushback);
3736         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
3737         Cvar_RegisterVariable(&r_editlights_cursorgrid);
3738         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
3739         Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system");
3740         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)");
3741         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)");
3742         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f, "save .rtlights file for current level");
3743         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f, "creates a light with default properties (let there be light!)");
3744         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f, "changes a property on the selected light");
3745         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)");
3746         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f, "remove selected light");
3747         Cmd_AddCommand("r_editlights_toggleshadow", R_Shadow_EditLights_ToggleShadow_f, "toggle on/off the shadow option on the selected light");
3748         Cmd_AddCommand("r_editlights_togglecorona", R_Shadow_EditLights_ToggleCorona_f, "toggle on/off the corona option on the selected light");
3749         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f, "load lights from .ent file or map entities (ignoring .rtlights or .lights file)");
3750         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)");
3751         Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light");
3752         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)");
3753 }
3754