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