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