use even bigger primes actually
[divverent/darkplaces.git] / model_shared.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // models.c -- model loading and caching
21
22 // models are the only shared resource between a client and server running
23 // on the same machine.
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "r_shadow.h"
28
29 cvar_t r_mipskins = {CVAR_SAVE, "r_mipskins", "0", "mipmaps model skins so they render faster in the distance and do not display noise artifacts, can cause discoloration of skins if they contain undesirable border colors"};
30
31 model_t *loadmodel;
32
33 static mempool_t *mod_mempool;
34 static memexpandablearray_t models;
35
36 // FIXME: make this a memexpandablearray_t
37 #define Q3SHADER_MAXSHADERS 16384
38 static int q3shaders_numshaders = 0;
39 static q3shaderinfo_t q3shaders_shaders[Q3SHADER_MAXSHADERS];
40
41 static void mod_start(void)
42 {
43         int i;
44         int nummodels = Mem_ExpandableArray_IndexRange(&models);
45         model_t *mod;
46
47         // parse the Q3 shader files
48         Mod_LoadQ3Shaders();
49
50         for (i = 0;i < nummodels;i++)
51                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
52                         if (mod->used)
53                                 Mod_LoadModel(mod, true, false, mod->isworldmodel);
54 }
55
56 static void mod_shutdown(void)
57 {
58         int i;
59         int nummodels = Mem_ExpandableArray_IndexRange(&models);
60         model_t *mod;
61
62         for (i = 0;i < nummodels;i++)
63                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
64                         Mod_UnloadModel(mod);
65 }
66
67 static void mod_newmap(void)
68 {
69         msurface_t *surface;
70         int i, j, k, surfacenum, ssize, tsize;
71         int nummodels = Mem_ExpandableArray_IndexRange(&models);
72         model_t *mod;
73
74         R_SkinFrame_PrepareForPurge();
75         for (i = 0;i < nummodels;i++)
76         {
77                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_textures)
78                 {
79                         for (j = 0;j < mod->num_textures;j++)
80                         {
81                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
82                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
83                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
84                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
85                         }
86                 }
87         }
88         R_SkinFrame_Purge();
89
90         if (!cl_stainmaps_clearonload.integer)
91                 return;
92
93         for (i = 0;i < nummodels;i++)
94         {
95                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
96                 {
97                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
98                         {
99                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
100                                 {
101                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
102                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
103                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
104                                         surface->cached_dlight = true;
105                                 }
106                         }
107                 }
108         }
109 }
110
111 /*
112 ===============
113 Mod_Init
114 ===============
115 */
116 static void Mod_Print(void);
117 static void Mod_Precache (void);
118 static void Mod_BuildVBOs(void);
119 void Mod_Init (void)
120 {
121         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
122         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(model_t), 16);
123
124         Mod_BrushInit();
125         Mod_AliasInit();
126         Mod_SpriteInit();
127
128         Cvar_RegisterVariable(&r_mipskins);
129         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
130         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
131 }
132
133 void Mod_RenderInit(void)
134 {
135         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
136 }
137
138 void Mod_UnloadModel (model_t *mod)
139 {
140         char name[MAX_QPATH];
141         qboolean isworldmodel;
142         qboolean used;
143         strlcpy(name, mod->name, sizeof(name));
144         isworldmodel = mod->isworldmodel;
145         used = mod->used;
146         if (mod->surfmesh.ebo)
147                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo);
148         if (mod->surfmesh.vbo)
149                 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
150         // free textures/memory attached to the model
151         R_FreeTexturePool(&mod->texturepool);
152         Mem_FreePool(&mod->mempool);
153         // clear the struct to make it available
154         memset(mod, 0, sizeof(model_t));
155         // restore the fields we want to preserve
156         strlcpy(mod->name, name, sizeof(mod->name));
157         mod->isworldmodel = isworldmodel;
158         mod->used = used;
159         mod->loaded = false;
160 }
161
162 /*
163 ==================
164 Mod_LoadModel
165
166 Loads a model
167 ==================
168 */
169 model_t *Mod_LoadModel(model_t *mod, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
170 {
171         int num;
172         unsigned int crc;
173         void *buf;
174         fs_offset_t filesize;
175
176         mod->used = true;
177
178         if (mod->name[0] == '*') // submodel
179                 return mod;
180
181         crc = 0;
182         buf = NULL;
183
184         // even if the model is loaded it still may need reloading...
185
186         // if the model is a worldmodel and is being referred to as a
187         // non-worldmodel here, then it needs reloading to get rid of the
188         // submodels
189         if (mod->isworldmodel != isworldmodel)
190                 mod->loaded = false;
191
192         // if it is not loaded or checkdisk is true we need to calculate the crc
193         if (!mod->loaded || checkdisk)
194         {
195                 if (checkdisk && mod->loaded)
196                         Con_DPrintf("checking model %s\n", mod->name);
197                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
198                 if (buf)
199                 {
200                         crc = CRC_Block((unsigned char *)buf, filesize);
201                         // we need to reload the model if the crc does not match
202                         if (mod->crc != crc)
203                                 mod->loaded = false;
204                 }
205         }
206
207         // if the model is already loaded and checks passed, just return
208         if (mod->loaded)
209         {
210                 if (buf)
211                         Mem_Free(buf);
212                 return mod;
213         }
214
215         Con_DPrintf("loading model %s\n", mod->name);
216         // LordHavoc: unload the existing model in this slot (if there is one)
217         if (mod->loaded || mod->mempool)
218                 Mod_UnloadModel(mod);
219
220         // load the model
221         mod->isworldmodel = isworldmodel;
222         mod->used = true;
223         mod->crc = crc;
224         // errors can prevent the corresponding mod->loaded = true;
225         mod->loaded = false;
226
227         // default model radius and bounding box (mainly for missing models)
228         mod->radius = 16;
229         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
230         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
231         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
232         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
233         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
234         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
235
236         if (buf)
237         {
238                 char *bufend = (char *)buf + filesize;
239
240                 // all models use memory, so allocate a memory pool
241                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
242
243                 num = LittleLong(*((int *)buf));
244                 // call the apropriate loader
245                 loadmodel = mod;
246                      if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
247                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
248                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
249                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
250                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
251                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
252                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
253                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
254                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
255                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
256                 else if (!memcmp(buf, "MCBSPpad", 8)) Mod_Q1BSP_Load(mod, buf, bufend);
257                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
258                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
259                 Mem_Free(buf);
260
261                 Mod_BuildVBOs();
262
263                 // no fatal errors occurred, so this model is ready to use.
264                 mod->loaded = true;
265         }
266         else if (crash)
267         {
268                 // LordHavoc: Sys_Error was *ANNOYING*
269                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
270         }
271         return mod;
272 }
273
274 void Mod_ClearUsed(void)
275 {
276         int i;
277         int nummodels = Mem_ExpandableArray_IndexRange(&models);
278         model_t *mod;
279         for (i = 0;i < nummodels;i++)
280                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
281                         mod->used = false;
282 }
283
284 void Mod_PurgeUnused(void)
285 {
286         int i;
287         int nummodels = Mem_ExpandableArray_IndexRange(&models);
288         model_t *mod;
289         for (i = 0;i < nummodels;i++)
290         {
291                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
292                 {
293                         Mod_UnloadModel(mod);
294                         Mem_ExpandableArray_FreeRecord(&models, mod);
295                 }
296         }
297 }
298
299 // only used during loading!
300 void Mod_RemoveStaleWorldModels(model_t *skip)
301 {
302         int i;
303         int nummodels = Mem_ExpandableArray_IndexRange(&models);
304         model_t *mod;
305         for (i = 0;i < nummodels;i++)
306         {
307                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->isworldmodel && mod->loaded && skip != mod)
308                 {
309                         Mod_UnloadModel(mod);
310                         mod->isworldmodel = false;
311                         mod->used = false;
312                 }
313         }
314 }
315
316 /*
317 ==================
318 Mod_FindName
319
320 ==================
321 */
322 model_t *Mod_FindName(const char *name)
323 {
324         int i;
325         int nummodels = Mem_ExpandableArray_IndexRange(&models);
326         model_t *mod;
327
328         if (!name[0])
329                 Host_Error ("Mod_ForName: NULL name");
330
331         // search the currently loaded models
332         for (i = 0;i < nummodels;i++)
333         {
334                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name))
335                 {
336                         mod->used = true;
337                         return mod;
338                 }
339         }
340
341         // no match found, create a new one
342         mod = Mem_ExpandableArray_AllocRecord(&models);
343         strlcpy(mod->name, name, sizeof(mod->name));
344         mod->loaded = false;
345         mod->used = true;
346         return mod;
347 }
348
349 /*
350 ==================
351 Mod_ForName
352
353 Loads in a model for the given name
354 ==================
355 */
356 model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
357 {
358         model_t *model;
359         model = Mod_FindName(name);
360         if (model->name[0] != '*' && (!model->loaded || checkdisk))
361                 Mod_LoadModel(model, crash, checkdisk, isworldmodel);
362         return model;
363 }
364
365 /*
366 ==================
367 Mod_Reload
368
369 Reloads all models if they have changed
370 ==================
371 */
372 void Mod_Reload(void)
373 {
374         int i;
375         int nummodels = Mem_ExpandableArray_IndexRange(&models);
376         model_t *mod;
377         for (i = 0;i < nummodels;i++)
378                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
379                         Mod_LoadModel(mod, true, true, mod->isworldmodel);
380 }
381
382 unsigned char *mod_base;
383
384
385 //=============================================================================
386
387 /*
388 ================
389 Mod_Print
390 ================
391 */
392 static void Mod_Print(void)
393 {
394         int i;
395         int nummodels = Mem_ExpandableArray_IndexRange(&models);
396         model_t *mod;
397
398         Con_Print("Loaded models:\n");
399         for (i = 0;i < nummodels;i++)
400                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
401                         Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
402 }
403
404 /*
405 ================
406 Mod_Precache
407 ================
408 */
409 static void Mod_Precache(void)
410 {
411         if (Cmd_Argc() == 2)
412                 Mod_ForName(Cmd_Argv(1), false, true, cl.worldmodel && !strcasecmp(Cmd_Argv(1), cl.worldmodel->name));
413         else
414                 Con_Print("usage: modelprecache <filename>\n");
415 }
416
417 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
418 {
419         int i, count;
420         unsigned char *used;
421         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
422         memset(used, 0, numvertices);
423         for (i = 0;i < numelements;i++)
424                 used[elements[i]] = 1;
425         for (i = 0, count = 0;i < numvertices;i++)
426                 remapvertices[i] = used[i] ? count++ : -1;
427         Mem_Free(used);
428         return count;
429 }
430
431 #if 1
432 // fast way, using an edge hash
433 #define TRIANGLEEDGEHASH 8192
434 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
435 {
436         int i, j, p, e1, e2, *n, hashindex, count, match;
437         const int *e;
438         typedef struct edgehashentry_s
439         {
440                 struct edgehashentry_s *next;
441                 int triangle;
442                 int element[2];
443         }
444         edgehashentry_t;
445         edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
446         memset(edgehash, 0, sizeof(edgehash));
447         edgehashentries = edgehashentriesbuffer;
448         // if there are too many triangles for the stack array, allocate larger buffer
449         if (numtriangles > TRIANGLEEDGEHASH)
450                 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
451         // find neighboring triangles
452         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
453         {
454                 for (j = 0, p = 2;j < 3;p = j, j++)
455                 {
456                         e1 = e[p];
457                         e2 = e[j];
458                         // this hash index works for both forward and backward edges
459                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
460                         hash = edgehashentries + i * 3 + j;
461                         hash->next = edgehash[hashindex];
462                         edgehash[hashindex] = hash;
463                         hash->triangle = i;
464                         hash->element[0] = e1;
465                         hash->element[1] = e2;
466                 }
467         }
468         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
469         {
470                 for (j = 0, p = 2;j < 3;p = j, j++)
471                 {
472                         e1 = e[p];
473                         e2 = e[j];
474                         // this hash index works for both forward and backward edges
475                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
476                         count = 0;
477                         match = -1;
478                         for (hash = edgehash[hashindex];hash;hash = hash->next)
479                         {
480                                 if (hash->element[0] == e2 && hash->element[1] == e1)
481                                 {
482                                         if (hash->triangle != i)
483                                                 match = hash->triangle;
484                                         count++;
485                                 }
486                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
487                                         count++;
488                         }
489                         // detect edges shared by three triangles and make them seams
490                         if (count > 2)
491                                 match = -1;
492                         n[p] = match;
493                 }
494         }
495         // free the allocated buffer
496         if (edgehashentries != edgehashentriesbuffer)
497                 Mem_Free(edgehashentries);
498 }
499 #else
500 // very slow but simple way
501 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
502 {
503         int i, match, count;
504         count = 0;
505         match = -1;
506         for (i = 0;i < numtriangles;i++, elements += 3)
507         {
508                      if ((elements[0] == start && elements[1] == end)
509                       || (elements[1] == start && elements[2] == end)
510                       || (elements[2] == start && elements[0] == end))
511                 {
512                         if (i != ignore)
513                                 match = i;
514                         count++;
515                 }
516                 else if ((elements[1] == start && elements[0] == end)
517                       || (elements[2] == start && elements[1] == end)
518                       || (elements[0] == start && elements[2] == end))
519                         count++;
520         }
521         // detect edges shared by three triangles and make them seams
522         if (count > 2)
523                 match = -1;
524         return match;
525 }
526
527 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
528 {
529         int i, *n;
530         const int *e;
531         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
532         {
533                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
534                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
535                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
536         }
537 }
538 #endif
539
540 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
541 {
542         int i, warned = false, endvertex = firstvertex + numverts;
543         for (i = 0;i < numtriangles * 3;i++)
544         {
545                 if (elements[i] < firstvertex || elements[i] >= endvertex)
546                 {
547                         if (!warned)
548                         {
549                                 warned = true;
550                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
551                         }
552                         elements[i] = firstvertex;
553                 }
554         }
555 }
556
557 // warning: this is an expensive function!
558 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
559 {
560         int i, j;
561         const int *element;
562         float *vectorNormal;
563         float areaNormal[3];
564         // clear the vectors
565         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
566         // process each vertex of each triangle and accumulate the results
567         // use area-averaging, to make triangles with a big area have a bigger
568         // weighting on the vertex normal than triangles with a small area
569         // to do so, just add the 'normals' together (the bigger the area
570         // the greater the length of the normal is
571         element = elements;
572         for (i = 0; i < numtriangles; i++, element += 3)
573         {
574                 TriangleNormal(
575                         vertex3f + element[0] * 3,
576                         vertex3f + element[1] * 3,
577                         vertex3f + element[2] * 3,
578                         areaNormal
579                         );
580
581                 if (!areaweighting)
582                         VectorNormalize(areaNormal);
583
584                 for (j = 0;j < 3;j++)
585                 {
586                         vectorNormal = normal3f + element[j] * 3;
587                         vectorNormal[0] += areaNormal[0];
588                         vectorNormal[1] += areaNormal[1];
589                         vectorNormal[2] += areaNormal[2];
590                 }
591         }
592         // and just normalize the accumulated vertex normal in the end
593         vectorNormal = normal3f + 3 * firstvertex;
594         for (i = 0; i < numvertices; i++, vectorNormal += 3)
595                 VectorNormalize(vectorNormal);
596 }
597
598 void Mod_BuildBumpVectors(const float *v0, const float *v1, const float *v2, const float *tc0, const float *tc1, const float *tc2, float *svector3f, float *tvector3f, float *normal3f)
599 {
600         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
601         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
602         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
603
604         // 6 multiply, 9 subtract
605         VectorSubtract(v1, v0, v10);
606         VectorSubtract(v2, v0, v20);
607         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
608         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
609         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
610         // 12 multiply, 10 subtract
611         tc10[1] = tc1[1] - tc0[1];
612         tc20[1] = tc2[1] - tc0[1];
613         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
614         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
615         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
616         tc10[0] = tc1[0] - tc0[0];
617         tc20[0] = tc2[0] - tc0[0];
618         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
619         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
620         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
621         // 12 multiply, 4 add, 6 subtract
622         f = DotProduct(svector3f, normal3f);
623         svector3f[0] -= f * normal3f[0];
624         svector3f[1] -= f * normal3f[1];
625         svector3f[2] -= f * normal3f[2];
626         f = DotProduct(tvector3f, normal3f);
627         tvector3f[0] -= f * normal3f[0];
628         tvector3f[1] -= f * normal3f[1];
629         tvector3f[2] -= f * normal3f[2];
630         // if texture is mapped the wrong way (counterclockwise), the tangents
631         // have to be flipped, this is detected by calculating a normal from the
632         // two tangents, and seeing if it is opposite the surface normal
633         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
634         CrossProduct(tvector3f, svector3f, tangentcross);
635         if (DotProduct(tangentcross, normal3f) < 0)
636         {
637                 VectorNegate(svector3f, svector3f);
638                 VectorNegate(tvector3f, tvector3f);
639         }
640 }
641
642 // warning: this is a very expensive function!
643 void Mod_BuildTextureVectorsFromNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const float *texcoord2f, const float *normal3f, const int *elements, float *svector3f, float *tvector3f, qboolean areaweighting)
644 {
645         int i, tnum;
646         float sdir[3], tdir[3], normal[3], *sv, *tv;
647         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
648         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
649         const int *e;
650         // clear the vectors
651         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
652         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
653         // process each vertex of each triangle and accumulate the results
654         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
655         {
656                 v0 = vertex3f + e[0] * 3;
657                 v1 = vertex3f + e[1] * 3;
658                 v2 = vertex3f + e[2] * 3;
659                 tc0 = texcoord2f + e[0] * 2;
660                 tc1 = texcoord2f + e[1] * 2;
661                 tc2 = texcoord2f + e[2] * 2;
662
663                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
664                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
665
666                 // calculate the edge directions and surface normal
667                 // 6 multiply, 9 subtract
668                 VectorSubtract(v1, v0, v10);
669                 VectorSubtract(v2, v0, v20);
670                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
671                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
672                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
673
674                 // calculate the tangents
675                 // 12 multiply, 10 subtract
676                 tc10[1] = tc1[1] - tc0[1];
677                 tc20[1] = tc2[1] - tc0[1];
678                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
679                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
680                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
681                 tc10[0] = tc1[0] - tc0[0];
682                 tc20[0] = tc2[0] - tc0[0];
683                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
684                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
685                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
686
687                 // if texture is mapped the wrong way (counterclockwise), the tangents
688                 // have to be flipped, this is detected by calculating a normal from the
689                 // two tangents, and seeing if it is opposite the surface normal
690                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
691                 CrossProduct(tdir, sdir, tangentcross);
692                 if (DotProduct(tangentcross, normal) < 0)
693                 {
694                         VectorNegate(sdir, sdir);
695                         VectorNegate(tdir, tdir);
696                 }
697
698                 if (!areaweighting)
699                 {
700                         VectorNormalize(sdir);
701                         VectorNormalize(tdir);
702                 }
703                 for (i = 0;i < 3;i++)
704                 {
705                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
706                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
707                 }
708         }
709         // make the tangents completely perpendicular to the surface normal, and
710         // then normalize them
711         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
712         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
713         {
714                 f = -DotProduct(sv, n);
715                 VectorMA(sv, f, n, sv);
716                 VectorNormalize(sv);
717                 f = -DotProduct(tv, n);
718                 VectorMA(tv, f, n, tv);
719                 VectorNormalize(tv);
720         }
721 }
722
723 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
724 {
725         unsigned char *data;
726         data = (unsigned char *)Mem_Alloc(mempool, numvertices * (3 + 3 + 3 + 3 + 2 + 2 + (vertexcolors ? 4 : 0)) * sizeof(float) + numvertices * (lightmapoffsets ? 1 : 0) * sizeof(int) + numtriangles * (3 + (neighbors ? 3 : 0)) * sizeof(int));
727         loadmodel->surfmesh.num_vertices = numvertices;
728         loadmodel->surfmesh.num_triangles = numtriangles;
729         if (loadmodel->surfmesh.num_vertices)
730         {
731                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
732                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
733                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
734                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
735                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
736                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
737                 if (vertexcolors)
738                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
739                 if (lightmapoffsets)
740                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
741         }
742         if (loadmodel->surfmesh.num_triangles)
743         {
744                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
745                 if (neighbors)
746                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
747         }
748 }
749
750 shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
751 {
752         shadowmesh_t *newmesh;
753         unsigned char *data;
754         int size;
755         size = sizeof(shadowmesh_t);
756         size += maxverts * sizeof(float[3]);
757         if (light)
758                 size += maxverts * sizeof(float[11]);
759         size += maxtriangles * sizeof(int[3]);
760         if (neighbors)
761                 size += maxtriangles * sizeof(int[3]);
762         if (expandable)
763                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
764         data = (unsigned char *)Mem_Alloc(mempool, size);
765         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
766         newmesh->map_diffuse = map_diffuse;
767         newmesh->map_specular = map_specular;
768         newmesh->map_normal = map_normal;
769         newmesh->maxverts = maxverts;
770         newmesh->maxtriangles = maxtriangles;
771         newmesh->numverts = 0;
772         newmesh->numtriangles = 0;
773
774         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
775         if (light)
776         {
777                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
778                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
779                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
780                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
781         }
782         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
783         if (neighbors)
784         {
785                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
786         }
787         if (expandable)
788         {
789                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
790                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
791         }
792         return newmesh;
793 }
794
795 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
796 {
797         shadowmesh_t *newmesh;
798         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
799         newmesh->numverts = oldmesh->numverts;
800         newmesh->numtriangles = oldmesh->numtriangles;
801
802         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
803         if (newmesh->svector3f && oldmesh->svector3f)
804         {
805                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
806                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
807                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
808                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
809         }
810         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
811         if (newmesh->neighbor3i && oldmesh->neighbor3i)
812                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
813         return newmesh;
814 }
815
816 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
817 {
818         int hashindex, vnum;
819         shadowmeshvertexhash_t *hash;
820         // this uses prime numbers intentionally
821         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
822         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
823         {
824                 vnum = (hash - mesh->vertexhashentries);
825                 if ((mesh->vertex3f == NULL || (mesh->vertex3f[vnum * 3 + 0] == vertex14f[0] && mesh->vertex3f[vnum * 3 + 1] == vertex14f[1] && mesh->vertex3f[vnum * 3 + 2] == vertex14f[2]))
826                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
827                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
828                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
829                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
830                         return hash - mesh->vertexhashentries;
831         }
832         vnum = mesh->numverts++;
833         hash = mesh->vertexhashentries + vnum;
834         hash->next = mesh->vertexhashtable[hashindex];
835         mesh->vertexhashtable[hashindex] = hash;
836         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
837         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
838         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
839         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
840         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
841         return vnum;
842 }
843
844 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
845 {
846         if (mesh->numtriangles == 0)
847         {
848                 // set the properties on this empty mesh to be more favorable...
849                 // (note: this case only occurs for the first triangle added to a new mesh chain)
850                 mesh->map_diffuse = map_diffuse;
851                 mesh->map_specular = map_specular;
852                 mesh->map_normal = map_normal;
853         }
854         while (mesh->map_diffuse != map_diffuse || mesh->map_specular != map_specular || mesh->map_normal != map_normal || mesh->numverts + 3 > mesh->maxverts || mesh->numtriangles + 1 > mesh->maxtriangles)
855         {
856                 if (mesh->next == NULL)
857                         mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxverts, 300), max(mesh->maxtriangles, 100), map_diffuse, map_specular, map_normal, mesh->svector3f != NULL, mesh->neighbor3i != NULL, true);
858                 mesh = mesh->next;
859         }
860         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
861         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
862         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
863         mesh->numtriangles++;
864 }
865
866 void Mod_ShadowMesh_AddMesh(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *texcoord2f, int numtris, const int *element3i)
867 {
868         int i, j, e;
869         float vbuf[3*14], *v;
870         memset(vbuf, 0, sizeof(vbuf));
871         for (i = 0;i < numtris;i++)
872         {
873                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
874                 {
875                         e = *element3i++;
876                         if (vertex3f)
877                         {
878                                 v[0] = vertex3f[e * 3 + 0];
879                                 v[1] = vertex3f[e * 3 + 1];
880                                 v[2] = vertex3f[e * 3 + 2];
881                         }
882                         if (svector3f)
883                         {
884                                 v[3] = svector3f[e * 3 + 0];
885                                 v[4] = svector3f[e * 3 + 1];
886                                 v[5] = svector3f[e * 3 + 2];
887                         }
888                         if (tvector3f)
889                         {
890                                 v[6] = tvector3f[e * 3 + 0];
891                                 v[7] = tvector3f[e * 3 + 1];
892                                 v[8] = tvector3f[e * 3 + 2];
893                         }
894                         if (normal3f)
895                         {
896                                 v[9] = normal3f[e * 3 + 0];
897                                 v[10] = normal3f[e * 3 + 1];
898                                 v[11] = normal3f[e * 3 + 2];
899                         }
900                         if (texcoord2f)
901                         {
902                                 v[12] = texcoord2f[e * 2 + 0];
903                                 v[13] = texcoord2f[e * 2 + 1];
904                         }
905                 }
906                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
907         }
908 }
909
910 shadowmesh_t *Mod_ShadowMesh_Begin(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
911 {
912         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
913 }
914
915 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
916 {
917         if (!gl_support_arb_vertex_buffer_object)
918                 return;
919
920         // element buffer is easy because it's just one array
921         if (mesh->numtriangles)
922                 mesh->ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(int[3]), "shadowmesh");
923
924         // vertex buffer is several arrays and we put them in the same buffer
925         //
926         // is this wise?  the texcoordtexture2f array is used with dynamic
927         // vertex/svector/tvector/normal when rendering animated models, on the
928         // other hand animated models don't use a lot of vertices anyway...
929         if (mesh->numverts)
930         {
931                 size_t size;
932                 unsigned char *mem;
933                 size = 0;
934                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
935                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
936                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
937                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
938                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
939                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
940                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
941                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
942                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
943                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
944                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
945                 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
946                 Mem_Free(mem);
947         }
948 }
949
950 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
951 {
952         shadowmesh_t *mesh, *newmesh, *nextmesh;
953         // reallocate meshs to conserve space
954         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
955         {
956                 nextmesh = mesh->next;
957                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
958                 {
959                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
960                         newmesh->next = firstmesh;
961                         firstmesh = newmesh;
962                         if (createvbo)
963                                 Mod_ShadowMesh_CreateVBOs(newmesh);
964                 }
965                 Mem_Free(mesh);
966         }
967         return firstmesh;
968 }
969
970 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
971 {
972         int i;
973         shadowmesh_t *mesh;
974         vec3_t nmins, nmaxs, ncenter, temp;
975         float nradius2, dist2, *v;
976         VectorClear(nmins);
977         VectorClear(nmaxs);
978         // calculate bbox
979         for (mesh = firstmesh;mesh;mesh = mesh->next)
980         {
981                 if (mesh == firstmesh)
982                 {
983                         VectorCopy(mesh->vertex3f, nmins);
984                         VectorCopy(mesh->vertex3f, nmaxs);
985                 }
986                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
987                 {
988                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
989                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
990                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
991                 }
992         }
993         // calculate center and radius
994         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
995         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
996         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
997         nradius2 = 0;
998         for (mesh = firstmesh;mesh;mesh = mesh->next)
999         {
1000                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1001                 {
1002                         VectorSubtract(v, ncenter, temp);
1003                         dist2 = DotProduct(temp, temp);
1004                         if (nradius2 < dist2)
1005                                 nradius2 = dist2;
1006                 }
1007         }
1008         // return data
1009         if (mins)
1010                 VectorCopy(nmins, mins);
1011         if (maxs)
1012                 VectorCopy(nmaxs, maxs);
1013         if (center)
1014                 VectorCopy(ncenter, center);
1015         if (radius)
1016                 *radius = sqrt(nradius2);
1017 }
1018
1019 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1020 {
1021         shadowmesh_t *nextmesh;
1022         for (;mesh;mesh = nextmesh)
1023         {
1024                 if (mesh->ebo)
1025                         R_Mesh_DestroyBufferObject(mesh->ebo);
1026                 if (mesh->vbo)
1027                         R_Mesh_DestroyBufferObject(mesh->vbo);
1028                 nextmesh = mesh->next;
1029                 Mem_Free(mesh);
1030         }
1031 }
1032
1033 void Mod_GetTerrainVertex3fTexCoord2fFromRGBA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1034 {
1035         float v[3], tc[3];
1036         v[0] = ix;
1037         v[1] = iy;
1038         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1039                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1040         else
1041                 v[2] = 0;
1042         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1043         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1044         texcoord2f[0] = tc[0];
1045         texcoord2f[1] = tc[1];
1046 }
1047
1048 void Mod_GetTerrainVertexFromRGBA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1049 {
1050         float vup[3], vdown[3], vleft[3], vright[3];
1051         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1052         float sv[3], tv[3], nl[3];
1053         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1054         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1055         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1056         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1057         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1058         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1059         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1060         VectorAdd(svector3f, sv, svector3f);
1061         VectorAdd(tvector3f, tv, tvector3f);
1062         VectorAdd(normal3f, nl, normal3f);
1063         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1064         VectorAdd(svector3f, sv, svector3f);
1065         VectorAdd(tvector3f, tv, tvector3f);
1066         VectorAdd(normal3f, nl, normal3f);
1067         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1068         VectorAdd(svector3f, sv, svector3f);
1069         VectorAdd(tvector3f, tv, tvector3f);
1070         VectorAdd(normal3f, nl, normal3f);
1071 }
1072
1073 void Mod_ConstructTerrainPatchFromRGBA(const unsigned char *imagepixels, int imagewidth, int imageheight, int x1, int y1, int width, int height, int *element3i, int *neighbor3i, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1074 {
1075         int x, y, ix, iy, *e;
1076         e = element3i;
1077         for (y = 0;y < height;y++)
1078         {
1079                 for (x = 0;x < width;x++)
1080                 {
1081                         e[0] = (y + 1) * (width + 1) + (x + 0);
1082                         e[1] = (y + 0) * (width + 1) + (x + 0);
1083                         e[2] = (y + 1) * (width + 1) + (x + 1);
1084                         e[3] = (y + 0) * (width + 1) + (x + 0);
1085                         e[4] = (y + 0) * (width + 1) + (x + 1);
1086                         e[5] = (y + 1) * (width + 1) + (x + 1);
1087                         e += 6;
1088                 }
1089         }
1090         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1091         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1092                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1093                         Mod_GetTerrainVertexFromRGBA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1094 }
1095
1096 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1097 {
1098         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1099         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1100         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1101         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1102         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1103         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1104         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1105         return Q3WAVEFUNC_NONE;
1106 }
1107
1108 void Mod_LoadQ3Shaders(void)
1109 {
1110         int j;
1111         int fileindex;
1112         fssearch_t *search;
1113         char *f;
1114         const char *text;
1115         q3shaderinfo_t *shader;
1116         q3shaderinfo_layer_t *layer;
1117         int numparameters;
1118         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1119         q3shaders_numshaders = 0;
1120         search = FS_Search("scripts/*.shader", true, false);
1121         if (!search)
1122                 return;
1123         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1124         {
1125                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1126                 if (!f)
1127                         continue;
1128                 while (COM_ParseToken_QuakeC(&text, false))
1129                 {
1130                         if (q3shaders_numshaders >= Q3SHADER_MAXSHADERS)
1131                         {
1132                                 Con_Printf("Mod_LoadQ3Shaders: too many shaders!\n");
1133                                 break;
1134                         }
1135                         shader = q3shaders_shaders + q3shaders_numshaders++;
1136                         memset(shader, 0, sizeof(*shader));
1137                         strlcpy(shader->name, com_token, sizeof(shader->name));
1138                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1139                         {
1140                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1141                                 break;
1142                         }
1143                         while (COM_ParseToken_QuakeC(&text, false))
1144                         {
1145                                 if (!strcasecmp(com_token, "}"))
1146                                         break;
1147                                 if (!strcasecmp(com_token, "{"))
1148                                 {
1149                                         if (shader->numlayers < Q3SHADER_MAXLAYERS)
1150                                         {
1151                                                 layer = shader->layers + shader->numlayers++;
1152                                                 layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1153                                                 layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1154                                                 layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1155                                                 layer->blendfunc[0] = GL_ONE;
1156                                                 layer->blendfunc[1] = GL_ZERO;
1157                                         }
1158                                         else
1159                                                 layer = NULL;
1160                                         while (COM_ParseToken_QuakeC(&text, false))
1161                                         {
1162                                                 if (!strcasecmp(com_token, "}"))
1163                                                         break;
1164                                                 if (!strcasecmp(com_token, "\n"))
1165                                                         continue;
1166                                                 if (layer == NULL)
1167                                                         continue;
1168                                                 numparameters = 0;
1169                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1170                                                 {
1171                                                         if (j < TEXTURE_MAXFRAMES + 4)
1172                                                         {
1173                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1174                                                                 numparameters = j + 1;
1175                                                         }
1176                                                         if (!COM_ParseToken_QuakeC(&text, true))
1177                                                                 break;
1178                                                 }
1179                                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1180                                                         parameter[j][0] = 0;
1181                                                 if (developer.integer >= 100)
1182                                                 {
1183                                                         Con_Printf("%s %i: ", shader->name, shader->numlayers - 1);
1184                                                         for (j = 0;j < numparameters;j++)
1185                                                                 Con_Printf(" %s", parameter[j]);
1186                                                         Con_Print("\n");
1187                                                 }
1188                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1189                                                 {
1190                                                         if (numparameters == 2)
1191                                                         {
1192                                                                 if (!strcasecmp(parameter[1], "add"))
1193                                                                 {
1194                                                                         layer->blendfunc[0] = GL_ONE;
1195                                                                         layer->blendfunc[1] = GL_ONE;
1196                                                                 }
1197                                                                 else if (!strcasecmp(parameter[1], "filter"))
1198                                                                 {
1199                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1200                                                                         layer->blendfunc[1] = GL_ZERO;
1201                                                                 }
1202                                                                 else if (!strcasecmp(parameter[1], "blend"))
1203                                                                 {
1204                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1205                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1206                                                                 }
1207                                                         }
1208                                                         else if (numparameters == 3)
1209                                                         {
1210                                                                 int k;
1211                                                                 for (k = 0;k < 2;k++)
1212                                                                 {
1213                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1214                                                                                 layer->blendfunc[k] = GL_ONE;
1215                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1216                                                                                 layer->blendfunc[k] = GL_ZERO;
1217                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1218                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1219                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1220                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1221                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1222                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1223                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1224                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1225                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1226                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1227                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1228                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1229                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1230                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1231                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1232                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1233                                                                         else
1234                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1235                                                                 }
1236                                                         }
1237                                                 }
1238                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1239                                                         layer->alphatest = true;
1240                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1241                                                 {
1242                                                         if (!strcasecmp(parameter[0], "clampmap"))
1243                                                                 layer->clampmap = true;
1244                                                         layer->numframes = 1;
1245                                                         layer->framerate = 1;
1246                                                         strlcpy(layer->texturename[0], parameter[1], sizeof(layer->texturename));
1247                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1248                                                                 shader->lighting = true;
1249                                                 }
1250                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1251                                                 {
1252                                                         int i;
1253                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1254                                                         layer->framerate = atof(parameter[1]);
1255                                                         for (i = 0;i < layer->numframes;i++)
1256                                                                 strlcpy(layer->texturename[i], parameter[i + 2], sizeof(layer->texturename));
1257                                                 }
1258                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1259                                                 {
1260                                                         int i;
1261                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1262                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1263                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1264                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1265                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1266                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1267                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1268                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1269                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1270                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1271                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1272                                                         else if (!strcasecmp(parameter[1], "wave"))
1273                                                         {
1274                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1275                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1276                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1277                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1278                                                         }
1279                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1280                                                 }
1281                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1282                                                 {
1283                                                         int i;
1284                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1285                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1286                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1287                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1288                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1289                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1290                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1291                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1292                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1293                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1294                                                         else if (!strcasecmp(parameter[1], "wave"))
1295                                                         {
1296                                                                 layer->alphagen.alphagen = Q3RGBGEN_WAVE;
1297                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1298                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1299                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1300                                                         }
1301                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1302                                                 }
1303                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1304                                                 {
1305                                                         int i;
1306                                                         // observed values: tcgen environment
1307                                                         // no other values have been observed in real shaders
1308                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1309                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1310                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1311                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1312                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1313                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1314                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1315                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1316                                                 }
1317                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1318                                                 {
1319                                                         int i, tcmodindex;
1320                                                         // observed values:
1321                                                         // tcmod rotate #
1322                                                         // tcmod scale # #
1323                                                         // tcmod scroll # #
1324                                                         // tcmod stretch sin # # # #
1325                                                         // tcmod stretch triangle # # # #
1326                                                         // tcmod transform # # # # # #
1327                                                         // tcmod turb # # # #
1328                                                         // tcmod turb sin # # # #  (this is bogus)
1329                                                         // no other values have been observed in real shaders
1330                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1331                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1332                                                                         break;
1333                                                         if (tcmodindex < Q3MAXTCMODS)
1334                                                         {
1335                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1336                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1337                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1338                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1339                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1340                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1341                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1342                                                                 {
1343                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1344                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1345                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1346                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1347                                                                 }
1348                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1349                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1350                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1351                                                         }
1352                                                         else
1353                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1354                                                 }
1355                                                 // break out a level if it was }
1356                                                 if (!strcasecmp(com_token, "}"))
1357                                                         break;
1358                                         }
1359                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1360                                                 shader->lighting = true;
1361                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1362                                         {
1363                                                 if (layer == shader->layers + 0)
1364                                                 {
1365                                                         // vertex controlled transparency
1366                                                         shader->vertexalpha = true;
1367                                                 }
1368                                                 else
1369                                                 {
1370                                                         // multilayer terrain shader or similar
1371                                                         shader->textureblendalpha = true;
1372                                                 }
1373                                         }
1374                                         continue;
1375                                 }
1376                                 numparameters = 0;
1377                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1378                                 {
1379                                         if (j < TEXTURE_MAXFRAMES + 4)
1380                                         {
1381                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1382                                                 numparameters = j + 1;
1383                                         }
1384                                         if (!COM_ParseToken_QuakeC(&text, true))
1385                                                 break;
1386                                 }
1387                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1388                                         parameter[j][0] = 0;
1389                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1390                                         break;
1391                                 if (developer.integer >= 100)
1392                                 {
1393                                         Con_Printf("%s: ", shader->name);
1394                                         for (j = 0;j < numparameters;j++)
1395                                                 Con_Printf(" %s", parameter[j]);
1396                                         Con_Print("\n");
1397                                 }
1398                                 if (numparameters < 1)
1399                                         continue;
1400                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1401                                 {
1402                                         if (!strcasecmp(parameter[1], "alphashadow"))
1403                                                 shader->surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1404                                         else if (!strcasecmp(parameter[1], "areaportal"))
1405                                                 shader->surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1406                                         else if (!strcasecmp(parameter[1], "botclip"))
1407                                                 shader->surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1408                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1409                                                 shader->surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1410                                         else if (!strcasecmp(parameter[1], "detail"))
1411                                                 shader->surfaceparms |= Q3SURFACEPARM_DETAIL;
1412                                         else if (!strcasecmp(parameter[1], "donotenter"))
1413                                                 shader->surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1414                                         else if (!strcasecmp(parameter[1], "dust"))
1415                                                 shader->surfaceparms |= Q3SURFACEPARM_DUST;
1416                                         else if (!strcasecmp(parameter[1], "hint"))
1417                                                 shader->surfaceparms |= Q3SURFACEPARM_HINT;
1418                                         else if (!strcasecmp(parameter[1], "fog"))
1419                                                 shader->surfaceparms |= Q3SURFACEPARM_FOG;
1420                                         else if (!strcasecmp(parameter[1], "lava"))
1421                                                 shader->surfaceparms |= Q3SURFACEPARM_LAVA;
1422                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1423                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1424                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1425                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1426                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1427                                                 shader->surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1428                                         else if (!strcasecmp(parameter[1], "nodamage"))
1429                                                 shader->surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1430                                         else if (!strcasecmp(parameter[1], "nodlight"))
1431                                                 shader->surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1432                                         else if (!strcasecmp(parameter[1], "nodraw"))
1433                                                 shader->surfaceparms |= Q3SURFACEPARM_NODRAW;
1434                                         else if (!strcasecmp(parameter[1], "nodrop"))
1435                                                 shader->surfaceparms |= Q3SURFACEPARM_NODROP;
1436                                         else if (!strcasecmp(parameter[1], "noimpact"))
1437                                                 shader->surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1438                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1439                                                 shader->surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1440                                         else if (!strcasecmp(parameter[1], "nomarks"))
1441                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMARKS;
1442                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1443                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1444                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1445                                                 shader->surfaceparms |= Q3SURFACEPARM_NONSOLID;
1446                                         else if (!strcasecmp(parameter[1], "origin"))
1447                                                 shader->surfaceparms |= Q3SURFACEPARM_ORIGIN;
1448                                         else if (!strcasecmp(parameter[1], "playerclip"))
1449                                                 shader->surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1450                                         else if (!strcasecmp(parameter[1], "sky"))
1451                                                 shader->surfaceparms |= Q3SURFACEPARM_SKY;
1452                                         else if (!strcasecmp(parameter[1], "slick"))
1453                                                 shader->surfaceparms |= Q3SURFACEPARM_SLICK;
1454                                         else if (!strcasecmp(parameter[1], "slime"))
1455                                                 shader->surfaceparms |= Q3SURFACEPARM_SLIME;
1456                                         else if (!strcasecmp(parameter[1], "structural"))
1457                                                 shader->surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1458                                         else if (!strcasecmp(parameter[1], "trans"))
1459                                                 shader->surfaceparms |= Q3SURFACEPARM_TRANS;
1460                                         else if (!strcasecmp(parameter[1], "water"))
1461                                                 shader->surfaceparms |= Q3SURFACEPARM_WATER;
1462                                         else if (!strcasecmp(parameter[1], "pointlight"))
1463                                                 shader->surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1464                                         else if (!strcasecmp(parameter[1], "antiportal"))
1465                                                 shader->surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1466                                         else
1467                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1468                                 }
1469                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1470                                 {
1471                                         // some q3 skies don't have the sky parm set
1472                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1473                                         strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1474                                 }
1475                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1476                                 {
1477                                         // some q3 skies don't have the sky parm set
1478                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1479                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1480                                                 strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1481                                 }
1482                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1483                                 {
1484                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1485                                                 shader->textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1486                                 }
1487                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1488                                         shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1489                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1490                                         shader->textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1491                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1492                                         shader->textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1493                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1494                                 {
1495                                         int i, deformindex;
1496                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1497                                                 if (!shader->deforms[deformindex].deform)
1498                                                         break;
1499                                         if (deformindex < Q3MAXDEFORMS)
1500                                         {
1501                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1502                                                         shader->deforms[deformindex].parms[i] = atof(parameter[i+2]);
1503                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader->deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1504                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1505                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1506                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT0;
1507                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT1;
1508                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT2;
1509                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT3;
1510                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT4;
1511                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT5;
1512                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT6;
1513                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT7;
1514                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader->deforms[deformindex].deform = Q3DEFORM_BULGE;
1515                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader->deforms[deformindex].deform = Q3DEFORM_NORMAL;
1516                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1517                                                 {
1518                                                         shader->deforms[deformindex].deform = Q3DEFORM_WAVE;
1519                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1520                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1521                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1522                                                 }
1523                                                 else if (!strcasecmp(parameter[1], "move"            ))
1524                                                 {
1525                                                         shader->deforms[deformindex].deform = Q3DEFORM_MOVE;
1526                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1527                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1528                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1529                                                 }
1530                                         }
1531                                 }
1532                         }
1533                         // identify if this is a blended terrain shader or similar
1534                         if (shader->numlayers)
1535                         {
1536                                 shader->backgroundlayer = NULL;
1537                                 shader->primarylayer = shader->layers + 0;
1538                                 if ((shader->layers[0].blendfunc[0] == GL_ONE       && shader->layers[0].blendfunc[1] == GL_ZERO                && !shader->layers[0].alphatest)
1539                                 && ((shader->layers[1].blendfunc[0] == GL_SRC_ALPHA && shader->layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA && !shader->layers[0].alphatest)
1540                                 ||  (shader->layers[1].blendfunc[0] == GL_ONE       && shader->layers[1].blendfunc[1] == GL_ZERO                &&  shader->layers[1].alphatest)))
1541                                 {
1542                                         // terrain blending or other effects
1543                                         shader->backgroundlayer = shader->layers + 0;
1544                                         shader->primarylayer = shader->layers + 1;
1545                                 }
1546                                 // now see if the lightmap came first, and if so choose the second texture instead
1547                                 if (!strcasecmp(shader->primarylayer->texturename[0], "$lightmap"))
1548                                 {
1549                                         shader->backgroundlayer = NULL;
1550                                         shader->primarylayer = shader->layers + 1;
1551                                 }
1552                         }
1553                 }
1554                 Mem_Free(f);
1555         }
1556 }
1557
1558 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
1559 {
1560         int i;
1561         for (i = 0;i < Q3SHADER_MAXSHADERS;i++)
1562                 if (!strcasecmp(q3shaders_shaders[i].name, name))
1563                         return q3shaders_shaders + i;
1564         return NULL;
1565 }
1566
1567 extern cvar_t r_picmipworld;
1568 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean q1bsp, qboolean q3bsp, qboolean md3)
1569 {
1570         int j;
1571         int texflags;
1572         qboolean success = true;
1573         q3shaderinfo_t *shader;
1574         strlcpy(texture->name, name, sizeof(texture->name));
1575         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
1576         if (shader)
1577         {
1578                 if (developer.integer >= 100)
1579                         Con_DPrintf("%s: loaded shader for %s\n", loadmodel->name, name);
1580                 texture->surfaceparms = shader->surfaceparms;
1581                 texture->textureflags = shader->textureflags;
1582                 texture->basematerialflags = 0;
1583                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
1584                 {
1585                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1586                         if (shader->skyboxname[0])
1587                         {
1588                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
1589                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
1590                         }
1591                 }
1592                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
1593                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1594                 else if (shader->surfaceparms & Q3SURFACEPARM_LAVA)
1595                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOSHADOW;
1596                 else if (shader->surfaceparms & Q3SURFACEPARM_SLIME)
1597                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1598                 else if (shader->surfaceparms & Q3SURFACEPARM_WATER)
1599                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1600                 else
1601                         texture->basematerialflags |= MATERIALFLAG_WALL;
1602                 if (shader->layers[0].alphatest)
1603                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1604                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
1605                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
1606                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
1607                         texture->basepolygonoffset -= 2;
1608                 texture->customblendfunc[0] = GL_ONE;
1609                 texture->customblendfunc[1] = GL_ZERO;
1610                 if (shader->numlayers > 0)
1611                 {
1612                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
1613                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
1614 /*
1615 Q3 shader blendfuncs actually used in the game (* = supported by DP)
1616 * additive               GL_ONE GL_ONE
1617 additive weird         GL_ONE GL_SRC_ALPHA
1618 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
1619 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
1620 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
1621 brighten               GL_DST_COLOR GL_ONE
1622 brighten               GL_ONE GL_SRC_COLOR
1623 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
1624 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
1625 * modulate               GL_DST_COLOR GL_ZERO
1626 * modulate               GL_ZERO GL_SRC_COLOR
1627 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
1628 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
1629 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
1630 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
1631 * no blend               GL_ONE GL_ZERO
1632 nothing                GL_ZERO GL_ONE
1633 */
1634                         // if not opaque, figure out what blendfunc to use
1635                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
1636                         {
1637                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
1638                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1639                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
1640                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1641                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
1642                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1643                                 else
1644                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1645                         }
1646                 }
1647                 if (!shader->lighting)
1648                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1649                 if (shader->primarylayer)
1650                 {
1651                         // copy over many shader->primarylayer parameters
1652                         texture->rgbgen = shader->primarylayer->rgbgen;
1653                         texture->alphagen = shader->primarylayer->alphagen;
1654                         texture->tcgen = shader->primarylayer->tcgen;
1655                         memcpy(texture->tcmods, shader->primarylayer->tcmods, sizeof(texture->tcmods));
1656                         // load the textures
1657                         texture->numskinframes = shader->primarylayer->numframes;
1658                         texture->skinframerate = shader->primarylayer->framerate;
1659                         for (j = 0;j < shader->primarylayer->numframes;j++)
1660                         {
1661                                 texflags = TEXF_ALPHA | TEXF_PRECACHE;
1662                                 if (!(shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1663                                         texflags |= TEXF_MIPMAP;
1664                                 if (!(shader->textureflags & Q3TEXTUREFLAG_NOPICMIP) && ((!q1bsp && !q3bsp) || r_picmipworld.integer))
1665                                         texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1666                                 if (shader->primarylayer->clampmap)
1667                                         texflags |= TEXF_CLAMP;
1668                                 if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(shader->primarylayer->texturename[j], texflags, false)))
1669                                 {
1670                                         Con_DPrintf("%s: could not load texture \"%s\" (frame %i) for shader \"%s\"\n", loadmodel->name, shader->primarylayer->texturename[j], j, texture->name);
1671                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
1672                                 }
1673                         }
1674                 }
1675                 if (shader->backgroundlayer)
1676                 {
1677                         texture->backgroundnumskinframes = shader->backgroundlayer->numframes;
1678                         texture->backgroundskinframerate = shader->backgroundlayer->framerate;
1679                         for (j = 0;j < shader->backgroundlayer->numframes;j++)
1680                         {
1681                                 if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(shader->backgroundlayer->texturename[j], ((shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | ((!r_picmipworld.integer || (shader->textureflags & Q3TEXTUREFLAG_NOPICMIP)) ? 0 : (TEXF_PICMIP | TEXF_COMPRESS)) | (shader->backgroundlayer->clampmap ? TEXF_CLAMP : 0), false)))
1682                                 {
1683                                         Con_DPrintf("%s: could not load texture \"%s\" (frame %i) for shader \"%s\"\n", loadmodel->name, shader->backgroundlayer->texturename[j], j, texture->name);
1684                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
1685                                 }
1686                         }
1687                 }
1688                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
1689         }
1690         else if (!strcmp(texture->name, "noshader"))
1691         {
1692                 if (developer.integer >= 100)
1693                         Con_DPrintf("%s: using default handler for %s\n", loadmodel->name, name);
1694                 texture->surfaceparms = 0;
1695         }
1696         else
1697         {
1698                 success = false;
1699                 if (developer.integer >= 100 || loadmodel->type == mod_brushq3)
1700                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, texture->name);
1701                 texture->surfaceparms = 0;
1702                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
1703                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1704                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
1705                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1706                 else
1707                         texture->basematerialflags |= MATERIALFLAG_WALL;
1708                 texture->numskinframes = 1;
1709                 if (!(texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false)))
1710                         Con_DPrintf("%s: could not load texture for missing shader \"%s\"\n", loadmodel->name, texture->name);
1711         }
1712         // init the animation variables
1713         texture->currentframe = texture;
1714         if (texture->numskinframes < 1)
1715                 texture->numskinframes = 1;
1716         if (!texture->skinframes[0])
1717                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
1718         texture->currentskinframe = texture->skinframes[0];
1719         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
1720         return success;
1721 }
1722
1723 skinfile_t *Mod_LoadSkinFiles(void)
1724 {
1725         int i, words, numtags, line, tagsetsused = false, wordsoverflow;
1726         char *text;
1727         const char *data;
1728         skinfile_t *skinfile = NULL, *first = NULL;
1729         skinfileitem_t *skinfileitem;
1730         char word[10][MAX_QPATH];
1731         overridetagnameset_t tagsets[MAX_SKINS];
1732         overridetagname_t tags[256];
1733
1734 /*
1735 sample file:
1736 U_bodyBox,models/players/Legoman/BikerA2.tga
1737 U_RArm,models/players/Legoman/BikerA1.tga
1738 U_LArm,models/players/Legoman/BikerA1.tga
1739 U_armor,common/nodraw
1740 U_sword,common/nodraw
1741 U_shield,common/nodraw
1742 U_homb,common/nodraw
1743 U_backpack,common/nodraw
1744 U_colcha,common/nodraw
1745 tag_head,
1746 tag_weapon,
1747 tag_torso,
1748 */
1749         memset(tagsets, 0, sizeof(tagsets));
1750         memset(word, 0, sizeof(word));
1751         for (i = 0;i < MAX_SKINS && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
1752         {
1753                 numtags = 0;
1754
1755                 // If it's the first file we parse
1756                 if (skinfile == NULL)
1757                 {
1758                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1759                         first = skinfile;
1760                 }
1761                 else
1762                 {
1763                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1764                         skinfile = skinfile->next;
1765                 }
1766                 skinfile->next = NULL;
1767
1768                 for(line = 0;;line++)
1769                 {
1770                         // parse line
1771                         if (!COM_ParseToken_QuakeC(&data, true))
1772                                 break;
1773                         if (!strcmp(com_token, "\n"))
1774                                 continue;
1775                         words = 0;
1776                         wordsoverflow = false;
1777                         do
1778                         {
1779                                 if (words < 10)
1780                                         strlcpy(word[words++], com_token, sizeof (word[0]));
1781                                 else
1782                                         wordsoverflow = true;
1783                         }
1784                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
1785                         if (wordsoverflow)
1786                         {
1787                                 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: line with too many statements, skipping\n", loadmodel->name, i, line);
1788                                 continue;
1789                         }
1790                         // words is always >= 1
1791                         if (!strcmp(word[0], "replace"))
1792                         {
1793                                 if (words == 3)
1794                                 {
1795                                         Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
1796                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1797                                         skinfileitem->next = skinfile->items;
1798                                         skinfile->items = skinfileitem;
1799                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
1800                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1801                                 }
1802                                 else
1803                                         Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: wrong number of parameters to command \"%s\", see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line, word[0]);
1804                         }
1805                         else if (words == 2 && !strcmp(word[1], ","))
1806                         {
1807                                 // tag name, like "tag_weapon,"
1808                                 Con_DPrintf("Mod_LoadSkinFiles: parsed tag #%i \"%s\"\n", numtags, word[0]);
1809                                 memset(tags + numtags, 0, sizeof(tags[numtags]));
1810                                 strlcpy (tags[numtags].name, word[0], sizeof (tags[numtags].name));
1811                                 numtags++;
1812                         }
1813                         else if (words == 3 && !strcmp(word[1], ","))
1814                         {
1815                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
1816                                 Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
1817                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1818                                 skinfileitem->next = skinfile->items;
1819                                 skinfile->items = skinfileitem;
1820                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
1821                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1822                         }
1823                         else
1824                                 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: does not look like tag or mesh specification, or replace command, see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line);
1825                 }
1826                 Mem_Free(text);
1827
1828                 if (numtags)
1829                 {
1830                         overridetagnameset_t *t;
1831                         t = tagsets + i;
1832                         t->num_overridetagnames = numtags;
1833                         t->data_overridetagnames = (overridetagname_t *)Mem_Alloc(loadmodel->mempool, t->num_overridetagnames * sizeof(overridetagname_t));
1834                         memcpy(t->data_overridetagnames, tags, t->num_overridetagnames * sizeof(overridetagname_t));
1835                         tagsetsused = true;
1836                 }
1837         }
1838         if (tagsetsused)
1839         {
1840                 loadmodel->data_overridetagnamesforskin = (overridetagnameset_t *)Mem_Alloc(loadmodel->mempool, i * sizeof(overridetagnameset_t));
1841                 memcpy(loadmodel->data_overridetagnamesforskin, tagsets, i * sizeof(overridetagnameset_t));
1842         }
1843         if (i)
1844                 loadmodel->numskins = i;
1845         return first;
1846 }
1847
1848 void Mod_FreeSkinFiles(skinfile_t *skinfile)
1849 {
1850         skinfile_t *next;
1851         skinfileitem_t *skinfileitem, *nextitem;
1852         for (;skinfile;skinfile = next)
1853         {
1854                 next = skinfile->next;
1855                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
1856                 {
1857                         nextitem = skinfileitem->next;
1858                         Mem_Free(skinfileitem);
1859                 }
1860                 Mem_Free(skinfile);
1861         }
1862 }
1863
1864 int Mod_CountSkinFiles(skinfile_t *skinfile)
1865 {
1866         int i;
1867         for (i = 0;skinfile;skinfile = skinfile->next, i++);
1868         return i;
1869 }
1870
1871 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
1872 {
1873         int i;
1874         double isnap = 1.0 / snap;
1875         for (i = 0;i < numvertices*numcomponents;i++)
1876                 vertices[i] = floor(vertices[i]*isnap)*snap;
1877 }
1878
1879 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
1880 {
1881         int i, outtriangles;
1882         float d, edgedir[3], temp[3];
1883         // a degenerate triangle is one with no width (thickness, surface area)
1884         // these are characterized by having all 3 points colinear (along a line)
1885         // or having two points identical
1886         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
1887         {
1888                 // calculate first edge
1889                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir);
1890                 if (VectorLength2(edgedir) < 0.0001f)
1891                         continue; // degenerate first edge (no length)
1892                 VectorNormalize(edgedir);
1893                 // check if third point is on the edge (colinear)
1894                 d = -DotProduct(vertex3f + inelement3i[2] * 3, edgedir);
1895                 VectorMA(vertex3f + inelement3i[2] * 3, d, edgedir, temp);
1896                 if (VectorLength2(temp) < 0.0001f)
1897                         continue; // third point colinear with first edge
1898                 // valid triangle (no colinear points, no duplicate points)
1899                 VectorCopy(inelement3i, outelement3i);
1900                 outelement3i += 3;
1901                 outtriangles++;
1902         }
1903         return outtriangles;
1904 }
1905
1906 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
1907 {
1908         int i, e;
1909         int firstvertex, lastvertex;
1910         if (numelements > 0 && elements)
1911         {
1912                 firstvertex = lastvertex = elements[0];
1913                 for (i = 1;i < numelements;i++)
1914                 {
1915                         e = elements[i];
1916                         firstvertex = min(firstvertex, e);
1917                         lastvertex = max(lastvertex, e);
1918                 }
1919         }
1920         else
1921                 firstvertex = lastvertex = 0;
1922         if (firstvertexpointer)
1923                 *firstvertexpointer = firstvertex;
1924         if (lastvertexpointer)
1925                 *lastvertexpointer = lastvertex;
1926 }
1927
1928 static void Mod_BuildVBOs(void)
1929 {
1930         if (!gl_support_arb_vertex_buffer_object)
1931                 return;
1932
1933         // element buffer is easy because it's just one array
1934         if (loadmodel->surfmesh.num_triangles)
1935                 loadmodel->surfmesh.ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name);
1936
1937         // vertex buffer is several arrays and we put them in the same buffer
1938         //
1939         // is this wise?  the texcoordtexture2f array is used with dynamic
1940         // vertex/svector/tvector/normal when rendering animated models, on the
1941         // other hand animated models don't use a lot of vertices anyway...
1942         if (loadmodel->surfmesh.num_vertices)
1943         {
1944                 size_t size;
1945                 unsigned char *mem;
1946                 size = 0;
1947                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1948                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1949                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1950                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1951                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1952                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1953                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
1954                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1955                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1956                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1957                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1958                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1959                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
1960                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
1961                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
1962                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
1963                 Mem_Free(mem);
1964         }
1965 }