]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
glossmap textures are now brighter (no change to forced gloss brightness)
[xonotic/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] = 64;
366         data[1] = 64;
367         data[2] = 64;
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_ClearWorldLights();
458                 r_shadow_reloadlights = false;
459                 R_Shadow_LoadWorldLights();
460                 if (r_shadow_worldlightchain == NULL)
461                 {
462                         R_Shadow_LoadLightsFile();
463                         if (r_shadow_worldlightchain == NULL)
464                                 R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
465                 }
466         }
467
468         memset(&m, 0, sizeof(m));
469         m.blendfunc1 = GL_ONE;
470         m.blendfunc2 = GL_ZERO;
471         R_Mesh_State(&m);
472         GL_Color(0, 0, 0, 1);
473         r_shadowstage = SHADOWSTAGE_NONE;
474 }
475
476 void R_Shadow_Stage_ShadowVolumes(void)
477 {
478         rmeshstate_t m;
479         memset(&m, 0, sizeof(m));
480         R_Mesh_TextureState(&m);
481         GL_Color(1, 1, 1, 1);
482         qglColorMask(0, 0, 0, 0);
483         qglDisable(GL_BLEND);
484         qglDepthMask(0);
485         qglDepthFunc(GL_LESS);
486         qglEnable(GL_STENCIL_TEST);
487         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
488         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
489         qglEnable(GL_CULL_FACE);
490         qglEnable(GL_DEPTH_TEST);
491         r_shadowstage = SHADOWSTAGE_STENCIL;
492         qglClear(GL_STENCIL_BUFFER_BIT);
493 }
494
495 void R_Shadow_Stage_Light(void)
496 {
497         rmeshstate_t m;
498         memset(&m, 0, sizeof(m));
499         R_Mesh_TextureState(&m);
500         qglActiveTexture(GL_TEXTURE0_ARB);
501
502         qglEnable(GL_BLEND);
503         qglBlendFunc(GL_ONE, GL_ONE);
504         GL_Color(1, 1, 1, 1);
505         qglColorMask(1, 1, 1, 1);
506         qglDepthMask(0);
507         qglDepthFunc(GL_EQUAL);
508         qglEnable(GL_STENCIL_TEST);
509         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
510         // only draw light where this geometry was already rendered AND the
511         // stencil is 128 (values other than this mean shadow)
512         qglStencilFunc(GL_EQUAL, 128, 0xFF);
513         qglEnable(GL_CULL_FACE);
514         qglEnable(GL_DEPTH_TEST);
515         r_shadowstage = SHADOWSTAGE_LIGHT;
516 }
517
518 void R_Shadow_Stage_End(void)
519 {
520         rmeshstate_t m;
521         // attempt to restore state to what Mesh_State thinks it is
522         qglDisable(GL_BLEND);
523         qglBlendFunc(GL_ONE, GL_ZERO);
524         qglDepthMask(1);
525         // now restore the rest of the state to normal
526         GL_Color(1, 1, 1, 1);
527         qglColorMask(1, 1, 1, 1);
528         qglDisable(GL_SCISSOR_TEST);
529         qglDepthFunc(GL_LEQUAL);
530         qglDisable(GL_STENCIL_TEST);
531         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
532         qglStencilFunc(GL_ALWAYS, 128, 0xFF);
533         qglEnable(GL_CULL_FACE);
534         qglEnable(GL_DEPTH_TEST);
535         // force mesh state to reset by using various combinations of features
536         memset(&m, 0, sizeof(m));
537         m.blendfunc1 = GL_SRC_ALPHA;
538         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
539         R_Mesh_State(&m);
540         m.blendfunc1 = GL_ONE;
541         m.blendfunc2 = GL_ZERO;
542         R_Mesh_State(&m);
543         r_shadowstage = SHADOWSTAGE_NONE;
544 }
545
546 int R_Shadow_ScissorForBBoxAndSphere(const float *mins, const float *maxs, const float *origin, float radius)
547 {
548         int i, ix1, iy1, ix2, iy2;
549         float x1, y1, x2, y2, x, y;
550         vec3_t smins, smaxs;
551         vec4_t v, v2;
552         if (!r_shadow_scissor.integer)
553                 return false;
554         // if view is inside the box, just say yes it's visible
555         if (r_origin[0] >= mins[0] && r_origin[0] <= maxs[0]
556          && r_origin[1] >= mins[1] && r_origin[1] <= maxs[1]
557          && r_origin[2] >= mins[2] && r_origin[2] <= maxs[2])
558         {
559                 qglDisable(GL_SCISSOR_TEST);
560                 return false;
561         }
562         VectorSubtract(r_origin, origin, v);
563         if (DotProduct(v, v) < radius * radius)
564         {
565                 qglDisable(GL_SCISSOR_TEST);
566                 return false;
567         }
568         // create viewspace bbox
569         for (i = 0;i < 8;i++)
570         {
571                 v[0] = ((i & 1) ? mins[0] : maxs[0]) - r_origin[0];
572                 v[1] = ((i & 2) ? mins[1] : maxs[1]) - r_origin[1];
573                 v[2] = ((i & 4) ? mins[2] : maxs[2]) - r_origin[2];
574                 v2[0] = DotProduct(v, vright);
575                 v2[1] = DotProduct(v, vup);
576                 v2[2] = DotProduct(v, vpn);
577                 if (i)
578                 {
579                         if (smins[0] > v2[0]) smins[0] = v2[0];
580                         if (smaxs[0] < v2[0]) smaxs[0] = v2[0];
581                         if (smins[1] > v2[1]) smins[1] = v2[1];
582                         if (smaxs[1] < v2[1]) smaxs[1] = v2[1];
583                         if (smins[2] > v2[2]) smins[2] = v2[2];
584                         if (smaxs[2] < v2[2]) smaxs[2] = v2[2];
585                 }
586                 else
587                 {
588                         smins[0] = smaxs[0] = v2[0];
589                         smins[1] = smaxs[1] = v2[1];
590                         smins[2] = smaxs[2] = v2[2];
591                 }
592         }
593         // now we have a bbox in viewspace
594         // clip it to the viewspace version of the sphere
595         v[0] = origin[0] - r_origin[0];
596         v[1] = origin[1] - r_origin[1];
597         v[2] = origin[2] - r_origin[2];
598         v2[0] = DotProduct(v, vright);
599         v2[1] = DotProduct(v, vup);
600         v2[2] = DotProduct(v, vpn);
601         if (smins[0] < v2[0] - radius) smins[0] = v2[0] - radius;
602         if (smaxs[0] < v2[0] - radius) smaxs[0] = v2[0] + radius;
603         if (smins[1] < v2[1] - radius) smins[1] = v2[1] - radius;
604         if (smaxs[1] < v2[1] - radius) smaxs[1] = v2[1] + radius;
605         if (smins[2] < v2[2] - radius) smins[2] = v2[2] - radius;
606         if (smaxs[2] < v2[2] - radius) smaxs[2] = v2[2] + radius;
607         // clip it to the view plane
608         if (smins[2] < 1)
609                 smins[2] = 1;
610         // return true if that culled the box
611         if (smins[2] >= smaxs[2])
612                 return true;
613         // ok some of it is infront of the view, transform each corner back to
614         // worldspace and then to screenspace and make screen rect
615         for (i = 0;i < 8;i++)
616         {
617                 v2[0] = (i & 1) ? smins[0] : smaxs[0];
618                 v2[1] = (i & 2) ? smins[1] : smaxs[1];
619                 v2[2] = (i & 4) ? smins[2] : smaxs[2];
620                 v[0] = v2[0] * vright[0] + v2[1] * vup[0] + v2[2] * vpn[0] + r_origin[0];
621                 v[1] = v2[0] * vright[1] + v2[1] * vup[1] + v2[2] * vpn[1] + r_origin[1];
622                 v[2] = v2[0] * vright[2] + v2[1] * vup[2] + v2[2] * vpn[2] + r_origin[2];
623                 v[3] = 1.0f;
624                 GL_TransformToScreen(v, v2);
625                 //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]);
626                 x = v2[0];
627                 y = v2[1];
628                 if (i)
629                 {
630                         if (x1 > x) x1 = x;
631                         if (x2 < x) x2 = x;
632                         if (y1 > y) y1 = y;
633                         if (y2 < y) y2 = y;
634                 }
635                 else
636                 {
637                         x1 = x2 = x;
638                         y1 = y2 = y;
639                 }
640         }
641         /*
642         // this code doesn't handle boxes with any points behind view properly
643         x1 = 1000;x2 = -1000;
644         y1 = 1000;y2 = -1000;
645         for (i = 0;i < 8;i++)
646         {
647                 v[0] = (i & 1) ? mins[0] : maxs[0];
648                 v[1] = (i & 2) ? mins[1] : maxs[1];
649                 v[2] = (i & 4) ? mins[2] : maxs[2];
650                 v[3] = 1.0f;
651                 GL_TransformToScreen(v, v2);
652                 //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]);
653                 if (v2[2] > 0)
654                 {
655                         x = v2[0];
656                         y = v2[1];
657
658                         if (x1 > x) x1 = x;
659                         if (x2 < x) x2 = x;
660                         if (y1 > y) y1 = y;
661                         if (y2 < y) y2 = y;
662                 }
663         }
664         */
665         ix1 = x1 - 1.0f;
666         iy1 = y1 - 1.0f;
667         ix2 = x2 + 1.0f;
668         iy2 = y2 + 1.0f;
669         //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2);
670         if (ix1 < r_refdef.x) ix1 = r_refdef.x;
671         if (iy1 < r_refdef.y) iy1 = r_refdef.y;
672         if (ix2 > r_refdef.x + r_refdef.width) ix2 = r_refdef.x + r_refdef.width;
673         if (iy2 > r_refdef.y + r_refdef.height) iy2 = r_refdef.y + r_refdef.height;
674         if (ix2 <= ix1 || iy2 <= iy1)
675                 return true;
676         // set up the scissor rectangle
677         qglScissor(ix1, iy1, ix2 - ix1, iy2 - iy1);
678         qglEnable(GL_SCISSOR_TEST);
679         return false;
680 }
681
682 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)
683 {
684         int i;
685         float lightvec[3], iradius;
686         iradius = 0.5f / lightradius;
687         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out2d += 4, out1d += 4)
688         {
689                 VectorSubtract(vertex, relativelightorigin, lightvec);
690                 out2d[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
691                 out2d[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
692                 out2d[2] = 0;
693                 out1d[0] = 0.5f + DotProduct(normals, lightvec) * iradius;
694                 out1d[1] = 0.5f;
695                 out1d[2] = 0;
696         }
697 }
698
699 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)
700 {
701         int i;
702         float lightvec[3], iradius;
703         iradius = 0.5f / lightradius;
704         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
705         {
706                 VectorSubtract(vertex, relativelightorigin, lightvec);
707                 out[0] = 0.5f + DotProduct(svectors, lightvec) * iradius;
708                 out[1] = 0.5f + DotProduct(tvectors, lightvec) * iradius;
709                 out[2] = 0.5f + DotProduct(normals, lightvec) * iradius;
710         }
711 }
712
713 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)
714 {
715         int i;
716         float lightdir[3];
717         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
718         {
719                 VectorSubtract(vertex, relativelightorigin, lightdir);
720                 // the cubemap normalizes this for us
721                 out[0] = DotProduct(svectors, lightdir);
722                 out[1] = DotProduct(tvectors, lightdir);
723                 out[2] = DotProduct(normals, lightdir);
724         }
725 }
726
727 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)
728 {
729         int i;
730         float lightdir[3], eyedir[3], halfdir[3], lightdirlen, iradius;
731         iradius = 0.5f / lightradius;
732         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
733         {
734                 VectorSubtract(vertex, relativelightorigin, lightdir);
735                 // this is used later to make the attenuation correct
736                 lightdirlen = sqrt(DotProduct(lightdir, lightdir)) * iradius;
737                 VectorNormalizeFast(lightdir);
738                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
739                 VectorNormalizeFast(eyedir);
740                 VectorAdd(lightdir, eyedir, halfdir);
741                 VectorNormalizeFast(halfdir);
742                 out[0] = 0.5f + DotProduct(svectors, halfdir) * lightdirlen;
743                 out[1] = 0.5f + DotProduct(tvectors, halfdir) * lightdirlen;
744                 out[2] = 0.5f + DotProduct(normals, halfdir) * lightdirlen;
745         }
746 }
747
748 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)
749 {
750         int i;
751         float lightdir[3], eyedir[3], halfdir[3];
752         for (i = 0;i < numverts;i++, vertex += 4, svectors += 4, tvectors += 4, normals += 4, out += 4)
753         {
754                 VectorSubtract(vertex, relativelightorigin, lightdir);
755                 VectorNormalizeFast(lightdir);
756                 VectorSubtract(vertex, relativeeyeorigin, eyedir);
757                 VectorNormalizeFast(eyedir);
758                 VectorAdd(lightdir, eyedir, halfdir);
759                 // the cubemap normalizes this for us
760                 out[0] = DotProduct(svectors, halfdir);
761                 out[1] = DotProduct(tvectors, halfdir);
762                 out[2] = DotProduct(normals, halfdir);
763         }
764 }
765
766 void R_Shadow_GenTexCoords_LightCubeMap(float *out, int numverts, const float *vertex, const vec3_t relativelightorigin)
767 {
768         int i;
769         // FIXME: this needs to be written
770         // this code assumes the vertices are in worldspace (a false assumption)
771         for (i = 0;i < numverts;i++, vertex += 4, out += 4)
772                 VectorSubtract(vertex, relativelightorigin, out);
773 }
774
775 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)
776 {
777         int renders, mult;
778         float scale, colorscale;
779         rmeshstate_t m;
780         memset(&m, 0, sizeof(m));
781         if (!bumptexture)
782                 bumptexture = r_shadow_blankbumptexture;
783         // colorscale accounts for how much we multiply the brightness during combine
784         // mult is how many times the final pass of the lighting will be
785         // performed to get more brightness than otherwise possible
786         // limit mult to 64 for sanity sake
787         if (r_textureunits.integer >= 4)
788         {
789                 // 4 texture no3D combine path, two pass
790                 m.tex[0] = R_GetTexture(bumptexture);
791                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
792                 m.texcombinergb[0] = GL_REPLACE;
793                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
794                 m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture);
795                 m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture);
796                 R_Mesh_TextureState(&m);
797                 qglColorMask(0,0,0,1);
798                 qglDisable(GL_BLEND);
799                 GL_Color(1,1,1,1);
800                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
801                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
802                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[2], varray_texcoord[3], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
803                 R_Mesh_Draw(numverts, numtriangles, elements);
804
805                 m.tex[0] = R_GetTexture(basetexture);
806                 m.texcubemap[1] = R_GetTexture(lightcubemap);
807                 m.texcombinergb[0] = GL_MODULATE;
808                 m.texcombinergb[1] = GL_MODULATE;
809                 m.tex[2] = 0;
810                 m.tex[3] = 0;
811                 R_Mesh_TextureState(&m);
812                 qglColorMask(1,1,1,1);
813                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
814                 qglEnable(GL_BLEND);
815                 if (lightcubemap)
816                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
817
818                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
819                 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]);
820                 colorscale *= scale;
821                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
822                 for (renders = 0;renders < mult;renders++)
823                         R_Mesh_Draw(numverts, numtriangles, elements);
824         }
825         else
826         {
827                 // 2 texture no3D combine path, three pass
828                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
829                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
830                 R_Mesh_TextureState(&m);
831                 qglColorMask(0,0,0,1);
832                 qglDisable(GL_BLEND);
833                 GL_Color(1,1,1,1);
834                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
835                 R_Mesh_Draw(numverts, numtriangles, elements);
836
837                 m.tex[0] = R_GetTexture(bumptexture);
838                 m.tex[1] = 0;
839                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
840                 m.texcombinergb[0] = GL_REPLACE;
841                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
842                 R_Mesh_TextureState(&m);
843                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
844                 qglEnable(GL_BLEND);
845                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
846                 R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin);
847                 R_Mesh_Draw(numverts, numtriangles, elements);
848
849                 m.tex[0] = R_GetTexture(basetexture);
850                 m.texcubemap[1] = R_GetTexture(lightcubemap);
851                 m.texcombinergb[0] = GL_MODULATE;
852                 m.texcombinergb[1] = GL_MODULATE;
853                 R_Mesh_TextureState(&m);
854                 qglColorMask(1,1,1,1);
855                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
856                 if (lightcubemap)
857                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
858
859                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
860                 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]);
861                 colorscale *= scale;
862                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
863                 for (renders = 0;renders < mult;renders++)
864                         R_Mesh_Draw(numverts, numtriangles, elements);
865         }
866 }
867
868 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)
869 {
870         int renders, mult;
871         float scale, colorscale;
872         rmeshstate_t m;
873         memset(&m, 0, sizeof(m));
874         if (!bumptexture)
875                 bumptexture = r_shadow_blankbumptexture;
876         if (!glosstexture)
877                 glosstexture = r_shadow_blankglosstexture;
878         if (r_shadow_gloss.integer >= 2 || (r_shadow_gloss.integer >= 1 && glosstexture != r_shadow_blankglosstexture))
879         {
880                 // 2 texture no3D combine path, five pass
881                 memset(&m, 0, sizeof(m));
882
883                 m.tex[0] = R_GetTexture(bumptexture);
884                 m.texcubemap[1] = R_GetTexture(r_shadow_normalscubetexture);
885                 m.texcombinergb[1] = GL_DOT3_RGBA_ARB;
886                 R_Mesh_TextureState(&m);
887                 qglColorMask(0,0,0,1);
888                 qglDisable(GL_BLEND);
889                 GL_Color(1,1,1,1);
890                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
891                 R_Shadow_GenTexCoords_Specular_NormalCubeMap(varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, relativeeyeorigin);
892                 R_Mesh_Draw(numverts, numtriangles, elements);
893
894                 m.tex[0] = 0;
895                 m.texcubemap[1] = 0;
896                 m.texcombinergb[1] = GL_MODULATE;
897                 R_Mesh_TextureState(&m);
898                 // square alpha in framebuffer a few times to make it shiny
899                 qglBlendFunc(GL_ZERO, GL_DST_ALPHA);
900                 qglEnable(GL_BLEND);
901                 // these comments are a test run through this math for intensity 0.5
902                 // 0.5 * 0.5 = 0.25
903                 R_Mesh_Draw(numverts, numtriangles, elements);
904                 // 0.25 * 0.25 = 0.0625
905                 R_Mesh_Draw(numverts, numtriangles, elements);
906                 // 0.0625 * 0.0625 = 0.00390625
907                 R_Mesh_Draw(numverts, numtriangles, elements);
908
909                 m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture);
910                 m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture);
911                 R_Mesh_TextureState(&m);
912                 qglBlendFunc(GL_DST_ALPHA, GL_ZERO);
913                 R_Shadow_GenTexCoords_Attenuation2D1D(varray_texcoord[0], varray_texcoord[1], numverts, varray_vertex, svectors, tvectors, normals, relativelightorigin, lightradius);
914                 R_Mesh_Draw(numverts, numtriangles, elements);
915
916                 m.tex[0] = R_GetTexture(glosstexture);
917                 m.texcubemap[1] = R_GetTexture(lightcubemap);
918                 R_Mesh_TextureState(&m);
919                 qglColorMask(1,1,1,1);
920                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
921                 memcpy(varray_texcoord[0], texcoords, numverts * sizeof(float[4]));
922                 if (lightcubemap)
923                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
924
925                 colorscale = r_colorscale * 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 cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "0.8"};
946 worldlight_t *r_shadow_worldlightchain;
947 worldlight_t *r_shadow_selectedlight;
948 vec3_t r_editlights_cursorlocation;
949
950 static int castshadowcount = 1;
951 void R_Shadow_NewWorldLight(vec3_t origin, float radius, vec3_t color, int style, const char *cubemapname)
952 {
953         int i, j, k, l, maxverts, *mark, tris;
954         float *verts, *v, f, temp[3], radius2;
955         //float projectdistance, *v0, *v1, temp2[3], temp3[3];
956         worldlight_t *e;
957         shadowmesh_t *mesh, *castmesh;
958         mleaf_t *leaf;
959         msurface_t *surf;
960         qbyte *pvs;
961         surfmesh_t *surfmesh;
962
963         if (radius < 15 || DotProduct(color, color) < 0.03)
964         {
965                 Con_Printf("R_Shadow_NewWorldLight: refusing to create a light too small/dim\n");
966                 return;
967         }
968
969         e = Mem_Alloc(r_shadow_mempool, sizeof(worldlight_t));
970         VectorCopy(origin, e->origin);
971         VectorCopy(color, e->light);
972         e->lightradius = radius;
973         VectorCopy(origin, e->mins);
974         VectorCopy(origin, e->maxs);
975         e->cullradius = 0;
976         e->style = style;
977         e->next = r_shadow_worldlightchain;
978         r_shadow_worldlightchain = e;
979         if (cubemapname)
980         {
981                 e->cubemapname = Mem_Alloc(r_shadow_mempool, strlen(cubemapname) + 1);
982                 strcpy(e->cubemapname, cubemapname);
983                 // FIXME: add cubemap loading (and don't load a cubemap twice)
984         }
985         if (cl.worldmodel)
986         {
987                 castshadowcount++;
988                 leaf = Mod_PointInLeaf(origin, cl.worldmodel);
989                 pvs = Mod_LeafPVS(leaf, cl.worldmodel);
990                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
991                 {
992                         if (pvs[i >> 3] & (1 << (i & 7)))
993                         {
994                                 VectorCopy(origin, temp);
995                                 if (temp[0] < leaf->mins[0]) temp[0] = leaf->mins[0];
996                                 if (temp[0] > leaf->maxs[0]) temp[0] = leaf->maxs[0];
997                                 if (temp[1] < leaf->mins[1]) temp[1] = leaf->mins[1];
998                                 if (temp[1] > leaf->maxs[1]) temp[1] = leaf->maxs[1];
999                                 if (temp[2] < leaf->mins[2]) temp[2] = leaf->mins[2];
1000                                 if (temp[2] > leaf->maxs[2]) temp[2] = leaf->maxs[2];
1001                                 VectorSubtract(temp, origin, temp);
1002                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1003                                 {
1004                                         leaf->worldnodeframe = castshadowcount;
1005                                         for (j = 0, mark = leaf->firstmarksurface;j < leaf->nummarksurfaces;j++, mark++)
1006                                         {
1007                                                 surf = cl.worldmodel->surfaces + *mark;
1008                                                 if (surf->castshadow != castshadowcount)
1009                                                 {
1010                                                         f = DotProduct(e->origin, surf->plane->normal) - surf->plane->dist;
1011                                                         if (surf->flags & SURF_PLANEBACK)
1012                                                                 f = -f;
1013                                                         if (f > 0 && f < e->lightradius)
1014                                                         {
1015                                                                 temp[0] = bound(surf->poly_mins[0], e->origin[0], surf->poly_maxs[0]) - e->origin[0];
1016                                                                 temp[1] = bound(surf->poly_mins[1], e->origin[1], surf->poly_maxs[1]) - e->origin[1];
1017                                                                 temp[2] = bound(surf->poly_mins[2], e->origin[2], surf->poly_maxs[2]) - e->origin[2];
1018                                                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1019                                                                         surf->castshadow = castshadowcount;
1020                                                         }
1021                                                 }
1022                                         }
1023                                 }
1024                         }
1025                 }
1026
1027                 e->numleafs = 0;
1028                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1029                         if (leaf->worldnodeframe == castshadowcount)
1030                                 e->numleafs++;
1031                 e->numsurfaces = 0;
1032                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1033                         if (surf->castshadow == castshadowcount)
1034                                 e->numsurfaces++;
1035
1036                 if (e->numleafs)
1037                         e->leafs = Mem_Alloc(r_shadow_mempool, e->numleafs * sizeof(mleaf_t *));
1038                 if (e->numsurfaces)
1039                         e->surfaces = Mem_Alloc(r_shadow_mempool, e->numsurfaces * sizeof(msurface_t *));
1040                 e->numleafs = 0;
1041                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1042                         if (leaf->worldnodeframe == castshadowcount)
1043                                 e->leafs[e->numleafs++] = leaf;
1044                 e->numsurfaces = 0;
1045                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1046                         if (surf->castshadow == castshadowcount)
1047                                 e->surfaces[e->numsurfaces++] = surf;
1048                 // find bounding box and sphere of lit surfaces
1049                 // (these will be used for creating a shape to clip the light)
1050                 radius2 = 0;
1051                 VectorCopy(e->origin, e->mins);
1052                 VectorCopy(e->origin, e->maxs);
1053                 for (j = 0;j < e->numsurfaces;j++)
1054                 {
1055                         surf = e->surfaces[j];
1056                         for (k = 0, v = surf->poly_verts;k < surf->poly_numverts;k++, v += 3)
1057                         {
1058                                 if (e->mins[0] > v[0]) e->mins[0] = v[0];if (e->maxs[0] < v[0]) e->maxs[0] = v[0];
1059                                 if (e->mins[1] > v[1]) e->mins[1] = v[1];if (e->maxs[1] < v[1]) e->maxs[1] = v[1];
1060                                 if (e->mins[2] > v[2]) e->mins[2] = v[2];if (e->maxs[2] < v[2]) e->maxs[2] = v[2];
1061                                 VectorSubtract(v, e->origin, temp);
1062                                 f = DotProduct(temp, temp);
1063                                 if (radius2 < f)
1064                                         radius2 = f;
1065                         }
1066                 }
1067                 e->cullradius = sqrt(radius2);
1068                 if (e->cullradius > e->lightradius)
1069                         e->cullradius = e->lightradius;
1070                 if (e->mins[0] < e->origin[0] - e->lightradius) e->mins[0] = e->origin[0] - e->lightradius;
1071                 if (e->maxs[0] > e->origin[0] + e->lightradius) e->maxs[0] = e->origin[0] + e->lightradius;
1072                 if (e->mins[1] < e->origin[1] - e->lightradius) e->mins[1] = e->origin[1] - e->lightradius;
1073                 if (e->maxs[1] > e->origin[1] + e->lightradius) e->maxs[1] = e->origin[1] + e->lightradius;
1074                 if (e->mins[2] < e->origin[2] - e->lightradius) e->mins[2] = e->origin[2] - e->lightradius;
1075                 if (e->maxs[2] > e->origin[2] + e->lightradius) e->maxs[2] = e->origin[2] + e->lightradius;
1076                 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);
1077                 // clip shadow volumes against eachother to remove unnecessary
1078                 // polygons (and sections of polygons)
1079                 maxverts = 256;
1080                 verts = NULL;
1081                 castshadowcount++;
1082                 for (j = 0;j < e->numsurfaces;j++)
1083                 {
1084                         surf = e->surfaces[j];
1085                         if (surf->flags & SURF_SHADOWCAST)
1086                         {
1087                                 surf->castshadow = castshadowcount;
1088                                 if (maxverts < surf->poly_numverts)
1089                                         maxverts = surf->poly_numverts;
1090                         }
1091                 }
1092                 e->shadowvolume = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1093                 // make a mesh to cast a shadow volume from
1094                 castmesh = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1095                 for (j = 0;j < e->numsurfaces;j++)
1096                         if (e->surfaces[j]->castshadow == castshadowcount)
1097                                 for (surfmesh = e->surfaces[j]->mesh;surfmesh;surfmesh = surfmesh->chain)
1098                                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, castmesh, surfmesh->numverts, surfmesh->verts, surfmesh->numtriangles, surfmesh->index);
1099                 castmesh = Mod_ShadowMesh_Finish(r_shadow_mempool, castmesh);
1100
1101                 // cast shadow volume from castmesh
1102                 for (mesh = castmesh;mesh;mesh = mesh->next)
1103                 {
1104                         R_Shadow_ResizeTriangleFacingLight(castmesh->numtriangles);
1105                         R_Shadow_ResizeShadowElements(castmesh->numtriangles);
1106
1107                         if (maxverts < castmesh->numverts * 2)
1108                         {
1109                                 maxverts = castmesh->numverts * 2;
1110                                 if (verts)
1111                                         Mem_Free(verts);
1112                                 verts = NULL;
1113                         }
1114                         if (verts == NULL && maxverts > 0)
1115                                 verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1116
1117                         // now that we have the buffers big enough, construct shadow volume mesh
1118                         memcpy(verts, castmesh->verts, castmesh->numverts * sizeof(float[4]));
1119                         R_Shadow_ProjectVertices(verts, castmesh->numverts, e->origin, 1000000.0f);//, e->lightradius);
1120                         R_Shadow_MakeTriangleShadowFlags(castmesh->elements, verts, castmesh->numtriangles, trianglefacinglight, e->origin, e->lightradius);
1121                         tris = R_Shadow_BuildShadowVolumeTriangles(castmesh->elements, castmesh->neighbors, castmesh->numtriangles, castmesh->numverts, trianglefacinglight, shadowelements);
1122                         // add the constructed shadow volume mesh
1123                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, e->shadowvolume, castmesh->numverts, verts, tris, shadowelements);
1124                 }
1125                 // we're done with castmesh now
1126                 Mod_ShadowMesh_Free(castmesh);
1127                 e->shadowvolume = Mod_ShadowMesh_Finish(r_shadow_mempool, e->shadowvolume);
1128                 for (l = 0, mesh = e->shadowvolume;mesh;mesh = mesh->next)
1129                         l += mesh->numtriangles;
1130                 Con_Printf("static shadow volume built containing %i triangles\n", l);
1131         }
1132 }
1133
1134 void R_Shadow_FreeWorldLight(worldlight_t *light)
1135 {
1136         worldlight_t **lightpointer;
1137         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
1138         if (*lightpointer != light)
1139                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain\n");
1140         *lightpointer = light->next;
1141         if (light->cubemapname)
1142                 Mem_Free(light->cubemapname);
1143         if (light->shadowvolume)
1144                 Mod_ShadowMesh_Free(light->shadowvolume);
1145         if (light->surfaces)
1146                 Mem_Free(light->surfaces);
1147         if (light->leafs)
1148                 Mem_Free(light->leafs);
1149         Mem_Free(light);
1150 }
1151
1152 void R_Shadow_ClearWorldLights(void)
1153 {
1154         while (r_shadow_worldlightchain)
1155                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
1156         r_shadow_selectedlight = NULL;
1157 }
1158
1159 void R_Shadow_SelectLight(worldlight_t *light)
1160 {
1161         if (r_shadow_selectedlight)
1162                 r_shadow_selectedlight->selected = false;
1163         r_shadow_selectedlight = light;
1164         if (r_shadow_selectedlight)
1165                 r_shadow_selectedlight->selected = true;
1166 }
1167
1168 void R_Shadow_FreeSelectedWorldLight(void)
1169 {
1170         if (r_shadow_selectedlight)
1171         {
1172                 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1173                 r_shadow_selectedlight = NULL;
1174         }
1175 }
1176
1177 void R_DrawLightSprite(int texnum, const vec3_t origin, vec_t scale, float cr, float cg, float cb, float ca)
1178 {
1179         rmeshstate_t m;
1180         float diff[3];
1181
1182         if (fogenabled)
1183         {
1184                 VectorSubtract(origin, r_origin, diff);
1185                 ca *= 1 - exp(fogdensity/DotProduct(diff,diff));
1186         }
1187
1188         memset(&m, 0, sizeof(m));
1189         m.blendfunc1 = GL_SRC_ALPHA;
1190         m.blendfunc2 = GL_ONE;
1191         m.tex[0] = texnum;
1192         R_Mesh_Matrix(&r_identitymatrix);
1193         R_Mesh_State(&m);
1194
1195         GL_Color(cr * r_colorscale, cg * r_colorscale, cb * r_colorscale, ca);
1196         varray_texcoord[0][ 0] = 0;varray_texcoord[0][ 1] = 0;
1197         varray_texcoord[0][ 4] = 0;varray_texcoord[0][ 5] = 1;
1198         varray_texcoord[0][ 8] = 1;varray_texcoord[0][ 9] = 1;
1199         varray_texcoord[0][12] = 1;varray_texcoord[0][13] = 0;
1200         varray_vertex[0] = origin[0] - vright[0] * scale - vup[0] * scale;
1201         varray_vertex[1] = origin[1] - vright[1] * scale - vup[1] * scale;
1202         varray_vertex[2] = origin[2] - vright[2] * scale - vup[2] * scale;
1203         varray_vertex[4] = origin[0] - vright[0] * scale + vup[0] * scale;
1204         varray_vertex[5] = origin[1] - vright[1] * scale + vup[1] * scale;
1205         varray_vertex[6] = origin[2] - vright[2] * scale + vup[2] * scale;
1206         varray_vertex[8] = origin[0] + vright[0] * scale + vup[0] * scale;
1207         varray_vertex[9] = origin[1] + vright[1] * scale + vup[1] * scale;
1208         varray_vertex[10] = origin[2] + vright[2] * scale + vup[2] * scale;
1209         varray_vertex[12] = origin[0] + vright[0] * scale - vup[0] * scale;
1210         varray_vertex[13] = origin[1] + vright[1] * scale - vup[1] * scale;
1211         varray_vertex[14] = origin[2] + vright[2] * scale - vup[2] * scale;
1212         R_Mesh_Draw(4, 2, polygonelements);
1213 }
1214
1215 void R_Shadow_DrawCursorCallback(const void *calldata1, int calldata2)
1216 {
1217         cachepic_t *pic;
1218         pic = Draw_CachePic("gfx/crosshair1.tga");
1219         if (pic)
1220                 R_DrawLightSprite(R_GetTexture(pic->tex), r_editlights_cursorlocation, r_editlights_cursorgrid.value * 0.5f, 1, 1, 1, 0.5);
1221 }
1222
1223 void R_Shadow_DrawLightSpriteCallback(const void *calldata1, int calldata2)
1224 {
1225         float intensity;
1226         const worldlight_t *light;
1227         light = calldata1;
1228         intensity = 0.5;
1229         if (light->selected)
1230                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
1231         if (light->shadowvolume)
1232                 R_DrawLightSprite(calldata2, light->origin, 8, intensity, intensity, intensity, 0.5);
1233         else
1234                 R_DrawLightSprite(calldata2, light->origin, 8, intensity * 0.5, intensity * 0.5, intensity * 0.5, 0.5);
1235 }
1236
1237 void R_Shadow_DrawLightSprites(void)
1238 {
1239         int i, texnums[5];
1240         cachepic_t *pic;
1241         worldlight_t *light;
1242
1243         for (i = 0;i < 5;i++)
1244         {
1245                 pic = Draw_CachePic(va("gfx/crosshair%i.tga", i + 1));
1246                 if (pic)
1247                         texnums[i] = R_GetTexture(pic->tex);
1248                 else
1249                         texnums[i] = 0;
1250         }
1251
1252         for (light = r_shadow_worldlightchain;light;light = light->next)
1253                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSpriteCallback, light, texnums[((int) light) % 5]);
1254         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursorCallback, NULL, 0);
1255 }
1256
1257 void R_Shadow_SelectLightInView(void)
1258 {
1259         float bestrating, rating, temp[3];
1260         worldlight_t *best, *light;
1261         best = NULL;
1262         bestrating = 0;
1263         for (light = r_shadow_worldlightchain;light;light = light->next)
1264         {
1265                 VectorSubtract(light->origin, r_refdef.vieworg, temp);
1266                 rating = (DotProduct(temp, vpn) / sqrt(DotProduct(temp, temp)));
1267                 if (rating >= 0.95)
1268                 {
1269                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
1270                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.vieworg, NULL, NULL, 0, true, NULL) == 1.0f)
1271                         {
1272                                 bestrating = rating;
1273                                 best = light;
1274                         }
1275                 }
1276         }
1277         R_Shadow_SelectLight(best);
1278 }
1279
1280 void R_Shadow_LoadWorldLights(void)
1281 {
1282         int n, a, style;
1283         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1284         float origin[3], radius, color[3];
1285         COM_StripExtension(cl.worldmodel->name, name);
1286         strcat(name, ".rtlights");
1287         lightsstring = COM_LoadFile(name, false);
1288         if (lightsstring)
1289         {
1290                 s = lightsstring;
1291                 n = 0;
1292                 while (*s)
1293                 {
1294                         t = s;
1295                         while (*s && *s != '\n')
1296                                 s++;
1297                         if (!*s)
1298                                 break;
1299                         *s = 0;
1300                         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);
1301                         if (a < 9)
1302                                 cubemapname[0] = 0;
1303                         *s = '\n';
1304                         if (a < 8)
1305                         {
1306                                 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);
1307                                 break;
1308                         }
1309                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1310                         s++;
1311                         n++;
1312                 }
1313                 if (*s)
1314                         Con_Printf("invalid rtlights file \"%s\"\n", name);
1315                 Mem_Free(lightsstring);
1316         }
1317 }
1318
1319 void R_Shadow_SaveWorldLights(void)
1320 {
1321         worldlight_t *light;
1322         int bufchars, bufmaxchars;
1323         char *buf, *oldbuf;
1324         char name[MAX_QPATH];
1325         char line[1024];
1326         if (!r_shadow_worldlightchain)
1327                 return;
1328         COM_StripExtension(cl.worldmodel->name, name);
1329         strcat(name, ".rtlights");
1330         bufchars = bufmaxchars = 0;
1331         buf = NULL;
1332         for (light = r_shadow_worldlightchain;light;light = light->next)
1333         {
1334                 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 : "");
1335                 if (bufchars + strlen(line) > bufmaxchars)
1336                 {
1337                         bufmaxchars = bufchars + strlen(line) + 2048;
1338                         oldbuf = buf;
1339                         buf = Mem_Alloc(r_shadow_mempool, bufmaxchars);
1340                         if (oldbuf)
1341                         {
1342                                 if (bufchars)
1343                                         memcpy(buf, oldbuf, bufchars);
1344                                 Mem_Free(oldbuf);
1345                         }
1346                 }
1347                 if (strlen(line))
1348                 {
1349                         memcpy(buf + bufchars, line, strlen(line));
1350                         bufchars += strlen(line);
1351                 }
1352         }
1353         if (bufchars)
1354                 COM_WriteFile(name, buf, bufchars);
1355         if (buf)
1356                 Mem_Free(buf);
1357 }
1358
1359 void R_Shadow_LoadLightsFile(void)
1360 {
1361         int n, a, style;
1362         char name[MAX_QPATH], *lightsstring, *s, *t;
1363         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
1364         COM_StripExtension(cl.worldmodel->name, name);
1365         strcat(name, ".lights");
1366         lightsstring = COM_LoadFile(name, false);
1367         if (lightsstring)
1368         {
1369                 s = lightsstring;
1370                 n = 0;
1371                 while (*s)
1372                 {
1373                         t = s;
1374                         while (*s && *s != '\n')
1375                                 s++;
1376                         if (!*s)
1377                                 break;
1378                         *s = 0;
1379                         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);
1380                         *s = '\n';
1381                         if (a < 14)
1382                         {
1383                                 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);
1384                                 break;
1385                         }
1386                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
1387                         radius = bound(15, radius, 4096);
1388                         VectorScale(color, (1.0f / (8388608.0f)), color);
1389                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1390                         s++;
1391                         n++;
1392                 }
1393                 if (*s)
1394                         Con_Printf("invalid lights file \"%s\"\n", name);
1395                 Mem_Free(lightsstring);
1396         }
1397 }
1398
1399 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
1400 {
1401         int entnum, style, islight;
1402         char key[256], value[1024];
1403         float origin[3], radius, color[3], light, scale, originhack[3], overridecolor[3];
1404         const char *data;
1405
1406         data = cl.worldmodel->entities;
1407         if (!data)
1408                 return;
1409         for (entnum = 0;COM_ParseToken(&data) && com_token[0] == '{';entnum++)
1410         {
1411                 light = 0;
1412                 origin[0] = origin[1] = origin[2] = 0;
1413                 originhack[0] = originhack[1] = originhack[2] = 0;
1414                 color[0] = color[1] = color[2] = 1;
1415                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
1416                 scale = 1;
1417                 style = 0;
1418                 islight = false;
1419                 while (1)
1420                 {
1421                         if (!COM_ParseToken(&data))
1422                                 break; // error
1423                         if (com_token[0] == '}')
1424                                 break; // end of entity
1425                         if (com_token[0] == '_')
1426                                 strcpy(key, com_token + 1);
1427                         else
1428                                 strcpy(key, com_token);
1429                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
1430                                 key[strlen(key)-1] = 0;
1431                         if (!COM_ParseToken(&data))
1432                                 break; // error
1433                         strcpy(value, com_token);
1434
1435                         // now that we have the key pair worked out...
1436                         if (!strcmp("light", key))
1437                                 light = atof(value);
1438                         else if (!strcmp("origin", key))
1439                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
1440                         else if (!strcmp("color", key))
1441                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
1442                         else if (!strcmp("wait", key))
1443                                 scale = atof(value);
1444                         else if (!strcmp("classname", key))
1445                         {
1446                                 if (!strncmp(value, "light", 5))
1447                                 {
1448                                         islight = true;
1449                                         if (!strcmp(value, "light_fluoro"))
1450                                         {
1451                                                 originhack[0] = 0;
1452                                                 originhack[1] = 0;
1453                                                 originhack[2] = 0;
1454                                                 overridecolor[0] = 1;
1455                                                 overridecolor[1] = 1;
1456                                                 overridecolor[2] = 1;
1457                                         }
1458                                         if (!strcmp(value, "light_fluorospark"))
1459                                         {
1460                                                 originhack[0] = 0;
1461                                                 originhack[1] = 0;
1462                                                 originhack[2] = 0;
1463                                                 overridecolor[0] = 1;
1464                                                 overridecolor[1] = 1;
1465                                                 overridecolor[2] = 1;
1466                                         }
1467                                         if (!strcmp(value, "light_globe"))
1468                                         {
1469                                                 originhack[0] = 0;
1470                                                 originhack[1] = 0;
1471                                                 originhack[2] = 0;
1472                                                 overridecolor[0] = 1;
1473                                                 overridecolor[1] = 0.8;
1474                                                 overridecolor[2] = 0.4;
1475                                         }
1476                                         if (!strcmp(value, "light_flame_large_yellow"))
1477                                         {
1478                                                 originhack[0] = 0;
1479                                                 originhack[1] = 0;
1480                                                 originhack[2] = 48;
1481                                                 overridecolor[0] = 1;
1482                                                 overridecolor[1] = 0.7;
1483                                                 overridecolor[2] = 0.2;
1484                                         }
1485                                         if (!strcmp(value, "light_flame_small_yellow"))
1486                                         {
1487                                                 originhack[0] = 0;
1488                                                 originhack[1] = 0;
1489                                                 originhack[2] = 40;
1490                                                 overridecolor[0] = 1;
1491                                                 overridecolor[1] = 0.7;
1492                                                 overridecolor[2] = 0.2;
1493                                         }
1494                                         if (!strcmp(value, "light_torch_small_white"))
1495                                         {
1496                                                 originhack[0] = 0;
1497                                                 originhack[1] = 0;
1498                                                 originhack[2] = 40;
1499                                                 overridecolor[0] = 1;
1500                                                 overridecolor[1] = 0.9;
1501                                                 overridecolor[2] = 0.7;
1502                                         }
1503                                         if (!strcmp(value, "light_torch_small_walltorch"))
1504                                         {
1505                                                 originhack[0] = 0;
1506                                                 originhack[1] = 0;
1507                                                 originhack[2] = 40;
1508                                                 overridecolor[0] = 1;
1509                                                 overridecolor[1] = 0.7;
1510                                                 overridecolor[2] = 0.2;
1511                                         }
1512                                 }
1513                         }
1514                         else if (!strcmp("style", key))
1515                                 style = atoi(value);
1516                 }
1517                 if (light <= 0 && islight)
1518                         light = 300;
1519                 radius = bound(15, light * r_editlights_quakelightsizescale.value / scale, 1048576);
1520                 light = sqrt(bound(0, light, 1048576)) * (1.0f / 16.0f);
1521                 if (color[0] == 1 && color[1] == 1 && color[2] == 1)
1522                         VectorCopy(overridecolor, color);
1523                 VectorScale(color, light, color);
1524                 VectorAdd(origin, originhack, origin);
1525                 if (radius >= 15)
1526                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1527         }
1528 }
1529
1530
1531 void R_Shadow_SetCursorLocationForView(void)
1532 {
1533         vec_t dist, push, frac;
1534         vec3_t dest, endpos, normal;
1535         VectorMA(r_refdef.vieworg, r_editlights_cursordistance.value, vpn, dest);
1536         frac = CL_TraceLine(r_refdef.vieworg, dest, endpos, normal, 0, true, NULL);
1537         if (frac < 1)
1538         {
1539                 dist = frac * r_editlights_cursordistance.value;
1540                 push = r_editlights_cursorpushback.value;
1541                 if (push > dist)
1542                         push = dist;
1543                 push = -push;
1544                 VectorMA(endpos, push, vpn, endpos);
1545                 VectorMA(endpos, r_editlights_cursorpushoff.value, normal, endpos);
1546         }
1547         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1548         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1549         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1550 }
1551
1552 void R_Shadow_UpdateLightingMode(void)
1553 {
1554         r_shadow_lightingmode = 0;
1555         if (r_shadow_realtime.integer)
1556         {
1557                 if (r_shadow_worldlightchain)
1558                         r_shadow_lightingmode = 2;
1559                 else
1560                         r_shadow_lightingmode = 1;
1561         }
1562 }
1563
1564 void R_Shadow_UpdateWorldLightSelection(void)
1565 {
1566         if (r_editlights.integer)
1567         {
1568                 R_Shadow_SetCursorLocationForView();
1569                 R_Shadow_SelectLightInView();
1570                 R_Shadow_DrawLightSprites();
1571         }
1572         else
1573                 R_Shadow_SelectLight(NULL);
1574 }
1575
1576 void R_Shadow_EditLights_Clear_f(void)
1577 {
1578         R_Shadow_ClearWorldLights();
1579 }
1580
1581 void R_Shadow_EditLights_Reload_f(void)
1582 {
1583         r_shadow_reloadlights = true;
1584 }
1585
1586 void R_Shadow_EditLights_Save_f(void)
1587 {
1588         if (cl.worldmodel)
1589                 R_Shadow_SaveWorldLights();
1590 }
1591
1592 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
1593 {
1594         R_Shadow_ClearWorldLights();
1595         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
1596 }
1597
1598 void R_Shadow_EditLights_ImportLightsFile_f(void)
1599 {
1600         R_Shadow_ClearWorldLights();
1601         R_Shadow_LoadLightsFile();
1602 }
1603
1604 void R_Shadow_EditLights_Spawn_f(void)
1605 {
1606         vec3_t origin, color;
1607         vec_t radius;
1608         int style;
1609         const char *cubemapname;
1610         if (!r_editlights.integer)
1611         {
1612                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1613                 return;
1614         }
1615         if (Cmd_Argc() <= 7)
1616         {
1617                 radius = 200;
1618                 color[0] = color[1] = color[2] = 1;
1619                 style = 0;
1620                 cubemapname = NULL;
1621                 if (Cmd_Argc() >= 2)
1622                 {
1623                         radius = atof(Cmd_Argv(1));
1624                         if (Cmd_Argc() >= 3)
1625                         {
1626                                 color[0] = atof(Cmd_Argv(2));
1627                                 color[1] = color[0];
1628                                 color[2] = color[0];
1629                                 if (Cmd_Argc() >= 5)
1630                                 {
1631                                         color[1] = atof(Cmd_Argv(3));
1632                                         color[2] = atof(Cmd_Argv(4));
1633                                         if (Cmd_Argc() >= 6)
1634                                         {
1635                                                 style = atoi(Cmd_Argv(5));
1636                                                 if (Cmd_Argc() >= 7)
1637                                                         cubemapname = Cmd_Argv(6);
1638                                         }
1639                                 }
1640                         }
1641                 }
1642                 if (cubemapname && !cubemapname[0])
1643                         cubemapname = NULL;
1644                 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))
1645                 {
1646                         VectorCopy(r_editlights_cursorlocation, origin);
1647                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1648                         return;
1649                 }
1650         }
1651         Con_Printf("usage: r_editlights_spawn radius red green blue [style [cubemap]]\n");
1652 }
1653
1654 void R_Shadow_EditLights_Edit_f(void)
1655 {
1656         vec3_t origin, color;
1657         vec_t radius;
1658         int style;
1659         const char *cubemapname;
1660         if (!r_editlights.integer)
1661         {
1662                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1663                 return;
1664         }
1665         if (!r_shadow_selectedlight)
1666         {
1667                 Con_Printf("No selected light.\n");
1668                 return;
1669         }
1670         if (Cmd_Argc() <= 7)
1671         {
1672                 radius = 200;
1673                 color[0] = color[1] = color[2] = 1;
1674                 style = 0;
1675                 cubemapname = NULL;
1676                 if (Cmd_Argc() >= 2)
1677                 {
1678                         radius = atof(Cmd_Argv(1));
1679                         if (Cmd_Argc() >= 3)
1680                         {
1681                                 color[0] = atof(Cmd_Argv(2));
1682                                 color[1] = color[0];
1683                                 color[2] = color[0];
1684                                 if (Cmd_Argc() >= 5)
1685                                 {
1686                                         color[1] = atof(Cmd_Argv(3));
1687                                         color[2] = atof(Cmd_Argv(4));
1688                                         if (Cmd_Argc() >= 6)
1689                                         {
1690                                                 style = atoi(Cmd_Argv(5));
1691                                                 if (Cmd_Argc() >= 7)
1692                                                         cubemapname = Cmd_Argv(6);
1693                                         }
1694                                 }
1695                         }
1696                 }
1697                 if (cubemapname && !cubemapname[0])
1698                         cubemapname = NULL;
1699                 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))
1700                 {
1701                         VectorCopy(r_shadow_selectedlight->origin, origin);
1702                         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1703                         r_shadow_selectedlight = NULL;
1704                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1705                         return;
1706                 }
1707         }
1708         Con_Printf("usage: r_editlights_edit radius red green blue [style [cubemap]]\n");
1709 }
1710
1711 void R_Shadow_EditLights_Remove_f(void)
1712 {
1713         if (!r_editlights.integer)
1714         {
1715                 Con_Printf("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
1716                 return;
1717         }
1718         if (!r_shadow_selectedlight)
1719         {
1720                 Con_Printf("No selected light.\n");
1721                 return;
1722         }
1723         R_Shadow_FreeSelectedWorldLight();
1724 }
1725
1726 void R_Shadow_EditLights_Init(void)
1727 {
1728         Cvar_RegisterVariable(&r_editlights);
1729         Cvar_RegisterVariable(&r_editlights_cursordistance);
1730         Cvar_RegisterVariable(&r_editlights_cursorpushback);
1731         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
1732         Cvar_RegisterVariable(&r_editlights_cursorgrid);
1733         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
1734         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f);
1735         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f);
1736         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f);
1737         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f);
1738         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f);
1739         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f);
1740         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f);
1741         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f);
1742 }