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