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