]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_shared.c
added tracking of memory usage of VBO/EBO buffers
[xonotic/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 skins (so they become blurrier in the distance), disabled by default because it tends to blur with strange border colors from the skin"};
30
31 model_t *loadmodel;
32
33 #if 0
34 // LordHavoc: was 512
35 static int mod_numknown = 0;
36 static int mod_maxknown = 0;
37 static model_t *mod_known = NULL;
38 #else
39 // LordHavoc: was 512
40 #define MAX_MOD_KNOWN (MAX_MODELS + 256)
41 static int mod_numknown = 0;
42 static int mod_maxknown = MAX_MOD_KNOWN;
43 static model_t mod_known[MAX_MOD_KNOWN];
44 #endif
45
46 static void mod_start(void)
47 {
48         int i;
49         model_t *mod;
50
51         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
52                 if (mod->name[0] && mod->name[0] != '*')
53                         if (mod->used)
54                                 Mod_LoadModel(mod, true, false, mod->isworldmodel);
55 }
56
57 static void mod_shutdown(void)
58 {
59         int i;
60         model_t *mod;
61
62         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
63                 if (mod->loaded || mod->mempool)
64                         Mod_UnloadModel(mod);
65 }
66
67 static void mod_newmap(void)
68 {
69         msurface_t *surface;
70         int i, j, k, numtextures, surfacenum, ssize, tsize;
71
72         R_SkinFrame_PrepareForPurge();
73         for (i = 0;i < mod_numknown;i++)
74         {
75                 if (mod_known[i].mempool && mod_known[i].data_textures)
76                 {
77                         numtextures = mod_known[i].num_textures;
78                         // models can have multiple sets of textures
79                         if (mod_known[i].numskins > 1)
80                                 numtextures *= mod_known[i].numskins;
81                         for (j = 0;j < numtextures;j++)
82                         {
83                                 for (k = 0;k < mod_known[i].data_textures[j].numskinframes;k++)
84                                         R_SkinFrame_MarkUsed(mod_known[i].data_textures[j].skinframes[k]);
85                                 for (k = 0;k < mod_known[i].data_textures[j].backgroundnumskinframes;k++)
86                                         R_SkinFrame_MarkUsed(mod_known[i].data_textures[j].backgroundskinframes[k]);
87                         }
88                 }
89         }
90         R_SkinFrame_Purge();
91
92         if (!cl_stainmaps_clearonload.integer)
93                 return;
94
95         for (i = 0;i < mod_numknown;i++)
96         {
97                 if (mod_known[i].mempool && mod_known[i].data_surfaces)
98                 {
99                         for (surfacenum = 0, surface = mod_known[i].data_surfaces;surfacenum < mod_known[i].num_surfaces;surfacenum++, surface++)
100                         {
101                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
102                                 {
103                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
104                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
105                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
106                                         surface->cached_dlight = true;
107                                 }
108                         }
109                 }
110         }
111 }
112
113 /*
114 ===============
115 Mod_Init
116 ===============
117 */
118 static void Mod_Print(void);
119 static void Mod_Precache (void);
120 static void Mod_BuildVBOs(void);
121 void Mod_Init (void)
122 {
123         Mod_BrushInit();
124         Mod_AliasInit();
125         Mod_SpriteInit();
126
127         Cvar_RegisterVariable(&r_mipskins);
128         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
129         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
130 }
131
132 void Mod_RenderInit(void)
133 {
134         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
135 }
136
137 void Mod_UnloadModel (model_t *mod)
138 {
139         char name[MAX_QPATH];
140         qboolean isworldmodel;
141         qboolean used;
142         strlcpy(name, mod->name, sizeof(name));
143         isworldmodel = mod->isworldmodel;
144         used = mod->used;
145         if (mod->surfmesh.ebo)
146                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo);
147         if (mod->surfmesh.vbo)
148                 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
149         // free textures/memory attached to the model
150         R_FreeTexturePool(&mod->texturepool);
151         Mem_FreePool(&mod->mempool);
152         // clear the struct to make it available
153         memset(mod, 0, sizeof(model_t));
154         // restore the fields we want to preserve
155         strlcpy(mod->name, name, sizeof(mod->name));
156         mod->isworldmodel = isworldmodel;
157         mod->used = used;
158         mod->loaded = false;
159 }
160
161 /*
162 ==================
163 Mod_LoadModel
164
165 Loads a model
166 ==================
167 */
168 model_t *Mod_LoadModel(model_t *mod, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
169 {
170         int num;
171         unsigned int crc;
172         void *buf;
173         fs_offset_t filesize;
174
175         mod->used = true;
176
177         if (mod->name[0] == '*') // submodel
178                 return mod;
179
180         crc = 0;
181         buf = NULL;
182
183         // even if the model is loaded it still may need reloading...
184
185         // if the model is a worldmodel and is being referred to as a
186         // non-worldmodel here, then it needs reloading to get rid of the
187         // submodels
188         if (mod->isworldmodel != isworldmodel)
189                 mod->loaded = false;
190
191         // if it is not loaded or checkdisk is true we need to calculate the crc
192         if (!mod->loaded || checkdisk)
193         {
194                 if (checkdisk && mod->loaded)
195                         Con_DPrintf("checking model %s\n", mod->name);
196                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
197                 if (buf)
198                 {
199                         crc = CRC_Block((unsigned char *)buf, filesize);
200                         // we need to reload the model if the crc does not match
201                         if (mod->crc != crc)
202                                 mod->loaded = false;
203                 }
204         }
205
206         // if the model is already loaded and checks passed, just return
207         if (mod->loaded)
208         {
209                 if (buf)
210                         Mem_Free(buf);
211                 return mod;
212         }
213
214         Con_DPrintf("loading model %s\n", mod->name);
215         // LordHavoc: unload the existing model in this slot (if there is one)
216         if (mod->loaded || mod->mempool)
217                 Mod_UnloadModel(mod);
218
219         // load the model
220         mod->isworldmodel = isworldmodel;
221         mod->used = true;
222         mod->crc = crc;
223         // errors can prevent the corresponding mod->loaded = true;
224         mod->loaded = false;
225
226         // default model radius and bounding box (mainly for missing models)
227         mod->radius = 16;
228         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
229         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
230         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
231         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
232         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
233         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
234
235         if (buf)
236         {
237                 char *bufend = (char *)buf + filesize;
238
239                 // all models use memory, so allocate a memory pool
240                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
241
242                 num = LittleLong(*((int *)buf));
243                 // call the apropriate loader
244                 loadmodel = mod;
245                      if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
246                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
247                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
248                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
249                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
250                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
251                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
252                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
253                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
254                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
255                 else if (!memcmp(buf, "MCBSPpad", 8)) Mod_Q1BSP_Load(mod, buf, bufend);
256                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
257                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
258                 Mem_Free(buf);
259
260                 Mod_BuildVBOs();
261
262                 // no fatal errors occurred, so this model is ready to use.
263                 mod->loaded = true;
264         }
265         else if (crash)
266         {
267                 // LordHavoc: Sys_Error was *ANNOYING*
268                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
269         }
270         return mod;
271 }
272
273 void Mod_ClearUsed(void)
274 {
275 #if 0
276         int i;
277         model_t *mod;
278
279         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
280                 if (mod->name[0])
281                         mod->used = false;
282 #endif
283 }
284
285 void Mod_PurgeUnused(void)
286 {
287         int i;
288         model_t *mod;
289
290         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
291                 if (mod->name[0])
292                         if (!mod->used)
293                                 Mod_UnloadModel(mod);
294 }
295
296 // only used during loading!
297 void Mod_RemoveStaleWorldModels(model_t *skip)
298 {
299         int i;
300         model_t *mod;
301
302         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
303         {
304                 if (mod->isworldmodel && mod->loaded && skip != mod)
305                 {
306                         Mod_UnloadModel(mod);
307                         mod->isworldmodel = false;
308                         mod->used = false;
309                 }
310         }
311 }
312
313 /*
314 ==================
315 Mod_FindName
316
317 ==================
318 */
319 model_t *Mod_FindName(const char *name)
320 {
321         int i;
322         model_t *mod;
323
324         if (!name[0])
325                 Host_Error ("Mod_ForName: NULL name");
326
327 // search the currently loaded models
328         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
329         {
330                 if (mod->name[0] && !strcmp(mod->name, name))
331                 {
332                         mod->used = true;
333                         return mod;
334                 }
335         }
336
337         // no match found, find room for a new one
338         for (i = 0;i < mod_numknown;i++)
339                 if (!mod_known[i].name[0])
340                         break;
341
342         if (mod_maxknown == i)
343         {
344 #if 0
345                 model_t *old;
346                 mod_maxknown += 256;
347                 old = mod_known;
348                 mod_known = Mem_Alloc(mod_mempool, mod_maxknown * sizeof(model_t));
349                 if (old)
350                 {
351                         memcpy(mod_known, old, mod_numknown * sizeof(model_t));
352                         Mem_Free(old);
353                 }
354 #else
355                 Host_Error ("Mod_FindName: ran out of models");
356 #endif
357         }
358         if (mod_numknown == i)
359                 mod_numknown++;
360         mod = mod_known + i;
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()
391 {
392         int i;
393         model_t *mod;
394
395         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
396                 if (mod->name[0] && mod->name[0] != '*')
397                         if (mod->used)
398                                 Mod_LoadModel(mod, true, true, mod->isworldmodel);
399 }
400
401 unsigned char *mod_base;
402
403
404 //=============================================================================
405
406 /*
407 ================
408 Mod_Print
409 ================
410 */
411 static void Mod_Print(void)
412 {
413         int             i;
414         model_t *mod;
415
416         Con_Print("Loaded models:\n");
417         for (i = 0, mod = mod_known;i < mod_numknown;i++, mod++)
418                 if (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] * 3 + vertex14f[1] * 5 + vertex14f[2] * 7) % 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_GetTerrainVertex3fTexCoord2fFromRGBA(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_GetTerrainVertexFromRGBA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
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_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1072         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1073         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1074         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1075         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(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_ConstructTerrainPatchFromRGBA(const unsigned char *imagepixels, int imagewidth, int imageheight, int x1, int y1, int width, int height, int *element3i, int *neighbor3i, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
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_GetTerrainVertexFromRGBA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1112 }
1113
1114 skinfile_t *Mod_LoadSkinFiles(void)
1115 {
1116         int i, words, numtags, line, tagsetsused = false, wordsoverflow;
1117         char *text;
1118         const char *data;
1119         skinfile_t *skinfile = NULL, *first = NULL;
1120         skinfileitem_t *skinfileitem;
1121         char word[10][MAX_QPATH];
1122         overridetagnameset_t tagsets[MAX_SKINS];
1123         overridetagname_t tags[256];
1124
1125 /*
1126 sample file:
1127 U_bodyBox,models/players/Legoman/BikerA2.tga
1128 U_RArm,models/players/Legoman/BikerA1.tga
1129 U_LArm,models/players/Legoman/BikerA1.tga
1130 U_armor,common/nodraw
1131 U_sword,common/nodraw
1132 U_shield,common/nodraw
1133 U_homb,common/nodraw
1134 U_backpack,common/nodraw
1135 U_colcha,common/nodraw
1136 tag_head,
1137 tag_weapon,
1138 tag_torso,
1139 */
1140         memset(tagsets, 0, sizeof(tagsets));
1141         memset(word, 0, sizeof(word));
1142         for (i = 0;i < MAX_SKINS && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
1143         {
1144                 numtags = 0;
1145
1146                 // If it's the first file we parse
1147                 if (skinfile == NULL)
1148                 {
1149                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1150                         first = skinfile;
1151                 }
1152                 else
1153                 {
1154                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1155                         skinfile = skinfile->next;
1156                 }
1157                 skinfile->next = NULL;
1158
1159                 for(line = 0;;line++)
1160                 {
1161                         // parse line
1162                         if (!COM_ParseToken(&data, true))
1163                                 break;
1164                         if (!strcmp(com_token, "\n"))
1165                                 continue;
1166                         words = 0;
1167                         wordsoverflow = false;
1168                         do
1169                         {
1170                                 if (words < 10)
1171                                         strlcpy(word[words++], com_token, sizeof (word[0]));
1172                                 else
1173                                         wordsoverflow = true;
1174                         }
1175                         while (COM_ParseToken(&data, true) && strcmp(com_token, "\n"));
1176                         if (wordsoverflow)
1177                         {
1178                                 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);
1179                                 continue;
1180                         }
1181                         // words is always >= 1
1182                         if (!strcmp(word[0], "replace"))
1183                         {
1184                                 if (words == 3)
1185                                 {
1186                                         Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
1187                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1188                                         skinfileitem->next = skinfile->items;
1189                                         skinfile->items = skinfileitem;
1190                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
1191                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1192                                 }
1193                                 else
1194                                         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]);
1195                         }
1196                         else if (words == 2 && !strcmp(word[1], ","))
1197                         {
1198                                 // tag name, like "tag_weapon,"
1199                                 Con_DPrintf("Mod_LoadSkinFiles: parsed tag #%i \"%s\"\n", numtags, word[0]);
1200                                 memset(tags + numtags, 0, sizeof(tags[numtags]));
1201                                 strlcpy (tags[numtags].name, word[0], sizeof (tags[numtags].name));
1202                                 numtags++;
1203                         }
1204                         else if (words == 3 && !strcmp(word[1], ","))
1205                         {
1206                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
1207                                 Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
1208                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1209                                 skinfileitem->next = skinfile->items;
1210                                 skinfile->items = skinfileitem;
1211                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
1212                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1213                         }
1214                         else
1215                                 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);
1216                 }
1217                 Mem_Free(text);
1218
1219                 if (numtags)
1220                 {
1221                         overridetagnameset_t *t;
1222                         t = tagsets + i;
1223                         t->num_overridetagnames = numtags;
1224                         t->data_overridetagnames = (overridetagname_t *)Mem_Alloc(loadmodel->mempool, t->num_overridetagnames * sizeof(overridetagname_t));
1225                         memcpy(t->data_overridetagnames, tags, t->num_overridetagnames * sizeof(overridetagname_t));
1226                         tagsetsused = true;
1227                 }
1228         }
1229         if (tagsetsused)
1230         {
1231                 loadmodel->data_overridetagnamesforskin = (overridetagnameset_t *)Mem_Alloc(loadmodel->mempool, i * sizeof(overridetagnameset_t));
1232                 memcpy(loadmodel->data_overridetagnamesforskin, tagsets, i * sizeof(overridetagnameset_t));
1233         }
1234         if (i)
1235                 loadmodel->numskins = i;
1236         return first;
1237 }
1238
1239 void Mod_FreeSkinFiles(skinfile_t *skinfile)
1240 {
1241         skinfile_t *next;
1242         skinfileitem_t *skinfileitem, *nextitem;
1243         for (;skinfile;skinfile = next)
1244         {
1245                 next = skinfile->next;
1246                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
1247                 {
1248                         nextitem = skinfileitem->next;
1249                         Mem_Free(skinfileitem);
1250                 }
1251                 Mem_Free(skinfile);
1252         }
1253 }
1254
1255 int Mod_CountSkinFiles(skinfile_t *skinfile)
1256 {
1257         int i;
1258         for (i = 0;skinfile;skinfile = skinfile->next, i++);
1259         return i;
1260 }
1261
1262 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
1263 {
1264         int i;
1265         double isnap = 1.0 / snap;
1266         for (i = 0;i < numvertices*numcomponents;i++)
1267                 vertices[i] = floor(vertices[i]*isnap)*snap;
1268 }
1269
1270 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
1271 {
1272         int i, outtriangles;
1273         float d, edgedir[3], temp[3];
1274         // a degenerate triangle is one with no width (thickness, surface area)
1275         // these are characterized by having all 3 points colinear (along a line)
1276         // or having two points identical
1277         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
1278         {
1279                 // calculate first edge
1280                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir);
1281                 if (VectorLength2(edgedir) < 0.0001f)
1282                         continue; // degenerate first edge (no length)
1283                 VectorNormalize(edgedir);
1284                 // check if third point is on the edge (colinear)
1285                 d = -DotProduct(vertex3f + inelement3i[2] * 3, edgedir);
1286                 VectorMA(vertex3f + inelement3i[2] * 3, d, edgedir, temp);
1287                 if (VectorLength2(temp) < 0.0001f)
1288                         continue; // third point colinear with first edge
1289                 // valid triangle (no colinear points, no duplicate points)
1290                 VectorCopy(inelement3i, outelement3i);
1291                 outelement3i += 3;
1292                 outtriangles++;
1293         }
1294         return outtriangles;
1295 }
1296
1297 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
1298 {
1299         int i, e;
1300         int firstvertex, lastvertex;
1301         if (numelements > 0 && elements)
1302         {
1303                 firstvertex = lastvertex = elements[0];
1304                 for (i = 1;i < numelements;i++)
1305                 {
1306                         e = elements[i];
1307                         firstvertex = min(firstvertex, e);
1308                         lastvertex = max(lastvertex, e);
1309                 }
1310         }
1311         else
1312                 firstvertex = lastvertex = 0;
1313         if (firstvertexpointer)
1314                 *firstvertexpointer = firstvertex;
1315         if (lastvertexpointer)
1316                 *lastvertexpointer = lastvertex;
1317 }
1318
1319 static void Mod_BuildVBOs(void)
1320 {
1321         if (!gl_support_arb_vertex_buffer_object)
1322                 return;
1323
1324         // element buffer is easy because it's just one array
1325         if (loadmodel->surfmesh.num_triangles)
1326                 loadmodel->surfmesh.ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name);
1327
1328         // vertex buffer is several arrays and we put them in the same buffer
1329         //
1330         // is this wise?  the texcoordtexture2f array is used with dynamic
1331         // vertex/svector/tvector/normal when rendering animated models, on the
1332         // other hand animated models don't use a lot of vertices anyway...
1333         if (loadmodel->surfmesh.num_vertices)
1334         {
1335                 size_t size;
1336                 unsigned char *mem;
1337                 size = 0;
1338                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1339                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1340                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1341                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1342                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1343                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1344                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
1345                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1346                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1347                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1348                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1349                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1350                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
1351                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
1352                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
1353                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
1354                 Mem_Free(mem);
1355         }
1356 }