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