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