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