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