removed use of 3D textures
[divverent/darkplaces.git] / r_shadow.c
1
2 #include "quakedef.h"
3 #include "r_shadow.h"
4 #include "cl_collision.h"
5
6 extern void R_Shadow_EditLights_Init(void);
7
8 #define SHADOWSTAGE_NONE 0
9 #define SHADOWSTAGE_STENCIL 1
10 #define SHADOWSTAGE_LIGHT 2
11 #define SHADOWSTAGE_ERASESTENCIL 3
12
13 int r_shadowstage = SHADOWSTAGE_NONE;
14 int r_shadow_reloadlights = false;
15
16 int r_shadow_lightingmode = 0;
17
18 mempool_t *r_shadow_mempool;
19
20 int maxshadowelements;
21 int *shadowelements;
22 int maxtrianglefacinglight;
23 qbyte *trianglefacinglight;
24
25 rtexturepool_t *r_shadow_texturepool;
26 rtexture_t *r_shadow_normalscubetexture;
27 rtexture_t *r_shadow_attenuation2dtexture;
28 rtexture_t *r_shadow_blankbumptexture;
29 rtexture_t *r_shadow_blankglosstexture;
30 rtexture_t *r_shadow_blankwhitetexture;
31
32 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "2"};
33 cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1"};
34 cvar_t r_shadow_realtime = {0, "r_shadow_realtime", "0"};
35 cvar_t r_shadow_gloss = {0, "r_shadow_gloss", "1"};
36 cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1"};
37 cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1"};
38 cvar_t r_shadow_bumpscale = {0, "r_shadow_bumpscale", "4"};
39 cvar_t r_shadow_shadownudge = {0, "r_shadow_shadownudge", "1"};
40
41 void R_Shadow_ClearWorldLights(void);
42 void R_Shadow_SaveWorldLights(void);
43 void R_Shadow_LoadWorldLights(void);
44 void R_Shadow_LoadLightsFile(void);
45 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void);
46
47 void r_shadow_start(void)
48 {
49         // allocate vertex processing arrays
50         r_shadow_mempool = Mem_AllocPool("R_Shadow");
51         maxshadowelements = 0;
52         shadowelements = NULL;
53         maxtrianglefacinglight = 0;
54         trianglefacinglight = NULL;
55         r_shadow_normalscubetexture = NULL;
56         r_shadow_attenuation2dtexture = NULL;
57         r_shadow_blankbumptexture = NULL;
58         r_shadow_blankglosstexture = NULL;
59         r_shadow_blankwhitetexture = NULL;
60         r_shadow_texturepool = NULL;
61         R_Shadow_ClearWorldLights();
62         r_shadow_reloadlights = true;
63 }
64
65 void r_shadow_shutdown(void)
66 {
67         R_Shadow_ClearWorldLights();
68         r_shadow_reloadlights = true;
69         r_shadow_normalscubetexture = NULL;
70         r_shadow_attenuation2dtexture = NULL;
71         r_shadow_blankbumptexture = NULL;
72         r_shadow_blankglosstexture = NULL;
73         r_shadow_blankwhitetexture = NULL;
74         R_FreeTexturePool(&r_shadow_texturepool);
75         maxshadowelements = 0;
76         shadowelements = NULL;
77         maxtrianglefacinglight = 0;
78         trianglefacinglight = NULL;
79         Mem_FreePool(&r_shadow_mempool);
80 }
81
82 void r_shadow_newmap(void)
83 {
84         R_Shadow_ClearWorldLights();
85         r_shadow_reloadlights = true;
86 }
87
88 void R_Shadow_Init(void)
89 {
90         Cvar_RegisterVariable(&r_shadow_lightattenuationscale);
91         Cvar_RegisterVariable(&r_shadow_lightintensityscale);
92         Cvar_RegisterVariable(&r_shadow_realtime);
93         Cvar_RegisterVariable(&r_shadow_gloss);
94         Cvar_RegisterVariable(&r_shadow_debuglight);
95         Cvar_RegisterVariable(&r_shadow_scissor);
96         Cvar_RegisterVariable(&r_shadow_bumpscale);
97         Cvar_RegisterVariable(&r_shadow_shadownudge);
98         R_Shadow_EditLights_Init();
99         R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap);
100 }
101
102 void R_Shadow_ProjectVertices(float *verts, int numverts, const float *relativelightorigin, float projectdistance)
103 {
104         int i;
105         float *in, *out, diff[4];
106         in = verts;
107         out = verts + numverts * 4;
108         for (i = 0;i < numverts;i++, in += 4, out += 4)
109         {
110                 VectorSubtract(in, relativelightorigin, diff);
111                 VectorNormalizeFast(diff);
112                 VectorMA(in, projectdistance, diff, out);
113                 VectorMA(in, r_shadow_shadownudge.value, diff, in);
114         }
115 }
116
117 void R_Shadow_MakeTriangleShadowFlags(const int *elements, const float *vertex, int numtris, qbyte *trianglefacinglight, const float *relativelightorigin, float lightradius)
118 {
119         int i;
120         const float *v0, *v1, *v2;
121         for (i = 0;i < numtris;i++, elements += 3)
122         {
123                 // calculate triangle facing flag
124                 v0 = vertex + elements[0] * 4;
125                 v1 = vertex + elements[1] * 4;
126                 v2 = vertex + elements[2] * 4;
127                 // we do not need to normalize the surface normal because both sides
128                 // of the comparison use it, therefore they are both multiplied the
129                 // same amount...  furthermore the subtract can be done on the
130                 // vectors, saving a little bit of math in the dotproducts
131 #if 0
132                 // fast version
133                 // subtracts v1 from v0 and v2, combined into a crossproduct,
134                 // combined with a dotproduct of the light location relative to the
135                 // first point of the triangle (any point works, since the triangle
136                 // is obviously flat), and finally a comparison to determine if the
137                 // light is infront of the triangle (the goal of this statement)
138                 trianglefacinglight[i] =
139                    (relativelightorigin[0] - v0[0]) * ((v0[1] - v1[1]) * (v2[2] - v1[2]) - (v0[2] - v1[2]) * (v2[1] - v1[1]))
140                  + (relativelightorigin[1] - v0[1]) * ((v0[2] - v1[2]) * (v2[0] - v1[0]) - (v0[0] - v1[0]) * (v2[2] - v1[2]))
141                  + (relativelightorigin[2] - v0[2]) * ((v0[0] - v1[0]) * (v2[1] - v1[1]) - (v0[1] - v1[1]) * (v2[0] - v1[0])) > 0;
142 #else
143                 // readable version
144                 {
145                 float dir0[3], dir1[3], temp[3], f;
146
147                 // calculate two mostly perpendicular edge directions
148                 VectorSubtract(v0, v1, dir0);
149                 VectorSubtract(v2, v1, dir1);
150
151                 // we have two edge directions, we can calculate a third vector from
152                 // them, which is the direction of the surface normal (it's magnitude
153                 // is not 1 however)
154                 CrossProduct(dir0, dir1, temp);
155
156                 // this is entirely unnecessary, but kept for clarity
157                 //VectorNormalize(temp);
158
159                 // compare distance of light along normal, with distance of any point
160                 // of the triangle along the same normal (the triangle is planar,
161                 // I.E. flat, so all points give the same answer)
162                 // the normal is not normalized because it is used on both sides of
163                 // the comparison, so it's magnitude does not matter
164                 //trianglefacinglight[i] = DotProduct(relativelightorigin, temp) >= DotProduct(v0, temp);
165                 f = DotProduct(relativelightorigin, temp) - DotProduct(v0, temp);
166                 trianglefacinglight[i] = f > 0 && f < lightradius * sqrt(DotProduct(temp, temp));
167                 }
168 #endif
169         }
170 }
171
172 int R_Shadow_BuildShadowVolumeTriangles(const int *elements, const int *neighbors, int numtris, int numverts, const qbyte *trianglefacinglight, int *out)
173 {
174         int i, tris;
175         // check each frontface for bordering backfaces,
176         // and cast shadow polygons from those edges,
177         // also create front and back caps for shadow volume
178         tris = 0;
179         for (i = 0;i < numtris;i++, elements += 3, neighbors += 3)
180         {
181                 if (trianglefacinglight[i])
182                 {
183                         // triangle is frontface and therefore casts shadow,
184                         // output front and back caps for shadow volume
185                         // front cap
186                         out[0] = elements[0];
187                         out[1] = elements[1];
188                         out[2] = elements[2];
189                         // rear cap (with flipped winding order)
190                         out[3] = elements[0] + numverts;
191                         out[4] = elements[2] + numverts;
192                         out[5] = elements[1] + numverts;
193                         out += 6;
194                         tris += 2;
195                         // check the edges
196                         if (neighbors[0] < 0 || !trianglefacinglight[neighbors[0]])
197                         {
198                                 out[0] = elements[1];
199                                 out[1] = elements[0];
200                                 out[2] = elements[0] + numverts;
201                                 out[3] = elements[1];
202                                 out[4] = elements[0] + numverts;
203                                 out[5] = elements[1] + numverts;
204                                 out += 6;
205                                 tris += 2;
206                         }
207                         if (neighbors[1] < 0 || !trianglefacinglight[neighbors[1]])
208                         {
209                                 out[0] = elements[2];
210                                 out[1] = elements[1];
211                                 out[2] = elements[1] + numverts;
212                                 out[3] = elements[2];
213                                 out[4] = elements[1] + numverts;
214                                 out[5] = elements[2] + numverts;
215                                 out += 6;
216                                 tris += 2;
217                         }
218                         if (neighbors[2] < 0 || !trianglefacinglight[neighbors[2]])
219                         {
220                                 out[0] = elements[0];
221                                 out[1] = elements[2];
222                                 out[2] = elements[2] + numverts;
223                                 out[3] = elements[0];
224                                 out[4] = elements[2] + numverts;
225                                 out[5] = elements[0] + numverts;
226                                 out += 6;
227                                 tris += 2;
228                         }
229                 }
230         }
231         return tris;
232 }
233
234 void R_Shadow_ResizeTriangleFacingLight(int numtris)
235 {
236         // make sure trianglefacinglight is big enough for this volume
237         if (maxtrianglefacinglight < numtris)
238         {
239                 maxtrianglefacinglight = numtris;
240                 if (trianglefacinglight)
241                         Mem_Free(trianglefacinglight);
242                 trianglefacinglight = Mem_Alloc(r_shadow_mempool, maxtrianglefacinglight);
243         }
244 }
245
246 void R_Shadow_ResizeShadowElements(int numtris)
247 {
248         // make sure shadowelements is big enough for this volume
249         if (maxshadowelements < numtris * 24)
250         {
251                 maxshadowelements = numtris * 24;
252                 if (shadowelements)
253                         Mem_Free(shadowelements);
254                 shadowelements = Mem_Alloc(r_shadow_mempool, maxshadowelements * sizeof(int));
255         }
256 }
257
258 void R_Shadow_Volume(int numverts, int numtris, int *elements, int *neighbors, vec3_t relativelightorigin, float lightradius, float projectdistance)
259 {
260         int tris;
261         if (projectdistance < 0.1)
262         {
263                 Con_Printf("R_Shadow_Volume: projectdistance %f\n");
264                 return;
265         }
266 // terminology:
267 //
268 // frontface:
269 // a triangle facing the light source
270 //
271 // backface:
272 // a triangle not facing the light source
273 //
274 // shadow volume:
275 // an extrusion of the frontfaces, beginning at the original geometry and
276 // ending further from the light source than the original geometry
277 // (presumably at least as far as the light's radius, if the light has a
278 // radius at all), capped at both front and back to avoid any problems
279 //
280 // description:
281 // draws the shadow volumes of the model.
282 // requirements:
283 // vertex locations must already be in varray_vertex before use.
284 // varray_vertex must have capacity for numverts * 2.
285
286         // make sure trianglefacinglight is big enough for this volume
287         if (maxtrianglefacinglight < numtris)
288                 R_Shadow_ResizeTriangleFacingLight(numtris);
289
290         // make sure shadowelements is big enough for this volume
291         if (maxshadowelements < numtris * 24)
292                 R_Shadow_ResizeShadowElements(numtris);
293
294         // check which triangles are facing the light
295         R_Shadow_MakeTriangleShadowFlags(elements, varray_vertex, numtris, trianglefacinglight, relativelightorigin, lightradius);
296
297         // generate projected vertices
298         // by clever use of elements we'll construct the whole shadow from
299         // the unprojected vertices and these projected vertices
300         R_Shadow_ProjectVertices(varray_vertex, numverts, relativelightorigin, projectdistance);
301
302         // output triangle elements
303         tris = R_Shadow_BuildShadowVolumeTriangles(elements, neighbors, numtris, numverts, trianglefacinglight, shadowelements);
304         R_Shadow_RenderVolume(numverts * 2, tris, shadowelements);
305 }
306
307 void R_Shadow_RenderVolume(int numverts, int numtris, int *elements)
308 {
309         if (!numverts || !numtris)
310                 return;
311         if (r_shadowstage == SHADOWSTAGE_STENCIL)
312         {
313                 // increment stencil if backface is behind depthbuffer
314                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
315                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
316                 R_Mesh_Draw(numverts, numtris, elements);
317                 // decrement stencil if frontface is behind depthbuffer
318                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
319                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
320         }
321         R_Mesh_Draw(numverts, numtris, elements);
322 }
323
324 void R_Shadow_RenderShadowMeshVolume(shadowmesh_t *firstmesh)
325 {
326         shadowmesh_t *mesh;
327         if (r_shadowstage == SHADOWSTAGE_STENCIL)
328         {
329                 // increment stencil if backface is behind depthbuffer
330                 qglCullFace(GL_BACK); // quake is backwards, this culls front faces
331                 qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
332                 for (mesh = firstmesh;mesh;mesh = mesh->next)
333                 {
334                         R_Mesh_ResizeCheck(mesh->numverts);
335                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
336                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
337                 }
338                 // decrement stencil if frontface is behind depthbuffer
339                 qglCullFace(GL_FRONT); // quake is backwards, this culls back faces
340                 qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
341         }
342         for (mesh = firstmesh;mesh;mesh = mesh->next)
343         {
344                 R_Mesh_ResizeCheck(mesh->numverts);
345                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
346                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
347         }
348 }
349
350 float r_shadow_atten1;
351 static void R_Shadow_MakeTextures(void)
352 {
353         int x, y, d, side;
354         float v[3], s, t, intensity;
355         qbyte *data;
356         R_FreeTexturePool(&r_shadow_texturepool);
357         r_shadow_texturepool = R_AllocTexturePool();
358         r_shadow_atten1 = r_shadow_lightattenuationscale.value;
359         data = Mem_Alloc(tempmempool, 6*128*128*4);
360         data[0] = 128;
361         data[1] = 128;
362         data[2] = 255;
363         data[3] = 255;
364         r_shadow_blankbumptexture = R_LoadTexture2D(r_shadow_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
365         data[0] = 255;
366         data[1] = 255;
367         data[2] = 255;
368         data[3] = 255;
369         r_shadow_blankglosstexture = R_LoadTexture2D(r_shadow_texturepool, "blankgloss", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
370         data[0] = 255;
371         data[1] = 255;
372         data[2] = 255;
373         data[3] = 255;
374         r_shadow_blankwhitetexture = R_LoadTexture2D(r_shadow_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
375         for (side = 0;side < 6;side++)
376         {
377                 for (y = 0;y < 128;y++)
378                 {
379                         for (x = 0;x < 128;x++)
380                         {
381                                 s = (x + 0.5f) * (2.0f / 128.0f) - 1.0f;
382                                 t = (y + 0.5f) * (2.0f / 128.0f) - 1.0f;
383                                 switch(side)
384                                 {
385                                 case 0:
386                                         v[0] = 1;
387                                         v[1] = -t;
388                                         v[2] = -s;
389                                         break;
390                                 case 1:
391                                         v[0] = -1;
392                                         v[1] = -t;
393                                         v[2] = s;
394                                         break;
395                                 case 2:
396                                         v[0] = s;
397                                         v[1] = 1;
398                                         v[2] = t;
399                                         break;
400                                 case 3:
401                                         v[0] = s;
402                                         v[1] = -1;
403                                         v[2] = -t;
404                                         break;
405                                 case 4:
406                                         v[0] = s;
407                                         v[1] = -t;
408                                         v[2] = 1;
409                                         break;
410                                 case 5:
411                                         v[0] = -s;
412                                         v[1] = -t;
413                                         v[2] = -1;
414                                         break;
415                                 }
416                                 intensity = 127.0f / sqrt(DotProduct(v, v));
417                                 data[((side*128+y)*128+x)*4+0] = 128.0f + intensity * v[0];
418                                 data[((side*128+y)*128+x)*4+1] = 128.0f + intensity * v[1];
419                                 data[((side*128+y)*128+x)*4+2] = 128.0f + intensity * v[2];
420                                 data[((side*128+y)*128+x)*4+3] = 255;
421                         }
422                 }
423         }
424         r_shadow_normalscubetexture = R_LoadTextureCubeMap(r_shadow_texturepool, "normalscube", 128, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
425         for (y = 0;y < 128;y++)
426         {
427                 for (x = 0;x < 128;x++)
428                 {
429                         v[0] = (x + 0.5f) * (2.0f / 128.0f) - 1.0f;
430                         v[1] = (y + 0.5f) * (2.0f / 128.0f) - 1.0f;
431                         v[2] = 0;
432                         intensity = 1.0f - sqrt(DotProduct(v, v));
433                         if (intensity > 0)
434                                 intensity *= intensity;
435                         intensity = bound(0, intensity * r_shadow_atten1 * 256.0f, 255.0f);
436                         d = bound(0, intensity, 255);
437                         data[((0*128+y)*128+x)*4+0] = d;
438                         data[((0*128+y)*128+x)*4+1] = d;
439                         data[((0*128+y)*128+x)*4+2] = d;
440                         data[((0*128+y)*128+x)*4+3] = d;
441                 }
442         }
443         r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", 128, 128, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_MIPMAP, NULL);
444         Mem_Free(data);
445 }
446
447 void R_Shadow_Stage_Begin(void)
448 {
449         rmeshstate_t m;
450
451         //cl.worldmodel->numlights = min(cl.worldmodel->numlights, 1);
452         if (!r_shadow_attenuation2dtexture
453          || r_shadow_lightattenuationscale.value != r_shadow_atten1)
454                 R_Shadow_MakeTextures();
455         if (r_shadow_reloadlights && cl.worldmodel)
456         {
457                 r_shadow_reloadlights = false;
458                 R_Shadow_LoadWorldLights();
459                 if (r_shadow_worldlightchain == NULL)
460                 {
461                         R_Shadow_LoadLightsFile();
462                         if (r_shadow_worldlightchain == NULL)
463                                 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
464                 }
465         }
466
467         memset(&m, 0, sizeof(m));
468         m.blendfunc1 = GL_ONE;
469         m.blendfunc2 = GL_ZERO;
470         R_Mesh_State(&m);
471         GL_Color(0, 0, 0, 1);
472         r_shadowstage = SHADOWSTAGE_NONE;
473 }
474
475 void R_Shadow_Stage_ShadowVolumes(void)
476 {
477         rmeshstate_t m;
478         memset(&m, 0, sizeof(m));
479         R_Mesh_TextureState(&m);
480         GL_Color(1, 1, 1, 1);
481         qglColorMask(0, 0, 0, 0);
482         qglDisable(GL_BLEND);
483         qglDepthMask(0);
484         qglDepthFunc(GL_LESS);
485         qglEnable(GL_STENCIL_TEST);
486         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
487         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
488         qglEnable(GL_CULL_FACE);
489         qglEnable(GL_DEPTH_TEST);
490         r_shadowstage = SHADOWSTAGE_STENCIL;
491         qglClear(GL_STENCIL_BUFFER_BIT);
492 }
493
494 void R_Shadow_Stage_Light(void)
495 {
496         rmeshstate_t m;
497         memset(&m, 0, sizeof(m));
498         R_Mesh_TextureState(&m);
499         qglActiveTexture(GL_TEXTURE0_ARB);
500
501         qglEnable(GL_BLEND);
502         qglBlendFunc(GL_ONE, GL_ONE);
503         GL_Color(1, 1, 1, 1);
504         qglColorMask(1, 1, 1, 1);
505         qglDepthMask(0);
506         qglDepthFunc(GL_EQUAL);
507         qglEnable(GL_STENCIL_TEST);
508         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
509         // only draw light where this geometry was already rendered AND the
510         // stencil is 128 (values other than this mean shadow)
511         qglStencilFunc(GL_EQUAL, 128, 0xFF);
512         qglEnable(GL_CULL_FACE);
513         qglEnable(GL_DEPTH_TEST);
514         r_shadowstage = SHADOWSTAGE_LIGHT;
515 }
516
517 void R_Shadow_Stage_End(void)
518 {
519         rmeshstate_t m;
520         // attempt to restore state to what Mesh_State thinks it is
521         qglDisable(GL_BLEND);
522         qglBlendFunc(GL_ONE, GL_ZERO);
523         qglDepthMask(1);
524         // now restore the rest of the state to normal
525         GL_Color(1, 1, 1, 1);
526         qglColorMask(1, 1, 1, 1);
527         qglDisable(GL_SCISSOR_TEST);
528         qglDepthFunc(GL_LEQUAL);
529         qglDisable(GL_STENCIL_TEST);
530         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
531         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
532         qglEnable(GL_CULL_FACE);
533         qglEnable(GL_DEPTH_TEST);
534         // force mesh state to reset by using various combinations of features
535         memset(&m, 0, sizeof(m));
536         m.blendfunc1 = GL_SRC_ALPHA;
537         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
538         R_Mesh_State(&m);
539         m.blendfunc1 = GL_ONE;
540         m.blendfunc2 = GL_ZERO;
541         R_Mesh_State(&m);
542         r_shadowstage = SHADOWSTAGE_NONE;
543 }
544
545 int R_Shadow_ScissorForBBoxAndSphere(const float *mins, const float *maxs, const float *origin, float radius)
546 {
547         int i, ix1, iy1, ix2, iy2;
548         float x1, y1, x2, y2, x, y;
549         vec3_t smins, smaxs;
550         vec4_t v, v2;
551         if (!r_shadow_scissor.integer)
552                 return false;
553         // if view is inside the box, just say yes it's visible
554         if (r_origin[0] >= mins[0] && r_origin[0] <= maxs[0]
555          && r_origin[1] >= mins[1] && r_origin[1] <= maxs[1]
556          && r_origin[2] >= mins[2] && r_origin[2] <= maxs[2])
557         {
558                 qglDisable(GL_SCISSOR_TEST);
559                 return false;
560         }
561         VectorSubtract(r_origin, origin, v);
562         if (DotProduct(v, v) < radius * radius)
563         {
564                 qglDisable(GL_SCISSOR_TEST);
565                 return false;
566         }
567         // create viewspace bbox
568         for (i = 0;i < 8;i++)
569         {
570                 v[0] = ((i & 1) ? mins[0] : maxs[0]) - r_origin[0];
571                 v[1] = ((i & 2) ? mins[1] : maxs[1]) - r_origin[1];
572                 v[2] = ((i & 4) ? mins[2] : maxs[2]) - r_origin[2];
573                 v2[0] = DotProduct(v, vright);
574                 v2[1] = DotProduct(v, vup);
575                 v2[2] = DotProduct(v, vpn);
576                 if (i)
577                 {
578                         if (smins[0] > v2[0]) smins[0] = v2[0];
579                         if (smaxs[0] < v2[0]) smaxs[0] = v2[0];
580                         if (smins[1] > v2[1]) smins[1] = v2[1];
581                         if (smaxs[1] < v2[1]) smaxs[1] = v2[1];
582                         if (smins[2] > v2[2]) smins[2] = v2[2];
583                         if (smaxs[2] < v2[2]) smaxs[2] = v2[2];
584                 }
585                 else
586                 {
587                         smins[0] = smaxs[0] = v2[0];
588                         smins[1] = smaxs[1] = v2[1];
589                         smins[2] = smaxs[2] = v2[2];
590                 }
591         }
592         // now we have a bbox in viewspace
593         // clip it to the viewspace version of the sphere
594         v[0] = origin[0] - r_origin[0];
595         v[1] = origin[1] - r_origin[1];
596         v[2] = origin[2] - r_origin[2];
597         v2[0] = DotProduct(v, vright);
598         v2[1] = DotProduct(v, vup);
599         v2[2] = DotProduct(v, vpn);
600         if (smins[0] < v2[0] - radius) smins[0] = v2[0] - radius;
601         if (smaxs[0] < v2[0] - radius) smaxs[0] = v2[0] + radius;
602         if (smins[1] < v2[1] - radius) smins[1] = v2[1] - radius;
603         if (smaxs[1] < v2[1] - radius) smaxs[1] = v2[1] + radius;
604         if (smins[2] < v2[2] - radius) smins[2] = v2[2] - radius;
605         if (smaxs[2] < v2[2] - radius) smaxs[2] = v2[2] + radius;
606         // clip it to the view plane
607         if (smins[2] < 1)
608                 smins[2] = 1;
609         // return true if that culled the box
610         if (smins[2] >= smaxs[2])
611                 return true;
612         // ok some of it is infront of the view, transform each corner back to
613         // worldspace and then to screenspace and make screen rect
614         for (i = 0;i < 8;i++)
615         {
616                 v2[0] = (i & 1) ? smins[0] : smaxs[0];
617                 v2[1] = (i & 2) ? smins[1] : smaxs[1];
618                 v2[2] = (i & 4) ? smins[2] : smaxs[2];
619                 v[0] = v2[0] * vright[0] + v2[1] * vup[0] + v2[2] * vpn[0] + r_origin[0];
620                 v[1] = v2[0] * vright[1] + v2[1] * vup[1] + v2[2] * vpn[1] + r_origin[1];
621                 v[2] = v2[0] * vright[2] + v2[1] * vup[2] + v2[2] * vpn[2] + r_origin[2];
622                 v[3] = 1.0f;
623                 GL_TransformToScreen(v, v2);
624                 //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]);
625                 x = v2[0];
626                 y = v2[1];
627                 if (i)
628                 {
629                         if (x1 > x) x1 = x;
630                         if (x2 < x) x2 = x;
631                         if (y1 > y) y1 = y;
632                         if (y2 < y) y2 = y;
633                 }
634                 else
635                 {
636                         x1 = x2 = x;
637                         y1 = y2 = y;
638                 }
639         }
640         /*
641         // this code doesn't handle boxes with any points behind view properly
642         x1 = 1000;x2 = -1000;
643         y1 = 1000;y2 = -1000;
644         for (i = 0;i < 8;i++)
645         {
646                 v[0] = (i & 1) ? mins[0] : maxs[0];
647                 v[1] = (i & 2) ? mins[1] : maxs[1];
648                 v[2] = (i & 4) ? mins[2] : maxs[2];
649                 v[3] = 1.0f;
650                 GL_TransformToScreen(v, v2);
651                 //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]);
652                 if (v2[2] > 0)
653                 {
654                         x = v2[0];
655                         y = v2[1];
656
657                         if (x1 > x) x1 = x;
658                         if (x2 < x) x2 = x;
659                         if (y1 > y) y1 = y;
660                         if (y2 < y) y2 = y;
661                 }
662         }
663         */
664         ix1 = x1 - 1.0f;
665         iy1 = y1 - 1.0f;
666         ix2 = x2 + 1.0f;
667         iy2 = y2 + 1.0f;
668         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
669         if (ix1 < r_refdef.x) ix1 = r_refdef.x;
670         if (iy1 < r_refdef.y) iy1 = r_refdef.y;
671         if (ix2 > r_refdef.x + r_refdef.width) ix2 = r_refdef.x + r_refdef.width;
672         if (iy2 > r_refdef.y + r_refdef.height) iy2 = r_refdef.y + r_refdef.height;
673         if (ix2 <= ix1 || iy2 <= iy1)
674                 return true;
675         // set up the scissor rectangle
676         qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
677         qglEnable(GL_SCISSOR_TEST);
678         return false;
679 }
680
681 void R_Shadow_GenTexCoords_Attenuation2D1D(float *out2d, float *out1d, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, float lightradius)
682 {
683         int i;
684         float lightvec[3], iradius;
685         iradius = 0.5f / lightradius;
686         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out2d += 4, out1d += 4)
687         {
688                 VectorSubtract(vertex, relativelightorigin, lightvec);
689                 out2d[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
690                 out2d[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
691                 out2d[2] = 0;
692                 out1d[0] = 0.5f + DotProduct(normals, lightvec) * iradius;
693                 out1d[1] = 0.5f;
694                 out1d[2] = 0;
695         }
696 }
697
698 void R_Shadow_GenTexCoords_Diffuse_Attenuation3D(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, float lightradius)
699 {
700         int i;
701         float lightvec[3], iradius;
702         iradius = 0.5f / lightradius;
703         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
704         {
705                 VectorSubtract(vertex, relativelightorigin, lightvec);
706                 out[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
707                 out[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
708                 out[2] = 0.5f + DotProduct(normals, lightvec) * iradius;
709         }
710 }
711
712 void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin)
713 {
714         int i;
715         float lightdir[3];
716         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
717         {
718                 VectorSubtract(vertex, relativelightorigin, lightdir);
719                 // the cubemap normalizes this for us
720                 out[0] = DotProduct(svectors, lightdir);
721                 out[1] = DotProduct(tvectors, lightdir);
722                 out[2] = DotProduct(normals, lightdir);
723         }
724 }
725
726 void R_Shadow_GenTexCoords_Specular_Attenuation3D(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, const vec3_t relativeeyeorigin, float lightradius)
727 {
728         int i;
729         float lightdir[3], eyedir[3], halfdir[3], lightdirlen, iradius;
730         iradius = 0.5f / lightradius;
731         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
732         {
733                 VectorSubtract(vertex, relativelightorigin, lightdir);
734                 // this is used later to make the attenuation correct
735                 lightdirlen = sqrt(DotProduct(lightdir, lightdir)) * iradius;
736                 VectorNormalizeFast(lightdir);
737                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
738                 VectorNormalizeFast(eyedir);
739                 VectorAdd(lightdir, eyedir, halfdir);
740                 VectorNormalizeFast(halfdir);
741                 out[0] = 0.5f + DotProduct(svectors, halfdir) * lightdirlen;
742                 out[1] = 0.5f + DotProduct(tvectors, halfdir) * lightdirlen;
743                 out[2] = 0.5f + DotProduct(normals, halfdir) * lightdirlen;
744         }
745 }
746
747 void R_Shadow_GenTexCoords_Specular_NormalCubeMap(float *out, int numverts, const float *vertex, const float *svectors, const float *tvectors, const float *normals, const vec3_t relativelightorigin, const vec3_t relativeeyeorigin)
748 {
749         int i;
750         float lightdir[3], eyedir[3], halfdir[3];
751         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
752         {
753                 VectorSubtract(vertex, relativelightorigin, lightdir);
754                 VectorNormalizeFast(lightdir);
755                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
756                 VectorNormalizeFast(eyedir);
757                 VectorAdd(lightdir, eyedir, halfdir);
758                 // the cubemap normalizes this for us
759                 out[0] = DotProduct(svectors, halfdir);
760                 out[1] = DotProduct(tvectors, halfdir);
761                 out[2] = DotProduct(normals, halfdir);
762         }
763 }
764
765 void R_Shadow_GenTexCoords_LightCubeMap(float *out, int numverts, const float *vertex, const vec3_t relativelightorigin)
766 {
767         int i;
768         // FIXME: this needs to be written
769         // this code assumes the vertices are in worldspace (a false assumption)
770         for (i = 0;i < numverts;i++, vertex += 4, out += 4)
771                 VectorSubtract(vertex, relativelightorigin, out);
772 }
773
774 void R_Shadow_DiffuseLighting(int numverts, int numtriangles, const int *elements, const float *svectors, const float *tvectors, const float *normals, const float *texcoords, const float *relativelightorigin, float lightradius, const float *lightcolor, rtexture_t *basetexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
775 {
776         int renders, mult;
777         float scale, colorscale;
778         rmeshstate_t m;
779         memset(&m, 0, sizeof(m));
780         if (!bumptexture)
781                 bumptexture = r_shadow_blankbumptexture;
782         // colorscale accounts for how much we multiply the brightness during combine
783         // mult is how many times the final pass of the lighting will be
784         // performed to get more brightness than otherwise possible
785         // limit mult to 64 for sanity sake
786         if (r_textureunits.integer >= 4)
787         {
788                 // 4 texture no3D combine path, two pass
789                 m.tex[0] = R_GetTexture(bumptexture);
790                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
791                 m.texcombinergb[0] = GL_REPLACE;
792                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
793                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
794                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
795                 R_Mesh_TextureState(&m);
796                 qglColorMask(0,0,0,1);
797                 qglDisable(GL_BLEND);
798                 GL_Color(1,1,1,1);
799                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
800                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
801                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[2], varray_texcoord[3], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
802                 R_Mesh_Draw(numverts, numtriangles, elements);
803
804                 m.tex[0] = R_GetTexture(basetexture);
805                 m.texcubemap[1] = R_GetTexture(lightcubemap);
806                 m.texcombinergb[0] = GL_MODULATE;
807                 m.texcombinergb[1] = GL_MODULATE;
808                 m.tex[2] = 0;
809                 m.tex[3] = 0;
810                 R_Mesh_TextureState(&m);
811                 qglColorMask(1,1,1,1);
812                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
813                 qglEnable(GL_BLEND);
814                 if (lightcubemap)
815                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
816
817                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
818                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
819                 colorscale *= scale;
820                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
821                 for (renders = 0;renders < mult;renders++)
822                         R_Mesh_Draw(numverts, numtriangles, elements);
823         }
824         else
825         {
826                 // 2 texture no3D combine path, three pass
827                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
828                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
829                 R_Mesh_TextureState(&m);
830                 qglColorMask(0,0,0,1);
831                 qglDisable(GL_BLEND);
832                 GL_Color(1,1,1,1);
833                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
834                 R_Mesh_Draw(numverts, numtriangles, elements);
835
836                 m.tex[0] = R_GetTexture(bumptexture);
837                 m.tex[1] = 0;
838                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
839                 m.texcombinergb[0] = GL_REPLACE;
840                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
841                 R_Mesh_TextureState(&m);
842                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
843                 qglEnable(GL_BLEND);
844                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
845                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
846                 R_Mesh_Draw(numverts, numtriangles, elements);
847
848                 m.tex[0] = R_GetTexture(basetexture);
849                 m.texcubemap[1] = R_GetTexture(lightcubemap);
850                 m.texcombinergb[0] = GL_MODULATE;
851                 m.texcombinergb[1] = GL_MODULATE;
852                 R_Mesh_TextureState(&m);
853                 qglColorMask(1,1,1,1);
854                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
855                 if (lightcubemap)
856                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
857
858                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
859                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
860                 colorscale *= scale;
861                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
862                 for (renders = 0;renders < mult;renders++)
863                         R_Mesh_Draw(numverts, numtriangles, elements);
864         }
865 }
866
867 void R_Shadow_SpecularLighting(int numverts, int numtriangles, const int *elements, const float *svectors, const float *tvectors, const float *normals, const float *texcoords, const float *relativelightorigin, const float *relativeeyeorigin, float lightradius, const float *lightcolor, rtexture_t *glosstexture, rtexture_t *bumptexture, rtexture_t *lightcubemap)
868 {
869         int renders, mult;
870         float scale, colorscale;
871         rmeshstate_t m;
872         memset(&m, 0, sizeof(m));
873         if (!bumptexture)
874                 bumptexture = r_shadow_blankbumptexture;
875         if (!glosstexture)
876                 glosstexture = r_shadow_blankglosstexture;
877         if (r_shadow_gloss.integer >= 2 || (r_shadow_gloss.integer >= 1 && glosstexture != r_shadow_blankglosstexture))
878         {
879                 // 2 texture no3D combine path, five pass
880                 memset(&m, 0, sizeof(m));
881
882                 m.tex[0] = R_GetTexture(bumptexture);
883                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
884                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
885                 R_Mesh_TextureState(&m);
886                 qglColorMask(0,0,0,1);
887                 qglDisable(GL_BLEND);
888                 GL_Color(1,1,1,1);
889                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
890                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
891                 R_Mesh_Draw(numverts, numtriangles, elements);
892
893                 m.tex[0] = 0;
894                 m.texcubemap[1] = 0;
895                 m.texcombinergb[1] = GL_MODULATE;
896                 R_Mesh_TextureState(&m);
897                 // square alpha in framebuffer a few times to make it shiny
898                 qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
899                 qglEnable(GL_BLEND);
900                 // these comments are a test run through this math for intensity 0.5
901                 // 0.5 * 0.5 = 0.25
902                 R_Mesh_Draw(numverts, numtriangles, elements);
903                 // 0.25 * 0.25 = 0.0625
904                 R_Mesh_Draw(numverts, numtriangles, elements);
905                 // 0.0625 * 0.0625 = 0.00390625
906                 R_Mesh_Draw(numverts, numtriangles, elements);
907
908                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
909                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
910                 R_Mesh_TextureState(&m);
911                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
912                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
913                 R_Mesh_Draw(numverts, numtriangles, elements);
914
915                 m.tex[0] = R_GetTexture(glosstexture);
916                 m.texcubemap[1] = R_GetTexture(lightcubemap);
917                 R_Mesh_TextureState(&m);
918                 qglColorMask(1,1,1,1);
919                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
920                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
921                 if (lightcubemap)
922                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
923
924                 // the 0.25f makes specular lighting much dimmer than diffuse (intentionally)
925                 colorscale = r_colorscale * 0.25f * r_shadow_lightintensityscale.value;
926                 for (mult = 1, scale = ixtable[mult];mult < 64 && (lightcolor[0] * scale * colorscale > 1 || lightcolor[1] * scale * colorscale > 1 || lightcolor[2] * scale * colorscale > 1);mult++, scale = ixtable[mult]);
927                 colorscale *= scale;
928                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
929                 for (renders = 0;renders < mult;renders++)
930                         R_Mesh_Draw(numverts, numtriangles, elements);
931         }
932 }
933
934 void R_Shadow_DrawWorldLightShadowVolume(matrix4x4_t *matrix, worldlight_t *light)
935 {
936         R_Mesh_Matrix(matrix);
937         R_Shadow_RenderShadowMeshVolume(light->shadowvolume);
938 }
939
940 cvar_t r_editlights = {0, "r_editlights", "0"};
941 cvar_t r_editlights_cursordistance = {0, "r_editlights_distance", "1024"};
942 cvar_t r_editlights_cursorpushback = {0, "r_editlights_pushback", "0"};
943 cvar_t r_editlights_cursorpushoff = {0, "r_editlights_pushoff", "4"};
944 cvar_t r_editlights_cursorgrid = {0, "r_editlights_grid", "4"};
945 worldlight_t *r_shadow_worldlightchain;
946 worldlight_t *r_shadow_selectedlight;
947 vec3_t r_editlights_cursorlocation;
948
949 static int castshadowcount = 1;
950 void R_Shadow_NewWorldLight(vec3_t origin, float radius, vec3_t color, int style, const char *cubemapname)
951 {
952         int i, j, k, l, maxverts, *mark, tris;
953         float *verts, *v, f, temp[3], radius2;
954         //float projectdistance, *v0, *v1, temp2[3], temp3[3];
955         worldlight_t *e;
956         shadowmesh_t *mesh, *castmesh;
957         mleaf_t *leaf;
958         msurface_t *surf;
959         qbyte *pvs;
960         surfmesh_t *surfmesh;
961
962         e = Mem_Alloc(r_shadow_mempool, sizeof(worldlight_t));
963         VectorCopy(origin, e->origin);
964         VectorCopy(color, e->light);
965         e->lightradius = radius;
966         VectorCopy(origin, e->mins);
967         VectorCopy(origin, e->maxs);
968         e->cullradius = 0;
969         e->style = style;
970         e->next = r_shadow_worldlightchain;
971         r_shadow_worldlightchain = e;
972         if (cubemapname)
973         {
974                 e->cubemapname = Mem_Alloc(r_shadow_mempool, strlen(cubemapname) + 1);
975                 strcpy(e->cubemapname, cubemapname);
976                 // FIXME: add cubemap loading (and don't load a cubemap twice)
977         }
978         if (cl.worldmodel)
979         {
980                 castshadowcount++;
981                 leaf = Mod_PointInLeaf(origin, cl.worldmodel);
982                 pvs = Mod_LeafPVS(leaf, cl.worldmodel);
983                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
984                 {
985                         if (pvs[i >> 3] & (1 << (i & 7)))
986                         {
987                                 VectorCopy(origin, temp);
988                                 if (temp[0] < leaf->mins[0]) temp[0] = leaf->mins[0];
989                                 if (temp[0] > leaf->maxs[0]) temp[0] = leaf->maxs[0];
990                                 if (temp[1] < leaf->mins[1]) temp[1] = leaf->mins[1];
991                                 if (temp[1] > leaf->maxs[1]) temp[1] = leaf->maxs[1];
992                                 if (temp[2] < leaf->mins[2]) temp[2] = leaf->mins[2];
993                                 if (temp[2] > leaf->maxs[2]) temp[2] = leaf->maxs[2];
994                                 VectorSubtract(temp, origin, temp);
995                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
996                                 {
997                                         leaf->worldnodeframe = castshadowcount;
998                                         for (j = 0, mark = leaf->firstmarksurface;j < leaf->nummarksurfaces;j++, mark++)
999                                         {
1000                                                 surf = cl.worldmodel->surfaces + *mark;
1001                                                 if (surf->castshadow != castshadowcount)
1002                                                 {
1003                                                         f = DotProduct(e->origin, surf->plane->normal) - surf->plane->dist;
1004                                                         if (surf->flags & SURF_PLANEBACK)
1005                                                                 f = -f;
1006                                                         if (f > 0 && f < e->lightradius)
1007                                                         {
1008                                                                 temp[0] = bound(surf->poly_mins[0], e->origin[0], surf->poly_maxs[0]) - e->origin[0];
1009                                                                 temp[1] = bound(surf->poly_mins[1], e->origin[1], surf->poly_maxs[1]) - e->origin[1];
1010                                                                 temp[2] = bound(surf->poly_mins[2], e->origin[2], surf->poly_maxs[2]) - e->origin[2];
1011                                                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1012                                                                         surf->castshadow = castshadowcount;
1013                                                         }
1014                                                 }
1015                                         }
1016                                 }
1017                         }
1018                 }
1019
1020                 e->numleafs = 0;
1021                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1022                         if (leaf->worldnodeframe == castshadowcount)
1023                                 e->numleafs++;
1024                 e->numsurfaces = 0;
1025                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1026                         if (surf->castshadow == castshadowcount)
1027                                 e->numsurfaces++;
1028
1029                 if (e->numleafs)
1030                         e->leafs = Mem_Alloc(r_shadow_mempool, e->numleafs * sizeof(mleaf_t *));
1031                 if (e->numsurfaces)
1032                         e->surfaces = Mem_Alloc(r_shadow_mempool, e->numsurfaces * sizeof(msurface_t *));
1033                 e->numleafs = 0;
1034                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1035                         if (leaf->worldnodeframe == castshadowcount)
1036                                 e->leafs[e->numleafs++] = leaf;
1037                 e->numsurfaces = 0;
1038                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1039                         if (surf->castshadow == castshadowcount)
1040                                 e->surfaces[e->numsurfaces++] = surf;
1041                 // find bounding box and sphere of lit surfaces
1042                 // (these will be used for creating a shape to clip the light)
1043                 radius2 = 0;
1044                 VectorCopy(e->origin, e->mins);
1045                 VectorCopy(e->origin, e->maxs);
1046                 for (j = 0;j < e->numsurfaces;j++)
1047                 {
1048                         surf = e->surfaces[j];
1049                         for (k = 0, v = surf->poly_verts;k < surf->poly_numverts;k++, v += 3)
1050                         {
1051                                 if (e->mins[0] > v[0]) e->mins[0] = v[0];if (e->maxs[0] < v[0]) e->maxs[0] = v[0];
1052                                 if (e->mins[1] > v[1]) e->mins[1] = v[1];if (e->maxs[1] < v[1]) e->maxs[1] = v[1];
1053                                 if (e->mins[2] > v[2]) e->mins[2] = v[2];if (e->maxs[2] < v[2]) e->maxs[2] = v[2];
1054                                 VectorSubtract(v, e->origin, temp);
1055                                 f = DotProduct(temp, temp);
1056                                 if (radius2 < f)
1057                                         radius2 = f;
1058                         }
1059                 }
1060                 e->cullradius = sqrt(radius2);
1061                 if (e->cullradius > e->lightradius)
1062                         e->cullradius = e->lightradius;
1063                 if (e->mins[0] < e->origin[0] - e->lightradius) e->mins[0] = e->origin[0] - e->lightradius;
1064                 if (e->maxs[0] > e->origin[0] + e->lightradius) e->maxs[0] = e->origin[0] + e->lightradius;
1065                 if (e->mins[1] < e->origin[1] - e->lightradius) e->mins[1] = e->origin[1] - e->lightradius;
1066                 if (e->maxs[1] > e->origin[1] + e->lightradius) e->maxs[1] = e->origin[1] + e->lightradius;
1067                 if (e->mins[2] < e->origin[2] - e->lightradius) e->mins[2] = e->origin[2] - e->lightradius;
1068                 if (e->maxs[2] > e->origin[2] + e->lightradius) e->maxs[2] = e->origin[2] + e->lightradius;
1069                 Con_Printf("%f %f %f, %f %f %f, %f, %f, %d, %d\n", e->mins[0], e->mins[1], e->mins[2], e->maxs[0], e->maxs[1], e->maxs[2], e->cullradius, e->lightradius, e->numleafs, e->numsurfaces);
1070                 // clip shadow volumes against eachother to remove unnecessary
1071                 // polygons (and sections of polygons)
1072                 maxverts = 256;
1073                 verts = NULL;
1074                 castshadowcount++;
1075                 for (j = 0;j < e->numsurfaces;j++)
1076                 {
1077                         surf = e->surfaces[j];
1078                         if (surf->flags & SURF_SHADOWCAST)
1079                         {
1080                                 surf->castshadow = castshadowcount;
1081                                 if (maxverts < surf->poly_numverts)
1082                                         maxverts = surf->poly_numverts;
1083                         }
1084                 }
1085                 e->shadowvolume = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1086                 // make a mesh to cast a shadow volume from
1087                 castmesh = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1088                 for (j = 0;j < e->numsurfaces;j++)
1089                         if (e->surfaces[j]->castshadow == castshadowcount)
1090                                 for (surfmesh = e->surfaces[j]->mesh;surfmesh;surfmesh = surfmesh->chain)
1091                                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, castmesh, surfmesh->numverts, surfmesh->verts, surfmesh->numtriangles, surfmesh->index);
1092                 castmesh = Mod_ShadowMesh_Finish(r_shadow_mempool, castmesh);
1093
1094                 // cast shadow volume from castmesh
1095                 for (mesh = castmesh;mesh;mesh = mesh->next)
1096                 {
1097                         R_Shadow_ResizeTriangleFacingLight(castmesh->numtriangles);
1098                         R_Shadow_ResizeShadowElements(castmesh->numtriangles);
1099
1100                         if (maxverts < castmesh->numverts * 2)
1101                         {
1102                                 maxverts = castmesh->numverts * 2;
1103                                 if (verts)
1104                                         Mem_Free(verts);
1105                                 verts = NULL;
1106                         }
1107                         if (verts == NULL && maxverts > 0)
1108                                 verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1109
1110                         // now that we have the buffers big enough, construct shadow volume mesh
1111                         memcpy(verts, castmesh->verts, castmesh->numverts * sizeof(float[4]));
1112                         R_Shadow_ProjectVertices(verts, castmesh->numverts, e->origin, 1000000.0f);//, e->lightradius);
1113                         R_Shadow_MakeTriangleShadowFlags(castmesh->elements, verts, castmesh->numtriangles, trianglefacinglight, e->origin, e->lightradius);
1114                         tris = R_Shadow_BuildShadowVolumeTriangles(castmesh->elements, castmesh->neighbors, castmesh->numtriangles, castmesh->numverts, trianglefacinglight, shadowelements);
1115                         // add the constructed shadow volume mesh
1116                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, e->shadowvolume, castmesh->numverts, verts, tris, shadowelements);
1117                 }
1118                 // we're done with castmesh now
1119                 Mod_ShadowMesh_Free(castmesh);
1120                 e->shadowvolume = Mod_ShadowMesh_Finish(r_shadow_mempool, e->shadowvolume);
1121                 for (l = 0, mesh = e->shadowvolume;mesh;mesh = mesh->next)
1122                         l += mesh->numtriangles;
1123                 Con_Printf("static shadow volume built containing %i triangles\n", l);
1124         }
1125 }
1126
1127 void R_Shadow_FreeWorldLight(worldlight_t *light)
1128 {
1129         worldlight_t **lightpointer;
1130         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
1131         if (*lightpointer != light)
1132                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain\n");
1133         *lightpointer = light->next;
1134         if (light->cubemapname)
1135                 Mem_Free(light->cubemapname);
1136         if (light->shadowvolume)
1137                 Mod_ShadowMesh_Free(light->shadowvolume);
1138         if (light->surfaces)
1139                 Mem_Free(light->surfaces);
1140         if (light->leafs)
1141                 Mem_Free(light->leafs);
1142         Mem_Free(light);
1143 }
1144
1145 void R_Shadow_ClearWorldLights(void)
1146 {
1147         while (r_shadow_worldlightchain)
1148                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
1149         r_shadow_selectedlight = NULL;
1150 }
1151
1152 void R_Shadow_SelectLight(worldlight_t *light)
1153 {
1154         if (r_shadow_selectedlight)
1155                 r_shadow_selectedlight->selected = false;
1156         r_shadow_selectedlight = light;
1157         if (r_shadow_selectedlight)
1158                 r_shadow_selectedlight->selected = true;
1159 }
1160
1161 void R_Shadow_FreeSelectedWorldLight(void)
1162 {
1163         if (r_shadow_selectedlight)
1164         {
1165                 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1166                 r_shadow_selectedlight = NULL;
1167         }
1168 }
1169
1170 void R_Shadow_SelectLightInView(void)
1171 {
1172         float bestrating, temp[3], dist;
1173         worldlight_t *best, *light;
1174         best = NULL;
1175         bestrating = 1e30;
1176         for (light = r_shadow_worldlightchain;light;light = light->next)
1177         {
1178                 VectorSubtract(light->origin, r_refdef.vieworg, temp);
1179                 dist = sqrt(DotProduct(temp, temp));
1180                 if (DotProduct(temp, vpn) >= 0.97 * dist && bestrating > dist && CL_TraceLine(light->origin, r_refdef.vieworg, NULL, NULL, 0, true, NULL) == 1.0f)
1181                 {
1182                         bestrating = dist;
1183                         best = light;
1184                 }
1185         }
1186         R_Shadow_SelectLight(best);
1187 }
1188
1189 void R_Shadow_LoadWorldLights(void)
1190 {
1191         int n, a, style;
1192         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1193         float origin[3], radius, color[3];
1194         COM_StripExtension(cl.worldmodel->name, name);
1195         strcat(name, ".rtlights");
1196         lightsstring = COM_LoadFile(name, false);
1197         if (lightsstring)
1198         {
1199                 s = lightsstring;
1200                 n = 0;
1201                 while (*s)
1202                 {
1203                         t = s;
1204                         while (*s && *s != '\n')
1205                                 s++;
1206                         if (!*s)
1207                                 break;
1208                         *s = 0;
1209                         a = sscanf(t, "%f %f %f %f %f %f %f %d %s", &origin[0], &origin[1], &origin[2], &radius, &color[0], &color[1], &color[2], &style, &cubemapname);
1210                         if (a < 9)
1211                                 cubemapname[0] = 0;
1212                         *s = '\n';
1213                         if (a < 8)
1214                         {
1215                                 Con_Printf("found %d parameters on line %i, should be 8 or 9 parameters (origin[0] origin[1] origin[2] radius color[0] color[1] color[2] style cubemapname)\n", a, n + 1);
1216                                 break;
1217                         }
1218                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1219                         s++;
1220                         n++;
1221                 }
1222                 if (*s)
1223                         Con_Printf("invalid rtlights file \"%s\"\n", name);
1224                 Mem_Free(lightsstring);
1225         }
1226 }
1227
1228 void R_Shadow_SaveWorldLights(void)
1229 {
1230         worldlight_t *light;
1231         int bufchars, bufmaxchars;
1232         char *buf, *oldbuf;
1233         char name[MAX_QPATH];
1234         char line[1024];
1235         if (!r_shadow_worldlightchain)
1236                 return;
1237         COM_StripExtension(cl.worldmodel->name, name);
1238         strcat(name, ".rtlights");
1239         bufchars = bufmaxchars = 0;
1240         buf = NULL;
1241         for (light = r_shadow_worldlightchain;light;light = light->next)
1242         {
1243                 sprintf(line, "%g %g %g %g %g %g %g %d %s\n", light->origin[0], light->origin[1], light->origin[2], light->lightradius, light->light[0], light->light[1], light->light[2], light->style, light->cubemapname ? light->cubemapname : "");
1244                 if (bufchars + strlen(line) > bufmaxchars)
1245                 {
1246                         bufmaxchars = bufchars + strlen(line) + 2048;
1247                         oldbuf = buf;
1248                         buf = Mem_Alloc(r_shadow_mempool, bufmaxchars);
1249                         if (oldbuf)
1250                         {
1251                                 if (bufchars)
1252                                         memcpy(buf, oldbuf, bufchars);
1253                                 Mem_Free(oldbuf);
1254                         }
1255                 }
1256                 if (strlen(line))
1257                 {
1258                         memcpy(buf + bufchars, line, strlen(line));
1259                         bufchars += strlen(line);
1260                 }
1261         }
1262         if (bufchars)
1263                 COM_WriteFile(name, buf, bufchars);
1264         if (buf)
1265                 Mem_Free(buf);
1266 }
1267
1268 void R_Shadow_LoadLightsFile(void)
1269 {
1270         int n, a, style;
1271         char name[MAX_QPATH], *lightsstring, *s, *t;
1272         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
1273         COM_StripExtension(cl.worldmodel->name, name);
1274         strcat(name, ".lights");
1275         lightsstring = COM_LoadFile(name, false);
1276         if (lightsstring)
1277         {
1278                 s = lightsstring;
1279                 n = 0;
1280                 while (*s)
1281                 {
1282                         t = s;
1283                         while (*s && *s != '\n')
1284                                 s++;
1285                         if (!*s)
1286                                 break;
1287                         *s = 0;
1288                         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);
1289                         *s = '\n';
1290                         if (a < 14)
1291                         {
1292                                 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);
1293                                 break;
1294                         }
1295                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
1296                         radius = bound(15, radius, 4096);
1297                         VectorScale(color, (1.0f / (8388608.0f)), color);
1298                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1299                         s++;
1300                         n++;
1301                 }
1302                 if (*s)
1303                         Con_Printf("invalid lights file \"%s\"\n", name);
1304                 Mem_Free(lightsstring);
1305         }
1306 }
1307
1308 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
1309 {
1310         int entnum, style, islight;
1311         char key[256], value[1024];
1312         float origin[3], radius, color[3], light, scale, originhack[3], overridecolor[3];
1313         const char *data;
1314
1315         data = cl.worldmodel->entities;
1316         if (!data)
1317                 return;
1318         for (entnum = 0;COM_ParseToken(&data) && com_token[0] == '{';entnum++)
1319         {
1320                 light = 0;
1321                 origin[0] = origin[1] = origin[2] = 0;
1322                 originhack[0] = originhack[1] = originhack[2] = 0;
1323                 color[0] = color[1] = color[2] = 1;
1324                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
1325                 scale = 1;
1326                 style = 0;
1327                 islight = false;
1328                 while (1)
1329                 {
1330                         if (!COM_ParseToken(&data))
1331                                 break; // error
1332                         if (com_token[0] == '}')
1333                                 break; // end of entity
1334                         if (com_token[0] == '_')
1335                                 strcpy(key, com_token + 1);
1336                         else
1337                                 strcpy(key, com_token);
1338                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
1339                                 key[strlen(key)-1] = 0;
1340                         if (!COM_ParseToken(&data))
1341                                 break; // error
1342                         strcpy(value, com_token);
1343
1344                         // now that we have the key pair worked out...
1345                         if (!strcmp("light", key))
1346                                 light = atof(value);
1347                         else if (!strcmp("origin", key))
1348                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
1349                         else if (!strcmp("color", key))
1350                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
1351                         else if (!strcmp("wait", key))
1352                                 scale = atof(value);
1353                         else if (!strcmp("classname", key))
1354                         {
1355                                 if (!strncmp(value, "light", 5))
1356                                 {
1357                                         islight = true;
1358                                         if (!strcmp(value, "light_fluoro"))
1359                                         {
1360                                                 originhack[0] = 0;
1361                                                 originhack[1] = 0;
1362                                                 originhack[2] = 0;
1363                                                 overridecolor[0] = 1;
1364                                                 overridecolor[1] = 1;
1365                                                 overridecolor[2] = 1;
1366                                         }
1367                                         if (!strcmp(value, "light_fluorospark"))
1368                                         {
1369                                                 originhack[0] = 0;
1370                                                 originhack[1] = 0;
1371                                                 originhack[2] = 0;
1372                                                 overridecolor[0] = 1;
1373                                                 overridecolor[1] = 1;
1374                                                 overridecolor[2] = 1;
1375                                         }
1376                                         if (!strcmp(value, "light_globe"))
1377                                         {
1378                                                 originhack[0] = 0;
1379                                                 originhack[1] = 0;
1380                                                 originhack[2] = 0;
1381                                                 overridecolor[0] = 1;
1382                                                 overridecolor[1] = 0.8;
1383                                                 overridecolor[2] = 0.4;
1384                                         }
1385                                         if (!strcmp(value, "light_flame_large_yellow"))
1386                                         {
1387                                                 originhack[0] = 0;
1388                                                 originhack[1] = 0;
1389                                                 originhack[2] = 48;
1390                                                 overridecolor[0] = 1;
1391                                                 overridecolor[1] = 0.7;
1392                                                 overridecolor[2] = 0.2;
1393                                         }
1394                                         if (!strcmp(value, "light_flame_small_yellow"))
1395                                         {
1396                                                 originhack[0] = 0;
1397                                                 originhack[1] = 0;
1398                                                 originhack[2] = 40;
1399                                                 overridecolor[0] = 1;
1400                                                 overridecolor[1] = 0.7;
1401                                                 overridecolor[2] = 0.2;
1402                                         }
1403                                         if (!strcmp(value, "light_torch_small_white"))
1404                                         {
1405                                                 originhack[0] = 0;
1406                                                 originhack[1] = 0;
1407                                                 originhack[2] = 40;
1408                                                 overridecolor[0] = 1;
1409                                                 overridecolor[1] = 0.9;
1410                                                 overridecolor[2] = 0.7;
1411                                         }
1412                                         if (!strcmp(value, "light_torch_small_walltorch"))
1413                                         {
1414                                                 originhack[0] = 0;
1415                                                 originhack[1] = 0;
1416                                                 originhack[2] = 40;
1417                                                 overridecolor[0] = 1;
1418                                                 overridecolor[1] = 0.7;
1419                                                 overridecolor[2] = 0.2;
1420                                         }
1421                                 }
1422                         }
1423                         else if (!strcmp("style", key))
1424                                 style = atoi(value);
1425                 }
1426                 if (light <= 0 && islight)
1427                         light = 300;
1428                 radius = bound(0, light / scale, 1048576) + 15.0f;
1429                 light = bound(0, light, 1048576) * (1.0f / 256.0f);
1430                 if (color[0] == 1 && color[1] == 1 && color[2] == 1)
1431                         VectorCopy(overridecolor, color);
1432                 VectorScale(color, light, color);
1433                 VectorAdd(origin, originhack, origin);
1434                 if (radius >= 15)
1435                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1436         }
1437 }
1438
1439
1440 void R_Shadow_SetCursorLocationForView(void)
1441 {
1442         vec_t dist, push, frac;
1443         vec3_t dest, endpos, normal;
1444         VectorMA(r_refdef.vieworg, r_editlights_cursordistance.value, vpn, dest);
1445         frac = CL_TraceLine(r_refdef.vieworg, dest, endpos, normal, 0, true, NULL);
1446         if (frac < 1)
1447         {
1448                 dist = frac * r_editlights_cursordistance.value;
1449                 push = r_editlights_cursorpushback.value;
1450                 if (push > dist)
1451                         push = dist;
1452                 push = -push;
1453                 VectorMA(endpos, push, vpn, endpos);
1454                 VectorMA(endpos, r_editlights_cursorpushoff.value, normal, endpos);
1455         }
1456         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1457         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1458         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1459 }
1460
1461 extern void R_DrawCrosshairSprite(rtexture_t *texture, vec3_t origin, vec_t scale, float cr, float cg, float cb, float ca);
1462 void R_Shadow_DrawCursorCallback(const void *calldata1, int calldata2)
1463 {
1464         cachepic_t *pic;
1465         pic = Draw_CachePic("gfx/crosshair1.tga");
1466         if (pic)
1467                 R_DrawCrosshairSprite(pic->tex, r_editlights_cursorlocation, r_editlights_cursorgrid.value * 0.5f, 1, 1, 1, 1);
1468 }
1469
1470 void R_Shadow_DrawCursor(void)
1471 {
1472         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursorCallback, NULL, 0);
1473 }
1474
1475 void R_Shadow_UpdateLightingMode(void)
1476 {
1477         r_shadow_lightingmode = 0;
1478         if (r_shadow_realtime.integer)
1479         {
1480                 if (r_shadow_worldlightchain)
1481                         r_shadow_lightingmode = 2;
1482                 else
1483                         r_shadow_lightingmode = 1;
1484         }
1485 }
1486
1487 void R_Shadow_UpdateWorldLightSelection(void)
1488 {
1489         if (r_editlights.integer)
1490         {
1491                 R_Shadow_SelectLightInView();
1492                 R_Shadow_SetCursorLocationForView();
1493                 R_Shadow_DrawCursor();
1494         }
1495         else
1496                 R_Shadow_SelectLight(NULL);
1497 }
1498
1499 void R_Shadow_EditLights_Clear_f(void)
1500 {
1501         R_Shadow_ClearWorldLights();
1502 }
1503
1504 void R_Shadow_EditLights_Reload_f(void)
1505 {
1506         if (cl.worldmodel)
1507         {
1508                 R_Shadow_ClearWorldLights();
1509                 R_Shadow_LoadWorldLights();
1510         }
1511 }
1512
1513 void R_Shadow_EditLights_Save_f(void)
1514 {
1515         if (cl.worldmodel)
1516                 R_Shadow_SaveWorldLights();
1517 }
1518
1519 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
1520 {
1521         R_Shadow_ClearWorldLights();
1522         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
1523 }
1524
1525 void R_Shadow_EditLights_ImportLightsFile_f(void)
1526 {
1527         R_Shadow_ClearWorldLights();
1528         R_Shadow_LoadLightsFile();
1529 }
1530
1531 void R_Shadow_EditLights_Spawn_f(void)
1532 {
1533         vec3_t origin, color;
1534         vec_t radius;
1535         int style;
1536         const char *cubemapname;
1537         if (!r_editlights.integer)
1538         {
1539                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1540                 return;
1541         }
1542         if (Cmd_Argc() <= 7)
1543         {
1544                 radius = 200;
1545                 color[0] = color[1] = color[2] = 1;
1546                 style = 0;
1547                 cubemapname = NULL;
1548                 if (Cmd_Argc() >= 2)
1549                 {
1550                         radius = atof(Cmd_Argv(1));
1551                         if (Cmd_Argc() >= 3)
1552                         {
1553                                 color[0] = atof(Cmd_Argv(2));
1554                                 color[1] = color[0];
1555                                 color[2] = color[0];
1556                                 if (Cmd_Argc() >= 5)
1557                                 {
1558                                         color[1] = atof(Cmd_Argv(3));
1559                                         color[2] = atof(Cmd_Argv(4));
1560                                         if (Cmd_Argc() >= 6)
1561                                         {
1562                                                 style = atoi(Cmd_Argv(5));
1563                                                 if (Cmd_Argc() >= 7)
1564                                                         cubemapname = Cmd_Argv(6);
1565                                         }
1566                                 }
1567                         }
1568                 }
1569                 if (cubemapname && !cubemapname[0])
1570                         cubemapname = NULL;
1571                 if (radius >= 16 && color[0] >= 0 && color[1] >= 0 && color[2] >= 0 && style >= 0 && style < 256 && (color[0] >= 0.1 || color[1] >= 0.1 || color[2] >= 0.1))
1572                 {
1573                         VectorCopy(r_editlights_cursorlocation, origin);
1574                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1575                         return;
1576                 }
1577         }
1578         Con_Printf("usage: r_editlights_spawn radius red green blue [style [cubemap]]\n");
1579 }
1580
1581 void R_Shadow_EditLights_Edit_f(void)
1582 {
1583         vec3_t origin, color;
1584         vec_t radius;
1585         int style;
1586         const char *cubemapname;
1587         if (!r_editlights.integer)
1588         {
1589                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1590                 return;
1591         }
1592         if (!r_shadow_selectedlight)
1593         {
1594                 Con_Printf("No selected light.\n");
1595                 return;
1596         }
1597         if (Cmd_Argc() <= 7)
1598         {
1599                 radius = 200;
1600                 color[0] = color[1] = color[2] = 1;
1601                 style = 0;
1602                 cubemapname = NULL;
1603                 if (Cmd_Argc() >= 2)
1604                 {
1605                         radius = atof(Cmd_Argv(1));
1606                         if (Cmd_Argc() >= 3)
1607                         {
1608                                 color[0] = atof(Cmd_Argv(2));
1609                                 color[1] = color[0];
1610                                 color[2] = color[0];
1611                                 if (Cmd_Argc() >= 5)
1612                                 {
1613                                         color[1] = atof(Cmd_Argv(3));
1614                                         color[2] = atof(Cmd_Argv(4));
1615                                         if (Cmd_Argc() >= 6)
1616                                         {
1617                                                 style = atoi(Cmd_Argv(5));
1618                                                 if (Cmd_Argc() >= 7)
1619                                                         cubemapname = Cmd_Argv(6);
1620                                         }
1621                                 }
1622                         }
1623                 }
1624                 if (cubemapname && !cubemapname[0])
1625                         cubemapname = NULL;
1626                 if (radius >= 16 && color[0] >= 0 && color[1] >= 0 && color[2] >= 0 && style >= 0 && style < 256 && (color[0] >= 0.1 || color[1] >= 0.1 || color[2] >= 0.1))
1627                 {
1628                         VectorCopy(r_shadow_selectedlight->origin, origin);
1629                         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1630                         r_shadow_selectedlight = NULL;
1631                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1632                         return;
1633                 }
1634         }
1635         Con_Printf("usage: r_editlights_edit radius red green blue [style [cubemap]]\n");
1636 }
1637
1638 void R_Shadow_EditLights_Remove_f(void)
1639 {
1640         if (!r_editlights.integer)
1641         {
1642                 Con_Printf("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
1643                 return;
1644         }
1645         if (!r_shadow_selectedlight)
1646         {
1647                 Con_Printf("No selected light.\n");
1648                 return;
1649         }
1650         R_Shadow_FreeSelectedWorldLight();
1651 }
1652
1653 void R_Shadow_EditLights_Init(void)
1654 {
1655         Cvar_RegisterVariable(&r_editlights);
1656         Cvar_RegisterVariable(&r_editlights_cursordistance);
1657         Cvar_RegisterVariable(&r_editlights_cursorpushback);
1658         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
1659         Cvar_RegisterVariable(&r_editlights_cursorgrid);
1660         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f);
1661         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f);
1662         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f);
1663         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f);
1664         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f);
1665         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f);
1666         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f);
1667         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f);
1668 }