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