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