]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - r_shadow.c
tiny cleanup to RotatePointAroundVector (uses a VectorCopy instead of 3 lines)
[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_lightattenuationpower = {0, "r_shadow_lightattenuationpower", "2"};
33 cvar_t r_shadow_lightattenuationscale = {0, "r_shadow_lightattenuationscale", "2"};
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", "4"};
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) - 1.0f;
433                         v[1] = (y + 0.5f) * (2.0f / 128.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 | TEXF_MIPMAP, 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, mult;
784         float scale, colorscale;
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,1);
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                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
825                 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]);
826                 colorscale *= scale;
827                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
828                 for (renders = 0;renders < mult;renders++)
829                         R_Mesh_Draw(numverts, numtriangles, elements);
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,1);
861                 qglBlendFunc(GL_DST_ALPHA, GL_ONE);
862                 if (lightcubemap)
863                         R_Shadow_GenTexCoords_LightCubeMap(varray_texcoord[1], numverts, varray_vertex, relativelightorigin);
864
865                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
866                 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]);
867                 colorscale *= scale;
868                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
869                 for (renders = 0;renders < mult;renders++)
870                         R_Mesh_Draw(numverts, numtriangles, elements);
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, mult;
877         float scale, colorscale;
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,1);
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                 colorscale = r_colorscale * r_shadow_lightintensityscale.value;
932                 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]);
933                 colorscale *= scale;
934                 GL_Color(lightcolor[0] * colorscale, lightcolor[1] * colorscale, lightcolor[2] * colorscale, 1);
935                 for (renders = 0;renders < mult;renders++)
936                         R_Mesh_Draw(numverts, numtriangles, elements);
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 worldlight_t *r_shadow_worldlightchain;
953 worldlight_t *r_shadow_selectedlight;
954 vec3_t r_editlights_cursorlocation;
955
956 static int castshadowcount = 1;
957 void R_Shadow_NewWorldLight(vec3_t origin, float radius, vec3_t color, int style, const char *cubemapname)
958 {
959         int i, j, k, l, maxverts, *mark, tris;
960         float *verts, *v, f, temp[3], radius2;
961         //float projectdistance, *v0, *v1, temp2[3], temp3[3];
962         worldlight_t *e;
963         shadowmesh_t *mesh, *castmesh;
964         mleaf_t *leaf;
965         msurface_t *surf;
966         qbyte *pvs;
967         surfmesh_t *surfmesh;
968
969         if (radius < 15 || DotProduct(color, color) < 0.03)
970         {
971                 Con_Printf("R_Shadow_NewWorldLight: refusing to create a light too small/dim\n");
972                 return;
973         }
974
975         e = Mem_Alloc(r_shadow_mempool, sizeof(worldlight_t));
976         VectorCopy(origin, e->origin);
977         VectorCopy(color, e->light);
978         e->lightradius = radius;
979         VectorCopy(origin, e->mins);
980         VectorCopy(origin, e->maxs);
981         e->cullradius = 0;
982         e->style = style;
983         e->next = r_shadow_worldlightchain;
984         r_shadow_worldlightchain = e;
985         if (cubemapname)
986         {
987                 e->cubemapname = Mem_Alloc(r_shadow_mempool, strlen(cubemapname) + 1);
988                 strcpy(e->cubemapname, cubemapname);
989                 // FIXME: add cubemap loading (and don't load a cubemap twice)
990         }
991         if (cl.worldmodel)
992         {
993                 castshadowcount++;
994                 leaf = Mod_PointInLeaf(origin, cl.worldmodel);
995                 pvs = Mod_LeafPVS(leaf, cl.worldmodel);
996                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
997                 {
998                         if (pvs[i >> 3] & (1 << (i & 7)))
999                         {
1000                                 VectorCopy(origin, temp);
1001                                 if (temp[0] < leaf->mins[0]) temp[0] = leaf->mins[0];
1002                                 if (temp[0] > leaf->maxs[0]) temp[0] = leaf->maxs[0];
1003                                 if (temp[1] < leaf->mins[1]) temp[1] = leaf->mins[1];
1004                                 if (temp[1] > leaf->maxs[1]) temp[1] = leaf->maxs[1];
1005                                 if (temp[2] < leaf->mins[2]) temp[2] = leaf->mins[2];
1006                                 if (temp[2] > leaf->maxs[2]) temp[2] = leaf->maxs[2];
1007                                 VectorSubtract(temp, origin, temp);
1008                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1009                                 {
1010                                         leaf->worldnodeframe = castshadowcount;
1011                                         for (j = 0, mark = leaf->firstmarksurface;j < leaf->nummarksurfaces;j++, mark++)
1012                                         {
1013                                                 surf = cl.worldmodel->surfaces + *mark;
1014                                                 if (surf->castshadow != castshadowcount)
1015                                                 {
1016                                                         f = DotProduct(e->origin, surf->plane->normal) - surf->plane->dist;
1017                                                         if (surf->flags & SURF_PLANEBACK)
1018                                                                 f = -f;
1019                                                         if (f > 0 && f < e->lightradius)
1020                                                         {
1021                                                                 temp[0] = bound(surf->poly_mins[0], e->origin[0], surf->poly_maxs[0]) - e->origin[0];
1022                                                                 temp[1] = bound(surf->poly_mins[1], e->origin[1], surf->poly_maxs[1]) - e->origin[1];
1023                                                                 temp[2] = bound(surf->poly_mins[2], e->origin[2], surf->poly_maxs[2]) - e->origin[2];
1024                                                                 if (DotProduct(temp, temp) < e->lightradius * e->lightradius)
1025                                                                         surf->castshadow = castshadowcount;
1026                                                         }
1027                                                 }
1028                                         }
1029                                 }
1030                         }
1031                 }
1032
1033                 e->numleafs = 0;
1034                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1035                         if (leaf->worldnodeframe == castshadowcount)
1036                                 e->numleafs++;
1037                 e->numsurfaces = 0;
1038                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1039                         if (surf->castshadow == castshadowcount)
1040                                 e->numsurfaces++;
1041
1042                 if (e->numleafs)
1043                         e->leafs = Mem_Alloc(r_shadow_mempool, e->numleafs * sizeof(mleaf_t *));
1044                 if (e->numsurfaces)
1045                         e->surfaces = Mem_Alloc(r_shadow_mempool, e->numsurfaces * sizeof(msurface_t *));
1046                 e->numleafs = 0;
1047                 for (i = 0, leaf = cl.worldmodel->leafs + 1;i < cl.worldmodel->numleafs;i++, leaf++)
1048                         if (leaf->worldnodeframe == castshadowcount)
1049                                 e->leafs[e->numleafs++] = leaf;
1050                 e->numsurfaces = 0;
1051                 for (i = 0, surf = cl.worldmodel->surfaces + cl.worldmodel->firstmodelsurface;i < cl.worldmodel->nummodelsurfaces;i++, surf++)
1052                         if (surf->castshadow == castshadowcount)
1053                                 e->surfaces[e->numsurfaces++] = surf;
1054                 // find bounding box and sphere of lit surfaces
1055                 // (these will be used for creating a shape to clip the light)
1056                 radius2 = 0;
1057                 VectorCopy(e->origin, e->mins);
1058                 VectorCopy(e->origin, e->maxs);
1059                 for (j = 0;j < e->numsurfaces;j++)
1060                 {
1061                         surf = e->surfaces[j];
1062                         for (k = 0, v = surf->poly_verts;k < surf->poly_numverts;k++, v += 3)
1063                         {
1064                                 if (e->mins[0] > v[0]) e->mins[0] = v[0];if (e->maxs[0] < v[0]) e->maxs[0] = v[0];
1065                                 if (e->mins[1] > v[1]) e->mins[1] = v[1];if (e->maxs[1] < v[1]) e->maxs[1] = v[1];
1066                                 if (e->mins[2] > v[2]) e->mins[2] = v[2];if (e->maxs[2] < v[2]) e->maxs[2] = v[2];
1067                                 VectorSubtract(v, e->origin, temp);
1068                                 f = DotProduct(temp, temp);
1069                                 if (radius2 < f)
1070                                         radius2 = f;
1071                         }
1072                 }
1073                 e->cullradius = sqrt(radius2);
1074                 if (e->cullradius > e->lightradius)
1075                         e->cullradius = e->lightradius;
1076                 if (e->mins[0] < e->origin[0] - e->lightradius) e->mins[0] = e->origin[0] - e->lightradius;
1077                 if (e->maxs[0] > e->origin[0] + e->lightradius) e->maxs[0] = e->origin[0] + e->lightradius;
1078                 if (e->mins[1] < e->origin[1] - e->lightradius) e->mins[1] = e->origin[1] - e->lightradius;
1079                 if (e->maxs[1] > e->origin[1] + e->lightradius) e->maxs[1] = e->origin[1] + e->lightradius;
1080                 if (e->mins[2] < e->origin[2] - e->lightradius) e->mins[2] = e->origin[2] - e->lightradius;
1081                 if (e->maxs[2] > e->origin[2] + e->lightradius) e->maxs[2] = e->origin[2] + e->lightradius;
1082                 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);
1083                 // clip shadow volumes against eachother to remove unnecessary
1084                 // polygons (and sections of polygons)
1085                 maxverts = 256;
1086                 verts = NULL;
1087                 castshadowcount++;
1088                 for (j = 0;j < e->numsurfaces;j++)
1089                 {
1090                         surf = e->surfaces[j];
1091                         if (surf->flags & SURF_SHADOWCAST)
1092                         {
1093                                 surf->castshadow = castshadowcount;
1094                                 if (maxverts < surf->poly_numverts)
1095                                         maxverts = surf->poly_numverts;
1096                         }
1097                 }
1098                 e->shadowvolume = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1099                 // make a mesh to cast a shadow volume from
1100                 castmesh = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768);
1101                 for (j = 0;j < e->numsurfaces;j++)
1102                         if (e->surfaces[j]->castshadow == castshadowcount)
1103                                 for (surfmesh = e->surfaces[j]->mesh;surfmesh;surfmesh = surfmesh->chain)
1104                                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, castmesh, surfmesh->numverts, surfmesh->verts, surfmesh->numtriangles, surfmesh->index);
1105                 castmesh = Mod_ShadowMesh_Finish(r_shadow_mempool, castmesh);
1106
1107                 // cast shadow volume from castmesh
1108                 for (mesh = castmesh;mesh;mesh = mesh->next)
1109                 {
1110                         R_Shadow_ResizeTriangleFacingLight(castmesh->numtriangles);
1111                         R_Shadow_ResizeShadowElements(castmesh->numtriangles);
1112
1113                         if (maxverts < castmesh->numverts * 2)
1114                         {
1115                                 maxverts = castmesh->numverts * 2;
1116                                 if (verts)
1117                                         Mem_Free(verts);
1118                                 verts = NULL;
1119                         }
1120                         if (verts == NULL && maxverts > 0)
1121                                 verts = Mem_Alloc(r_shadow_mempool, maxverts * sizeof(float[4]));
1122
1123                         // now that we have the buffers big enough, construct shadow volume mesh
1124                         memcpy(verts, castmesh->verts, castmesh->numverts * sizeof(float[4]));
1125                         R_Shadow_ProjectVertices(verts, castmesh->numverts, e->origin, 1000000.0f);//, e->lightradius);
1126                         R_Shadow_MakeTriangleShadowFlags(castmesh->elements, verts, castmesh->numtriangles, trianglefacinglight, e->origin, e->lightradius);
1127                         tris = R_Shadow_BuildShadowVolumeTriangles(castmesh->elements, castmesh->neighbors, castmesh->numtriangles, castmesh->numverts, trianglefacinglight, shadowelements);
1128                         // add the constructed shadow volume mesh
1129                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, e->shadowvolume, castmesh->numverts, verts, tris, shadowelements);
1130                 }
1131                 // we're done with castmesh now
1132                 Mod_ShadowMesh_Free(castmesh);
1133                 e->shadowvolume = Mod_ShadowMesh_Finish(r_shadow_mempool, e->shadowvolume);
1134                 for (l = 0, mesh = e->shadowvolume;mesh;mesh = mesh->next)
1135                         l += mesh->numtriangles;
1136                 Con_Printf("static shadow volume built containing %i triangles\n", l);
1137         }
1138 }
1139
1140 void R_Shadow_FreeWorldLight(worldlight_t *light)
1141 {
1142         worldlight_t **lightpointer;
1143         for (lightpointer = &r_shadow_worldlightchain;*lightpointer && *lightpointer != light;lightpointer = &(*lightpointer)->next);
1144         if (*lightpointer != light)
1145                 Sys_Error("R_Shadow_FreeWorldLight: light not linked into chain\n");
1146         *lightpointer = light->next;
1147         if (light->cubemapname)
1148                 Mem_Free(light->cubemapname);
1149         if (light->shadowvolume)
1150                 Mod_ShadowMesh_Free(light->shadowvolume);
1151         if (light->surfaces)
1152                 Mem_Free(light->surfaces);
1153         if (light->leafs)
1154                 Mem_Free(light->leafs);
1155         Mem_Free(light);
1156 }
1157
1158 void R_Shadow_ClearWorldLights(void)
1159 {
1160         while (r_shadow_worldlightchain)
1161                 R_Shadow_FreeWorldLight(r_shadow_worldlightchain);
1162         r_shadow_selectedlight = NULL;
1163 }
1164
1165 void R_Shadow_SelectLight(worldlight_t *light)
1166 {
1167         if (r_shadow_selectedlight)
1168                 r_shadow_selectedlight->selected = false;
1169         r_shadow_selectedlight = light;
1170         if (r_shadow_selectedlight)
1171                 r_shadow_selectedlight->selected = true;
1172 }
1173
1174 void R_Shadow_FreeSelectedWorldLight(void)
1175 {
1176         if (r_shadow_selectedlight)
1177         {
1178                 R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1179                 r_shadow_selectedlight = NULL;
1180         }
1181 }
1182
1183 void R_DrawLightSprite(int texnum, const vec3_t origin, vec_t scale, float cr, float cg, float cb, float ca)
1184 {
1185         rmeshstate_t m;
1186         float diff[3];
1187
1188         if (fogenabled)
1189         {
1190                 VectorSubtract(origin, r_origin, diff);
1191                 ca *= 1 - exp(fogdensity/DotProduct(diff,diff));
1192         }
1193
1194         memset(&m, 0, sizeof(m));
1195         m.blendfunc1 = GL_SRC_ALPHA;
1196         m.blendfunc2 = GL_ONE;
1197         m.tex[0] = texnum;
1198         R_Mesh_Matrix(&r_identitymatrix);
1199         R_Mesh_State(&m);
1200
1201         GL_Color(cr * r_colorscale, cg * r_colorscale, cb * r_colorscale, ca);
1202         varray_texcoord[0][ 0] = 0;varray_texcoord[0][ 1] = 0;
1203         varray_texcoord[0][ 4] = 0;varray_texcoord[0][ 5] = 1;
1204         varray_texcoord[0][ 8] = 1;varray_texcoord[0][ 9] = 1;
1205         varray_texcoord[0][12] = 1;varray_texcoord[0][13] = 0;
1206         varray_vertex[0] = origin[0] - vright[0] * scale - vup[0] * scale;
1207         varray_vertex[1] = origin[1] - vright[1] * scale - vup[1] * scale;
1208         varray_vertex[2] = origin[2] - vright[2] * scale - vup[2] * scale;
1209         varray_vertex[4] = origin[0] - vright[0] * scale + vup[0] * scale;
1210         varray_vertex[5] = origin[1] - vright[1] * scale + vup[1] * scale;
1211         varray_vertex[6] = origin[2] - vright[2] * scale + vup[2] * scale;
1212         varray_vertex[8] = origin[0] + vright[0] * scale + vup[0] * scale;
1213         varray_vertex[9] = origin[1] + vright[1] * scale + vup[1] * scale;
1214         varray_vertex[10] = origin[2] + vright[2] * scale + vup[2] * scale;
1215         varray_vertex[12] = origin[0] + vright[0] * scale - vup[0] * scale;
1216         varray_vertex[13] = origin[1] + vright[1] * scale - vup[1] * scale;
1217         varray_vertex[14] = origin[2] + vright[2] * scale - vup[2] * scale;
1218         R_Mesh_Draw(4, 2, polygonelements);
1219 }
1220
1221 void R_Shadow_DrawCursorCallback(const void *calldata1, int calldata2)
1222 {
1223         cachepic_t *pic;
1224         pic = Draw_CachePic("gfx/crosshair1.tga");
1225         if (pic)
1226                 R_DrawLightSprite(R_GetTexture(pic->tex), r_editlights_cursorlocation, r_editlights_cursorgrid.value * 0.5f, 1, 1, 1, 0.5);
1227 }
1228
1229 void R_Shadow_DrawLightSpriteCallback(const void *calldata1, int calldata2)
1230 {
1231         float intensity;
1232         const worldlight_t *light;
1233         light = calldata1;
1234         intensity = 0.5;
1235         if (light->selected)
1236                 intensity = 0.75 + 0.25 * sin(realtime * M_PI * 4.0);
1237         if (light->shadowvolume)
1238                 R_DrawLightSprite(calldata2, light->origin, 8, intensity, intensity, intensity, 0.5);
1239         else
1240                 R_DrawLightSprite(calldata2, light->origin, 8, intensity * 0.5, intensity * 0.5, intensity * 0.5, 0.5);
1241 }
1242
1243 void R_Shadow_DrawLightSprites(void)
1244 {
1245         int i, texnums[5];
1246         cachepic_t *pic;
1247         worldlight_t *light;
1248
1249         for (i = 0;i < 5;i++)
1250         {
1251                 pic = Draw_CachePic(va("gfx/crosshair%i.tga", i + 1));
1252                 if (pic)
1253                         texnums[i] = R_GetTexture(pic->tex);
1254                 else
1255                         texnums[i] = 0;
1256         }
1257
1258         for (light = r_shadow_worldlightchain;light;light = light->next)
1259                 R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSpriteCallback, light, texnums[((int) light) % 5]);
1260         R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursorCallback, NULL, 0);
1261 }
1262
1263 void R_Shadow_SelectLightInView(void)
1264 {
1265         float bestrating, rating, temp[3];
1266         worldlight_t *best, *light;
1267         best = NULL;
1268         bestrating = 0;
1269         for (light = r_shadow_worldlightchain;light;light = light->next)
1270         {
1271                 VectorSubtract(light->origin, r_refdef.vieworg, temp);
1272                 rating = (DotProduct(temp, vpn) / sqrt(DotProduct(temp, temp)));
1273                 if (rating >= 0.95)
1274                 {
1275                         rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp)));
1276                         if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.vieworg, NULL, NULL, 0, true, NULL) == 1.0f)
1277                         {
1278                                 bestrating = rating;
1279                                 best = light;
1280                         }
1281                 }
1282         }
1283         R_Shadow_SelectLight(best);
1284 }
1285
1286 void R_Shadow_LoadWorldLights(void)
1287 {
1288         int n, a, style;
1289         char name[MAX_QPATH], cubemapname[MAX_QPATH], *lightsstring, *s, *t;
1290         float origin[3], radius, color[3];
1291         COM_StripExtension(cl.worldmodel->name, name);
1292         strcat(name, ".rtlights");
1293         lightsstring = COM_LoadFile(name, false);
1294         if (lightsstring)
1295         {
1296                 s = lightsstring;
1297                 n = 0;
1298                 while (*s)
1299                 {
1300                         t = s;
1301                         while (*s && *s != '\n')
1302                                 s++;
1303                         if (!*s)
1304                                 break;
1305                         *s = 0;
1306                         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);
1307                         if (a < 9)
1308                                 cubemapname[0] = 0;
1309                         *s = '\n';
1310                         if (a < 8)
1311                         {
1312                                 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);
1313                                 break;
1314                         }
1315                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1316                         s++;
1317                         n++;
1318                 }
1319                 if (*s)
1320                         Con_Printf("invalid rtlights file \"%s\"\n", name);
1321                 Mem_Free(lightsstring);
1322         }
1323 }
1324
1325 void R_Shadow_SaveWorldLights(void)
1326 {
1327         worldlight_t *light;
1328         int bufchars, bufmaxchars;
1329         char *buf, *oldbuf;
1330         char name[MAX_QPATH];
1331         char line[1024];
1332         if (!r_shadow_worldlightchain)
1333                 return;
1334         COM_StripExtension(cl.worldmodel->name, name);
1335         strcat(name, ".rtlights");
1336         bufchars = bufmaxchars = 0;
1337         buf = NULL;
1338         for (light = r_shadow_worldlightchain;light;light = light->next)
1339         {
1340                 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 : "");
1341                 if (bufchars + strlen(line) > bufmaxchars)
1342                 {
1343                         bufmaxchars = bufchars + strlen(line) + 2048;
1344                         oldbuf = buf;
1345                         buf = Mem_Alloc(r_shadow_mempool, bufmaxchars);
1346                         if (oldbuf)
1347                         {
1348                                 if (bufchars)
1349                                         memcpy(buf, oldbuf, bufchars);
1350                                 Mem_Free(oldbuf);
1351                         }
1352                 }
1353                 if (strlen(line))
1354                 {
1355                         memcpy(buf + bufchars, line, strlen(line));
1356                         bufchars += strlen(line);
1357                 }
1358         }
1359         if (bufchars)
1360                 COM_WriteFile(name, buf, bufchars);
1361         if (buf)
1362                 Mem_Free(buf);
1363 }
1364
1365 void R_Shadow_LoadLightsFile(void)
1366 {
1367         int n, a, style;
1368         char name[MAX_QPATH], *lightsstring, *s, *t;
1369         float origin[3], radius, color[3], subtract, spotdir[3], spotcone, falloff, distbias;
1370         COM_StripExtension(cl.worldmodel->name, name);
1371         strcat(name, ".lights");
1372         lightsstring = COM_LoadFile(name, false);
1373         if (lightsstring)
1374         {
1375                 s = lightsstring;
1376                 n = 0;
1377                 while (*s)
1378                 {
1379                         t = s;
1380                         while (*s && *s != '\n')
1381                                 s++;
1382                         if (!*s)
1383                                 break;
1384                         *s = 0;
1385                         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);
1386                         *s = '\n';
1387                         if (a < 14)
1388                         {
1389                                 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);
1390                                 break;
1391                         }
1392                         radius = sqrt(DotProduct(color, color) / (falloff * falloff * 8192.0f * 8192.0f));
1393                         radius = bound(15, radius, 4096);
1394                         VectorScale(color, (1.0f / (8388608.0f)), color);
1395                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1396                         s++;
1397                         n++;
1398                 }
1399                 if (*s)
1400                         Con_Printf("invalid lights file \"%s\"\n", name);
1401                 Mem_Free(lightsstring);
1402         }
1403 }
1404
1405 void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void)
1406 {
1407         int entnum, style, islight;
1408         char key[256], value[1024];
1409         float origin[3], radius, color[3], light, scale, originhack[3], overridecolor[3];
1410         const char *data;
1411
1412         data = cl.worldmodel->entities;
1413         if (!data)
1414                 return;
1415         for (entnum = 0;COM_ParseToken(&data) && com_token[0] == '{';entnum++)
1416         {
1417                 light = 0;
1418                 origin[0] = origin[1] = origin[2] = 0;
1419                 originhack[0] = originhack[1] = originhack[2] = 0;
1420                 color[0] = color[1] = color[2] = 1;
1421                 overridecolor[0] = overridecolor[1] = overridecolor[2] = 1;
1422                 scale = 1;
1423                 style = 0;
1424                 islight = false;
1425                 while (1)
1426                 {
1427                         if (!COM_ParseToken(&data))
1428                                 break; // error
1429                         if (com_token[0] == '}')
1430                                 break; // end of entity
1431                         if (com_token[0] == '_')
1432                                 strcpy(key, com_token + 1);
1433                         else
1434                                 strcpy(key, com_token);
1435                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
1436                                 key[strlen(key)-1] = 0;
1437                         if (!COM_ParseToken(&data))
1438                                 break; // error
1439                         strcpy(value, com_token);
1440
1441                         // now that we have the key pair worked out...
1442                         if (!strcmp("light", key))
1443                                 light = atof(value);
1444                         else if (!strcmp("origin", key))
1445                                 sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]);
1446                         else if (!strcmp("color", key))
1447                                 sscanf(value, "%f %f %f", &color[0], &color[1], &color[2]);
1448                         else if (!strcmp("wait", key))
1449                                 scale = atof(value);
1450                         else if (!strcmp("classname", key))
1451                         {
1452                                 if (!strncmp(value, "light", 5))
1453                                 {
1454                                         islight = true;
1455                                         if (!strcmp(value, "light_fluoro"))
1456                                         {
1457                                                 originhack[0] = 0;
1458                                                 originhack[1] = 0;
1459                                                 originhack[2] = 0;
1460                                                 overridecolor[0] = 1;
1461                                                 overridecolor[1] = 1;
1462                                                 overridecolor[2] = 1;
1463                                         }
1464                                         if (!strcmp(value, "light_fluorospark"))
1465                                         {
1466                                                 originhack[0] = 0;
1467                                                 originhack[1] = 0;
1468                                                 originhack[2] = 0;
1469                                                 overridecolor[0] = 1;
1470                                                 overridecolor[1] = 1;
1471                                                 overridecolor[2] = 1;
1472                                         }
1473                                         if (!strcmp(value, "light_globe"))
1474                                         {
1475                                                 originhack[0] = 0;
1476                                                 originhack[1] = 0;
1477                                                 originhack[2] = 0;
1478                                                 overridecolor[0] = 1;
1479                                                 overridecolor[1] = 0.8;
1480                                                 overridecolor[2] = 0.4;
1481                                         }
1482                                         if (!strcmp(value, "light_flame_large_yellow"))
1483                                         {
1484                                                 originhack[0] = 0;
1485                                                 originhack[1] = 0;
1486                                                 originhack[2] = 48;
1487                                                 overridecolor[0] = 1;
1488                                                 overridecolor[1] = 0.7;
1489                                                 overridecolor[2] = 0.2;
1490                                         }
1491                                         if (!strcmp(value, "light_flame_small_yellow"))
1492                                         {
1493                                                 originhack[0] = 0;
1494                                                 originhack[1] = 0;
1495                                                 originhack[2] = 40;
1496                                                 overridecolor[0] = 1;
1497                                                 overridecolor[1] = 0.7;
1498                                                 overridecolor[2] = 0.2;
1499                                         }
1500                                         if (!strcmp(value, "light_torch_small_white"))
1501                                         {
1502                                                 originhack[0] = 0;
1503                                                 originhack[1] = 0;
1504                                                 originhack[2] = 40;
1505                                                 overridecolor[0] = 1;
1506                                                 overridecolor[1] = 0.9;
1507                                                 overridecolor[2] = 0.7;
1508                                         }
1509                                         if (!strcmp(value, "light_torch_small_walltorch"))
1510                                         {
1511                                                 originhack[0] = 0;
1512                                                 originhack[1] = 0;
1513                                                 originhack[2] = 40;
1514                                                 overridecolor[0] = 1;
1515                                                 overridecolor[1] = 0.7;
1516                                                 overridecolor[2] = 0.2;
1517                                         }
1518                                 }
1519                         }
1520                         else if (!strcmp("style", key))
1521                                 style = atoi(value);
1522                 }
1523                 if (light <= 0 && islight)
1524                         light = 300;
1525                 radius = bound(15, light * r_editlights_quakelightsizescale.value / scale, 1048576);
1526                 light = sqrt(bound(0, light, 1048576)) * (1.0f / 16.0f);
1527                 if (color[0] == 1 && color[1] == 1 && color[2] == 1)
1528                         VectorCopy(overridecolor, color);
1529                 VectorScale(color, light, color);
1530                 VectorAdd(origin, originhack, origin);
1531                 if (radius >= 15)
1532                         R_Shadow_NewWorldLight(origin, radius, color, style, NULL);
1533         }
1534 }
1535
1536
1537 void R_Shadow_SetCursorLocationForView(void)
1538 {
1539         vec_t dist, push, frac;
1540         vec3_t dest, endpos, normal;
1541         VectorMA(r_refdef.vieworg, r_editlights_cursordistance.value, vpn, dest);
1542         frac = CL_TraceLine(r_refdef.vieworg, dest, endpos, normal, 0, true, NULL);
1543         if (frac < 1)
1544         {
1545                 dist = frac * r_editlights_cursordistance.value;
1546                 push = r_editlights_cursorpushback.value;
1547                 if (push > dist)
1548                         push = dist;
1549                 push = -push;
1550                 VectorMA(endpos, push, vpn, endpos);
1551                 VectorMA(endpos, r_editlights_cursorpushoff.value, normal, endpos);
1552         }
1553         r_editlights_cursorlocation[0] = floor(endpos[0] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1554         r_editlights_cursorlocation[1] = floor(endpos[1] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1555         r_editlights_cursorlocation[2] = floor(endpos[2] / r_editlights_cursorgrid.value + 0.5f) * r_editlights_cursorgrid.value;
1556 }
1557
1558 void R_Shadow_UpdateLightingMode(void)
1559 {
1560         r_shadow_lightingmode = 0;
1561         if (r_shadow_realtime.integer)
1562         {
1563                 if (r_shadow_worldlightchain)
1564                         r_shadow_lightingmode = 2;
1565                 else
1566                         r_shadow_lightingmode = 1;
1567         }
1568 }
1569
1570 void R_Shadow_UpdateWorldLightSelection(void)
1571 {
1572         if (r_editlights.integer)
1573         {
1574                 R_Shadow_SetCursorLocationForView();
1575                 R_Shadow_SelectLightInView();
1576                 R_Shadow_DrawLightSprites();
1577         }
1578         else
1579                 R_Shadow_SelectLight(NULL);
1580 }
1581
1582 void R_Shadow_EditLights_Clear_f(void)
1583 {
1584         R_Shadow_ClearWorldLights();
1585 }
1586
1587 void R_Shadow_EditLights_Reload_f(void)
1588 {
1589         r_shadow_reloadlights = true;
1590 }
1591
1592 void R_Shadow_EditLights_Save_f(void)
1593 {
1594         if (cl.worldmodel)
1595                 R_Shadow_SaveWorldLights();
1596 }
1597
1598 void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void)
1599 {
1600         R_Shadow_ClearWorldLights();
1601         R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite();
1602 }
1603
1604 void R_Shadow_EditLights_ImportLightsFile_f(void)
1605 {
1606         R_Shadow_ClearWorldLights();
1607         R_Shadow_LoadLightsFile();
1608 }
1609
1610 void R_Shadow_EditLights_Spawn_f(void)
1611 {
1612         vec3_t origin, color;
1613         vec_t radius;
1614         int style;
1615         const char *cubemapname;
1616         if (!r_editlights.integer)
1617         {
1618                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1619                 return;
1620         }
1621         if (Cmd_Argc() <= 7)
1622         {
1623                 radius = 200;
1624                 color[0] = color[1] = color[2] = 1;
1625                 style = 0;
1626                 cubemapname = NULL;
1627                 if (Cmd_Argc() >= 2)
1628                 {
1629                         radius = atof(Cmd_Argv(1));
1630                         if (Cmd_Argc() >= 3)
1631                         {
1632                                 color[0] = atof(Cmd_Argv(2));
1633                                 color[1] = color[0];
1634                                 color[2] = color[0];
1635                                 if (Cmd_Argc() >= 5)
1636                                 {
1637                                         color[1] = atof(Cmd_Argv(3));
1638                                         color[2] = atof(Cmd_Argv(4));
1639                                         if (Cmd_Argc() >= 6)
1640                                         {
1641                                                 style = atoi(Cmd_Argv(5));
1642                                                 if (Cmd_Argc() >= 7)
1643                                                         cubemapname = Cmd_Argv(6);
1644                                         }
1645                                 }
1646                         }
1647                 }
1648                 if (cubemapname && !cubemapname[0])
1649                         cubemapname = NULL;
1650                 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))
1651                 {
1652                         VectorCopy(r_editlights_cursorlocation, origin);
1653                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1654                         return;
1655                 }
1656         }
1657         Con_Printf("usage: r_editlights_spawn radius red green blue [style [cubemap]]\n");
1658 }
1659
1660 void R_Shadow_EditLights_Edit_f(void)
1661 {
1662         vec3_t origin, color;
1663         vec_t radius;
1664         int style;
1665         const char *cubemapname;
1666         if (!r_editlights.integer)
1667         {
1668                 Con_Printf("Cannot spawn light when not in editing mode.  Set r_editlights to 1.\n");
1669                 return;
1670         }
1671         if (!r_shadow_selectedlight)
1672         {
1673                 Con_Printf("No selected light.\n");
1674                 return;
1675         }
1676         if (Cmd_Argc() <= 7)
1677         {
1678                 radius = 200;
1679                 color[0] = color[1] = color[2] = 1;
1680                 style = 0;
1681                 cubemapname = NULL;
1682                 if (Cmd_Argc() >= 2)
1683                 {
1684                         radius = atof(Cmd_Argv(1));
1685                         if (Cmd_Argc() >= 3)
1686                         {
1687                                 color[0] = atof(Cmd_Argv(2));
1688                                 color[1] = color[0];
1689                                 color[2] = color[0];
1690                                 if (Cmd_Argc() >= 5)
1691                                 {
1692                                         color[1] = atof(Cmd_Argv(3));
1693                                         color[2] = atof(Cmd_Argv(4));
1694                                         if (Cmd_Argc() >= 6)
1695                                         {
1696                                                 style = atoi(Cmd_Argv(5));
1697                                                 if (Cmd_Argc() >= 7)
1698                                                         cubemapname = Cmd_Argv(6);
1699                                         }
1700                                 }
1701                         }
1702                 }
1703                 if (cubemapname && !cubemapname[0])
1704                         cubemapname = NULL;
1705                 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))
1706                 {
1707                         VectorCopy(r_shadow_selectedlight->origin, origin);
1708                         R_Shadow_FreeWorldLight(r_shadow_selectedlight);
1709                         r_shadow_selectedlight = NULL;
1710                         R_Shadow_NewWorldLight(origin, radius, color, style, cubemapname);
1711                         return;
1712                 }
1713         }
1714         Con_Printf("usage: r_editlights_edit radius red green blue [style [cubemap]]\n");
1715 }
1716
1717 void R_Shadow_EditLights_Remove_f(void)
1718 {
1719         if (!r_editlights.integer)
1720         {
1721                 Con_Printf("Cannot remove light when not in editing mode.  Set r_editlights to 1.\n");
1722                 return;
1723         }
1724         if (!r_shadow_selectedlight)
1725         {
1726                 Con_Printf("No selected light.\n");
1727                 return;
1728         }
1729         R_Shadow_FreeSelectedWorldLight();
1730 }
1731
1732 void R_Shadow_EditLights_Init(void)
1733 {
1734         Cvar_RegisterVariable(&r_editlights);
1735         Cvar_RegisterVariable(&r_editlights_cursordistance);
1736         Cvar_RegisterVariable(&r_editlights_cursorpushback);
1737         Cvar_RegisterVariable(&r_editlights_cursorpushoff);
1738         Cvar_RegisterVariable(&r_editlights_cursorgrid);
1739         Cvar_RegisterVariable(&r_editlights_quakelightsizescale);
1740         Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f);
1741         Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f);
1742         Cmd_AddCommand("r_editlights_save", R_Shadow_EditLights_Save_f);
1743         Cmd_AddCommand("r_editlights_spawn", R_Shadow_EditLights_Spawn_f);
1744         Cmd_AddCommand("r_editlights_edit", R_Shadow_EditLights_Edit_f);
1745         Cmd_AddCommand("r_editlights_remove", R_Shadow_EditLights_Remove_f);
1746         Cmd_AddCommand("r_editlights_importlightentitiesfrommap", R_Shadow_EditLights_ImportLightEntitiesFromMap_f);
1747         Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f);
1748 }