it is now possible to have multiple map models loaded at once - removed
[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 dp_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         dp_model_t *mod;
56
57         for (i = 0;i < nummodels;i++)
58                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
59                         if (mod->used)
60                                 Mod_LoadModel(mod, true, false);
61 }
62
63 static void mod_shutdown(void)
64 {
65         int i;
66         int nummodels = Mem_ExpandableArray_IndexRange(&models);
67         dp_model_t *mod;
68
69         for (i = 0;i < nummodels;i++)
70                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
71                         Mod_UnloadModel(mod);
72
73         Mod_FreeQ3Shaders();
74 }
75
76 static void mod_newmap(void)
77 {
78         msurface_t *surface;
79         int i, j, k, surfacenum, ssize, tsize;
80         int nummodels = Mem_ExpandableArray_IndexRange(&models);
81         dp_model_t *mod;
82
83         R_SkinFrame_PrepareForPurge();
84         for (i = 0;i < nummodels;i++)
85         {
86                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_textures)
87                 {
88                         for (j = 0;j < mod->num_textures;j++)
89                         {
90                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
91                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
92                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
93                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
94                         }
95                 }
96         }
97         R_SkinFrame_Purge();
98
99         if (!cl_stainmaps_clearonload.integer)
100                 return;
101
102         for (i = 0;i < nummodels;i++)
103         {
104                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
105                 {
106                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
107                         {
108                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
109                                 {
110                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
111                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
112                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
113                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
114                                 }
115                         }
116                 }
117         }
118 }
119
120 /*
121 ===============
122 Mod_Init
123 ===============
124 */
125 static void Mod_Print(void);
126 static void Mod_Precache (void);
127 static void Mod_Decompile_f(void);
128 static void Mod_BuildVBOs(void);
129 void Mod_Init (void)
130 {
131         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
132         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
133
134         Mod_BrushInit();
135         Mod_AliasInit();
136         Mod_SpriteInit();
137
138         Cvar_RegisterVariable(&r_mipskins);
139         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
140         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
141         Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
142 }
143
144 void Mod_RenderInit(void)
145 {
146         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
147 }
148
149 void Mod_UnloadModel (dp_model_t *mod)
150 {
151         char name[MAX_QPATH];
152         qboolean used;
153         dp_model_t *parentmodel;
154
155         if (developer_loading.integer)
156                 Con_Printf("unloading model %s\n", mod->name);
157
158         strlcpy(name, mod->name, sizeof(name));
159         parentmodel = mod->brush.parentmodel;
160         used = mod->used;
161         if (mod->surfmesh.ebo3i)
162                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3i);
163         if (mod->surfmesh.ebo3s)
164                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3s);
165         if (mod->surfmesh.vbo)
166                 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
167         // free textures/memory attached to the model
168         R_FreeTexturePool(&mod->texturepool);
169         Mem_FreePool(&mod->mempool);
170         // clear the struct to make it available
171         memset(mod, 0, sizeof(dp_model_t));
172         // restore the fields we want to preserve
173         strlcpy(mod->name, name, sizeof(mod->name));
174         mod->brush.parentmodel = parentmodel;
175         mod->used = used;
176         mod->loaded = false;
177 }
178
179 void R_Model_Null_Draw(entity_render_t *ent)
180 {
181         return;
182 }
183
184 /*
185 ==================
186 Mod_LoadModel
187
188 Loads a model
189 ==================
190 */
191 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
192 {
193         int num;
194         unsigned int crc;
195         void *buf;
196         fs_offset_t filesize;
197
198         mod->used = true;
199
200         if (mod->name[0] == '*') // submodel
201                 return mod;
202         
203         if (!strcmp(mod->name, "null"))
204         {
205                 if(mod->loaded)
206                         return mod;
207
208                 if (mod->loaded || mod->mempool)
209                         Mod_UnloadModel(mod);
210
211                 if (developer_loading.integer)
212                         Con_Printf("loading model %s\n", mod->name);
213
214                 mod->used = true;
215                 mod->crc = -1;
216                 mod->loaded = false;
217
218                 VectorClear(mod->normalmins);
219                 VectorClear(mod->normalmaxs);
220                 VectorClear(mod->yawmins);
221                 VectorClear(mod->yawmaxs);
222                 VectorClear(mod->rotatedmins);
223                 VectorClear(mod->rotatedmaxs);
224
225                 mod->modeldatatypestring = "null";
226                 mod->type = mod_null;
227                 mod->Draw = R_Model_Null_Draw;
228                 mod->numframes = 2;
229                 mod->numskins = 1;
230
231                 // no fatal errors occurred, so this model is ready to use.
232                 mod->loaded = true;
233
234                 return mod;
235         }
236
237         crc = 0;
238         buf = NULL;
239
240         // even if the model is loaded it still may need reloading...
241
242         // if it is not loaded or checkdisk is true we need to calculate the crc
243         if (!mod->loaded || checkdisk)
244         {
245                 if (checkdisk && mod->loaded)
246                         Con_DPrintf("checking model %s\n", mod->name);
247                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
248                 if (buf)
249                 {
250                         crc = CRC_Block((unsigned char *)buf, filesize);
251                         // we need to reload the model if the crc does not match
252                         if (mod->crc != crc)
253                                 mod->loaded = false;
254                 }
255         }
256
257         // if the model is already loaded and checks passed, just return
258         if (mod->loaded)
259         {
260                 if (buf)
261                         Mem_Free(buf);
262                 return mod;
263         }
264
265         if (developer_loading.integer)
266                 Con_Printf("loading model %s\n", mod->name);
267
268         // LordHavoc: unload the existing model in this slot (if there is one)
269         if (mod->loaded || mod->mempool)
270                 Mod_UnloadModel(mod);
271
272         // load the model
273         mod->used = true;
274         mod->crc = crc;
275         // errors can prevent the corresponding mod->loaded = true;
276         mod->loaded = false;
277
278         // default model radius and bounding box (mainly for missing models)
279         mod->radius = 16;
280         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
281         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
282         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
283         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
284         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
285         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
286
287         if (!q3shaders_mem)
288         {
289                 // load q3 shaders for the first time, or after a level change
290                 Mod_LoadQ3Shaders();
291         }
292
293         if (buf)
294         {
295                 char *bufend = (char *)buf + filesize;
296
297                 // all models use memory, so allocate a memory pool
298                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
299
300                 num = LittleLong(*((int *)buf));
301                 // call the apropriate loader
302                 loadmodel = mod;
303                      if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
304                 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
305                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
306                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
307                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
308                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
309                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
310                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
311                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
312                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
313                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
314                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
315                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
316                 Mem_Free(buf);
317
318                 Mod_BuildVBOs();
319
320                 // no fatal errors occurred, so this model is ready to use.
321                 mod->loaded = true;
322         }
323         else if (crash)
324         {
325                 // LordHavoc: Sys_Error was *ANNOYING*
326                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
327         }
328         return mod;
329 }
330
331 void Mod_ClearUsed(void)
332 {
333         int i;
334         int nummodels = Mem_ExpandableArray_IndexRange(&models);
335         dp_model_t *mod;
336         for (i = 0;i < nummodels;i++)
337                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
338                         mod->used = false;
339 }
340
341 void Mod_PurgeUnused(void)
342 {
343         int i;
344         int nummodels = Mem_ExpandableArray_IndexRange(&models);
345         dp_model_t *mod;
346         for (i = 0;i < nummodels;i++)
347         {
348                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
349                 {
350                         Mod_UnloadModel(mod);
351                         Mem_ExpandableArray_FreeRecord(&models, mod);
352                 }
353         }
354 }
355
356 /*
357 ==================
358 Mod_FindName
359
360 ==================
361 */
362 dp_model_t *Mod_FindName(const char *name, const char *parentname)
363 {
364         int i;
365         int nummodels;
366         dp_model_t *mod;
367
368         if (!parentname)
369                 parentname = "";
370
371         // if we're not dedicatd, the renderer calls will crash without video
372         Host_StartVideo();
373
374         nummodels = Mem_ExpandableArray_IndexRange(&models);
375
376         if (!name[0])
377                 Host_Error ("Mod_ForName: NULL name");
378
379         // search the currently loaded models
380         for (i = 0;i < nummodels;i++)
381         {
382                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name) && ((!mod->brush.parentmodel && !parentname[0]) || (mod->brush.parentmodel && parentname[0] && !strcmp(mod->brush.parentmodel->name, parentname))))
383                 {
384                         mod->used = true;
385                         return mod;
386                 }
387         }
388
389         // no match found, create a new one
390         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
391         strlcpy(mod->name, name, sizeof(mod->name));
392         if (parentname[0])
393                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
394         else
395                 mod->brush.parentmodel = NULL;
396         mod->loaded = false;
397         mod->used = true;
398         return mod;
399 }
400
401 /*
402 ==================
403 Mod_ForName
404
405 Loads in a model for the given name
406 ==================
407 */
408 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
409 {
410         dp_model_t *model;
411         model = Mod_FindName(name, parentname);
412         if (!model->loaded || checkdisk)
413                 Mod_LoadModel(model, crash, checkdisk);
414         return model;
415 }
416
417 /*
418 ==================
419 Mod_Reload
420
421 Reloads all models if they have changed
422 ==================
423 */
424 void Mod_Reload(void)
425 {
426         int i;
427         int nummodels = Mem_ExpandableArray_IndexRange(&models);
428         dp_model_t *mod;
429         for (i = 0;i < nummodels;i++)
430                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
431                         Mod_LoadModel(mod, true, true);
432 }
433
434 unsigned char *mod_base;
435
436
437 //=============================================================================
438
439 /*
440 ================
441 Mod_Print
442 ================
443 */
444 static void Mod_Print(void)
445 {
446         int i;
447         int nummodels = Mem_ExpandableArray_IndexRange(&models);
448         dp_model_t *mod;
449
450         Con_Print("Loaded models:\n");
451         for (i = 0;i < nummodels;i++)
452         {
453                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
454                 {
455                         if (mod->brush.numsubmodels)
456                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
457                         else
458                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
459                 }
460         }
461 }
462
463 /*
464 ================
465 Mod_Precache
466 ================
467 */
468 static void Mod_Precache(void)
469 {
470         if (Cmd_Argc() == 2)
471                 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
472         else
473                 Con_Print("usage: modelprecache <filename>\n");
474 }
475
476 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
477 {
478         int i, count;
479         unsigned char *used;
480         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
481         memset(used, 0, numvertices);
482         for (i = 0;i < numelements;i++)
483                 used[elements[i]] = 1;
484         for (i = 0, count = 0;i < numvertices;i++)
485                 remapvertices[i] = used[i] ? count++ : -1;
486         Mem_Free(used);
487         return count;
488 }
489
490 #if 1
491 // fast way, using an edge hash
492 #define TRIANGLEEDGEHASH 8192
493 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
494 {
495         int i, j, p, e1, e2, *n, hashindex, count, match;
496         const int *e;
497         typedef struct edgehashentry_s
498         {
499                 struct edgehashentry_s *next;
500                 int triangle;
501                 int element[2];
502         }
503         edgehashentry_t;
504         edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
505         memset(edgehash, 0, sizeof(edgehash));
506         edgehashentries = edgehashentriesbuffer;
507         // if there are too many triangles for the stack array, allocate larger buffer
508         if (numtriangles > TRIANGLEEDGEHASH)
509                 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
510         // find neighboring triangles
511         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
512         {
513                 for (j = 0, p = 2;j < 3;p = j, j++)
514                 {
515                         e1 = e[p];
516                         e2 = e[j];
517                         // this hash index works for both forward and backward edges
518                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
519                         hash = edgehashentries + i * 3 + j;
520                         hash->next = edgehash[hashindex];
521                         edgehash[hashindex] = hash;
522                         hash->triangle = i;
523                         hash->element[0] = e1;
524                         hash->element[1] = e2;
525                 }
526         }
527         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
528         {
529                 for (j = 0, p = 2;j < 3;p = j, j++)
530                 {
531                         e1 = e[p];
532                         e2 = e[j];
533                         // this hash index works for both forward and backward edges
534                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
535                         count = 0;
536                         match = -1;
537                         for (hash = edgehash[hashindex];hash;hash = hash->next)
538                         {
539                                 if (hash->element[0] == e2 && hash->element[1] == e1)
540                                 {
541                                         if (hash->triangle != i)
542                                                 match = hash->triangle;
543                                         count++;
544                                 }
545                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
546                                         count++;
547                         }
548                         // detect edges shared by three triangles and make them seams
549                         if (count > 2)
550                                 match = -1;
551                         n[p] = match;
552                 }
553
554                 // also send a keepalive here (this can take a while too!)
555                 CL_KeepaliveMessage(false);
556         }
557         // free the allocated buffer
558         if (edgehashentries != edgehashentriesbuffer)
559                 Mem_Free(edgehashentries);
560 }
561 #else
562 // very slow but simple way
563 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
564 {
565         int i, match, count;
566         count = 0;
567         match = -1;
568         for (i = 0;i < numtriangles;i++, elements += 3)
569         {
570                      if ((elements[0] == start && elements[1] == end)
571                       || (elements[1] == start && elements[2] == end)
572                       || (elements[2] == start && elements[0] == end))
573                 {
574                         if (i != ignore)
575                                 match = i;
576                         count++;
577                 }
578                 else if ((elements[1] == start && elements[0] == end)
579                       || (elements[2] == start && elements[1] == end)
580                       || (elements[0] == start && elements[2] == end))
581                         count++;
582         }
583         // detect edges shared by three triangles and make them seams
584         if (count > 2)
585                 match = -1;
586         return match;
587 }
588
589 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
590 {
591         int i, *n;
592         const int *e;
593         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
594         {
595                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
596                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
597                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
598         }
599 }
600 #endif
601
602 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
603 {
604         int i, warned = false, endvertex = firstvertex + numverts;
605         for (i = 0;i < numtriangles * 3;i++)
606         {
607                 if (elements[i] < firstvertex || elements[i] >= endvertex)
608                 {
609                         if (!warned)
610                         {
611                                 warned = true;
612                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
613                         }
614                         elements[i] = firstvertex;
615                 }
616         }
617 }
618
619 // warning: this is an expensive function!
620 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
621 {
622         int i, j;
623         const int *element;
624         float *vectorNormal;
625         float areaNormal[3];
626         // clear the vectors
627         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
628         // process each vertex of each triangle and accumulate the results
629         // use area-averaging, to make triangles with a big area have a bigger
630         // weighting on the vertex normal than triangles with a small area
631         // to do so, just add the 'normals' together (the bigger the area
632         // the greater the length of the normal is
633         element = elements;
634         for (i = 0; i < numtriangles; i++, element += 3)
635         {
636                 TriangleNormal(
637                         vertex3f + element[0] * 3,
638                         vertex3f + element[1] * 3,
639                         vertex3f + element[2] * 3,
640                         areaNormal
641                         );
642
643                 if (!areaweighting)
644                         VectorNormalize(areaNormal);
645
646                 for (j = 0;j < 3;j++)
647                 {
648                         vectorNormal = normal3f + element[j] * 3;
649                         vectorNormal[0] += areaNormal[0];
650                         vectorNormal[1] += areaNormal[1];
651                         vectorNormal[2] += areaNormal[2];
652                 }
653         }
654         // and just normalize the accumulated vertex normal in the end
655         vectorNormal = normal3f + 3 * firstvertex;
656         for (i = 0; i < numvertices; i++, vectorNormal += 3)
657                 VectorNormalize(vectorNormal);
658 }
659
660 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)
661 {
662         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
663         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
664         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
665
666         // 6 multiply, 9 subtract
667         VectorSubtract(v1, v0, v10);
668         VectorSubtract(v2, v0, v20);
669         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
670         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
671         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
672         // 12 multiply, 10 subtract
673         tc10[1] = tc1[1] - tc0[1];
674         tc20[1] = tc2[1] - tc0[1];
675         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
676         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
677         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
678         tc10[0] = tc1[0] - tc0[0];
679         tc20[0] = tc2[0] - tc0[0];
680         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
681         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
682         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
683         // 12 multiply, 4 add, 6 subtract
684         f = DotProduct(svector3f, normal3f);
685         svector3f[0] -= f * normal3f[0];
686         svector3f[1] -= f * normal3f[1];
687         svector3f[2] -= f * normal3f[2];
688         f = DotProduct(tvector3f, normal3f);
689         tvector3f[0] -= f * normal3f[0];
690         tvector3f[1] -= f * normal3f[1];
691         tvector3f[2] -= f * normal3f[2];
692         // if texture is mapped the wrong way (counterclockwise), the tangents
693         // have to be flipped, this is detected by calculating a normal from the
694         // two tangents, and seeing if it is opposite the surface normal
695         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
696         CrossProduct(tvector3f, svector3f, tangentcross);
697         if (DotProduct(tangentcross, normal3f) < 0)
698         {
699                 VectorNegate(svector3f, svector3f);
700                 VectorNegate(tvector3f, tvector3f);
701         }
702 }
703
704 // warning: this is a very expensive function!
705 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)
706 {
707         int i, tnum;
708         float sdir[3], tdir[3], normal[3], *sv, *tv;
709         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
710         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
711         const int *e;
712         // clear the vectors
713         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
714         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
715         // process each vertex of each triangle and accumulate the results
716         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
717         {
718                 v0 = vertex3f + e[0] * 3;
719                 v1 = vertex3f + e[1] * 3;
720                 v2 = vertex3f + e[2] * 3;
721                 tc0 = texcoord2f + e[0] * 2;
722                 tc1 = texcoord2f + e[1] * 2;
723                 tc2 = texcoord2f + e[2] * 2;
724
725                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
726                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
727
728                 // calculate the edge directions and surface normal
729                 // 6 multiply, 9 subtract
730                 VectorSubtract(v1, v0, v10);
731                 VectorSubtract(v2, v0, v20);
732                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
733                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
734                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
735
736                 // calculate the tangents
737                 // 12 multiply, 10 subtract
738                 tc10[1] = tc1[1] - tc0[1];
739                 tc20[1] = tc2[1] - tc0[1];
740                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
741                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
742                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
743                 tc10[0] = tc1[0] - tc0[0];
744                 tc20[0] = tc2[0] - tc0[0];
745                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
746                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
747                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
748
749                 // if texture is mapped the wrong way (counterclockwise), the tangents
750                 // have to be flipped, this is detected by calculating a normal from the
751                 // two tangents, and seeing if it is opposite the surface normal
752                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
753                 CrossProduct(tdir, sdir, tangentcross);
754                 if (DotProduct(tangentcross, normal) < 0)
755                 {
756                         VectorNegate(sdir, sdir);
757                         VectorNegate(tdir, tdir);
758                 }
759
760                 if (!areaweighting)
761                 {
762                         VectorNormalize(sdir);
763                         VectorNormalize(tdir);
764                 }
765                 for (i = 0;i < 3;i++)
766                 {
767                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
768                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
769                 }
770         }
771         // make the tangents completely perpendicular to the surface normal, and
772         // then normalize them
773         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
774         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
775         {
776                 f = -DotProduct(sv, n);
777                 VectorMA(sv, f, n, sv);
778                 VectorNormalize(sv);
779                 f = -DotProduct(tv, n);
780                 VectorMA(tv, f, n, tv);
781                 VectorNormalize(tv);
782         }
783 }
784
785 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
786 {
787         unsigned char *data;
788         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) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0));
789         loadmodel->surfmesh.num_vertices = numvertices;
790         loadmodel->surfmesh.num_triangles = numtriangles;
791         if (loadmodel->surfmesh.num_vertices)
792         {
793                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
794                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
795                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
796                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
797                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
798                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
799                 if (vertexcolors)
800                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
801                 if (lightmapoffsets)
802                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
803         }
804         if (loadmodel->surfmesh.num_triangles)
805         {
806                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
807                 if (neighbors)
808                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
809                 if (loadmodel->surfmesh.num_vertices <= 65536)
810                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
811         }
812 }
813
814 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)
815 {
816         shadowmesh_t *newmesh;
817         unsigned char *data;
818         int size;
819         size = sizeof(shadowmesh_t);
820         size += maxverts * sizeof(float[3]);
821         if (light)
822                 size += maxverts * sizeof(float[11]);
823         size += maxtriangles * sizeof(int[3]);
824         if (maxverts <= 65536)
825                 size += maxtriangles * sizeof(unsigned short[3]);
826         if (neighbors)
827                 size += maxtriangles * sizeof(int[3]);
828         if (expandable)
829                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
830         data = (unsigned char *)Mem_Alloc(mempool, size);
831         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
832         newmesh->map_diffuse = map_diffuse;
833         newmesh->map_specular = map_specular;
834         newmesh->map_normal = map_normal;
835         newmesh->maxverts = maxverts;
836         newmesh->maxtriangles = maxtriangles;
837         newmesh->numverts = 0;
838         newmesh->numtriangles = 0;
839
840         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
841         if (light)
842         {
843                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
844                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
845                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
846                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
847         }
848         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
849         if (neighbors)
850         {
851                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
852         }
853         if (expandable)
854         {
855                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
856                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
857         }
858         if (maxverts <= 65536)
859                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
860         return newmesh;
861 }
862
863 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
864 {
865         shadowmesh_t *newmesh;
866         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
867         newmesh->numverts = oldmesh->numverts;
868         newmesh->numtriangles = oldmesh->numtriangles;
869
870         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
871         if (newmesh->svector3f && oldmesh->svector3f)
872         {
873                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
874                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
875                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
876                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
877         }
878         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
879         if (newmesh->neighbor3i && oldmesh->neighbor3i)
880                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
881         return newmesh;
882 }
883
884 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
885 {
886         int hashindex, vnum;
887         shadowmeshvertexhash_t *hash;
888         // this uses prime numbers intentionally
889         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
890         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
891         {
892                 vnum = (hash - mesh->vertexhashentries);
893                 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]))
894                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
895                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
896                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
897                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
898                         return hash - mesh->vertexhashentries;
899         }
900         vnum = mesh->numverts++;
901         hash = mesh->vertexhashentries + vnum;
902         hash->next = mesh->vertexhashtable[hashindex];
903         mesh->vertexhashtable[hashindex] = hash;
904         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
905         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
906         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
907         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
908         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
909         return vnum;
910 }
911
912 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
913 {
914         if (mesh->numtriangles == 0)
915         {
916                 // set the properties on this empty mesh to be more favorable...
917                 // (note: this case only occurs for the first triangle added to a new mesh chain)
918                 mesh->map_diffuse = map_diffuse;
919                 mesh->map_specular = map_specular;
920                 mesh->map_normal = map_normal;
921         }
922         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)
923         {
924                 if (mesh->next == NULL)
925                         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);
926                 mesh = mesh->next;
927         }
928         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
929         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
930         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
931         mesh->numtriangles++;
932 }
933
934 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)
935 {
936         int i, j, e;
937         float vbuf[3*14], *v;
938         memset(vbuf, 0, sizeof(vbuf));
939         for (i = 0;i < numtris;i++)
940         {
941                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
942                 {
943                         e = *element3i++;
944                         if (vertex3f)
945                         {
946                                 v[0] = vertex3f[e * 3 + 0];
947                                 v[1] = vertex3f[e * 3 + 1];
948                                 v[2] = vertex3f[e * 3 + 2];
949                         }
950                         if (svector3f)
951                         {
952                                 v[3] = svector3f[e * 3 + 0];
953                                 v[4] = svector3f[e * 3 + 1];
954                                 v[5] = svector3f[e * 3 + 2];
955                         }
956                         if (tvector3f)
957                         {
958                                 v[6] = tvector3f[e * 3 + 0];
959                                 v[7] = tvector3f[e * 3 + 1];
960                                 v[8] = tvector3f[e * 3 + 2];
961                         }
962                         if (normal3f)
963                         {
964                                 v[9] = normal3f[e * 3 + 0];
965                                 v[10] = normal3f[e * 3 + 1];
966                                 v[11] = normal3f[e * 3 + 2];
967                         }
968                         if (texcoord2f)
969                         {
970                                 v[12] = texcoord2f[e * 2 + 0];
971                                 v[13] = texcoord2f[e * 2 + 1];
972                         }
973                 }
974                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
975         }
976
977         // the triangle calculation can take a while, so let's do a keepalive here
978         CL_KeepaliveMessage(false);
979 }
980
981 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)
982 {
983         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
984         CL_KeepaliveMessage(false);
985
986         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
987 }
988
989 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
990 {
991         if (!gl_support_arb_vertex_buffer_object)
992                 return;
993
994         // element buffer is easy because it's just one array
995         if (mesh->numtriangles)
996         {
997                 if (mesh->element3s)
998                         mesh->ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3s, mesh->numtriangles * sizeof(unsigned short[3]), "shadowmesh");
999                 else
1000                         mesh->ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(unsigned int[3]), "shadowmesh");
1001         }
1002
1003         // vertex buffer is several arrays and we put them in the same buffer
1004         //
1005         // is this wise?  the texcoordtexture2f array is used with dynamic
1006         // vertex/svector/tvector/normal when rendering animated models, on the
1007         // other hand animated models don't use a lot of vertices anyway...
1008         if (mesh->numverts)
1009         {
1010                 size_t size;
1011                 unsigned char *mem;
1012                 size = 0;
1013                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1014                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1015                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1016                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1017                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1018                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1019                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1020                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1021                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1022                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1023                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1024                 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
1025                 Mem_Free(mem);
1026         }
1027 }
1028
1029 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1030 {
1031         shadowmesh_t *mesh, *newmesh, *nextmesh;
1032         // reallocate meshs to conserve space
1033         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1034         {
1035                 nextmesh = mesh->next;
1036                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1037                 {
1038                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1039                         newmesh->next = firstmesh;
1040                         firstmesh = newmesh;
1041                         if (newmesh->element3s)
1042                         {
1043                                 int i;
1044                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1045                                         newmesh->element3s[i] = newmesh->element3i[i];
1046                         }
1047                         if (createvbo)
1048                                 Mod_ShadowMesh_CreateVBOs(newmesh);
1049                 }
1050                 Mem_Free(mesh);
1051         }
1052
1053         // this can take a while, so let's do a keepalive here
1054         CL_KeepaliveMessage(false);
1055
1056         return firstmesh;
1057 }
1058
1059 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1060 {
1061         int i;
1062         shadowmesh_t *mesh;
1063         vec3_t nmins, nmaxs, ncenter, temp;
1064         float nradius2, dist2, *v;
1065         VectorClear(nmins);
1066         VectorClear(nmaxs);
1067         // calculate bbox
1068         for (mesh = firstmesh;mesh;mesh = mesh->next)
1069         {
1070                 if (mesh == firstmesh)
1071                 {
1072                         VectorCopy(mesh->vertex3f, nmins);
1073                         VectorCopy(mesh->vertex3f, nmaxs);
1074                 }
1075                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1076                 {
1077                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1078                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1079                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1080                 }
1081         }
1082         // calculate center and radius
1083         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1084         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1085         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1086         nradius2 = 0;
1087         for (mesh = firstmesh;mesh;mesh = mesh->next)
1088         {
1089                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1090                 {
1091                         VectorSubtract(v, ncenter, temp);
1092                         dist2 = DotProduct(temp, temp);
1093                         if (nradius2 < dist2)
1094                                 nradius2 = dist2;
1095                 }
1096         }
1097         // return data
1098         if (mins)
1099                 VectorCopy(nmins, mins);
1100         if (maxs)
1101                 VectorCopy(nmaxs, maxs);
1102         if (center)
1103                 VectorCopy(ncenter, center);
1104         if (radius)
1105                 *radius = sqrt(nradius2);
1106 }
1107
1108 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1109 {
1110         shadowmesh_t *nextmesh;
1111         for (;mesh;mesh = nextmesh)
1112         {
1113                 if (mesh->ebo3i)
1114                         R_Mesh_DestroyBufferObject(mesh->ebo3i);
1115                 if (mesh->ebo3s)
1116                         R_Mesh_DestroyBufferObject(mesh->ebo3s);
1117                 if (mesh->vbo)
1118                         R_Mesh_DestroyBufferObject(mesh->vbo);
1119                 nextmesh = mesh->next;
1120                 Mem_Free(mesh);
1121         }
1122 }
1123
1124 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)
1125 {
1126         float v[3], tc[3];
1127         v[0] = ix;
1128         v[1] = iy;
1129         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1130                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1131         else
1132                 v[2] = 0;
1133         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1134         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1135         texcoord2f[0] = tc[0];
1136         texcoord2f[1] = tc[1];
1137 }
1138
1139 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)
1140 {
1141         float vup[3], vdown[3], vleft[3], vright[3];
1142         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1143         float sv[3], tv[3], nl[3];
1144         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1145         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1146         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1147         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1148         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1149         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1150         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1151         VectorAdd(svector3f, sv, svector3f);
1152         VectorAdd(tvector3f, tv, tvector3f);
1153         VectorAdd(normal3f, nl, normal3f);
1154         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1155         VectorAdd(svector3f, sv, svector3f);
1156         VectorAdd(tvector3f, tv, tvector3f);
1157         VectorAdd(normal3f, nl, normal3f);
1158         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1159         VectorAdd(svector3f, sv, svector3f);
1160         VectorAdd(tvector3f, tv, tvector3f);
1161         VectorAdd(normal3f, nl, normal3f);
1162 }
1163
1164 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)
1165 {
1166         int x, y, ix, iy, *e;
1167         e = element3i;
1168         for (y = 0;y < height;y++)
1169         {
1170                 for (x = 0;x < width;x++)
1171                 {
1172                         e[0] = (y + 1) * (width + 1) + (x + 0);
1173                         e[1] = (y + 0) * (width + 1) + (x + 0);
1174                         e[2] = (y + 1) * (width + 1) + (x + 1);
1175                         e[3] = (y + 0) * (width + 1) + (x + 0);
1176                         e[4] = (y + 0) * (width + 1) + (x + 1);
1177                         e[5] = (y + 1) * (width + 1) + (x + 1);
1178                         e += 6;
1179                 }
1180         }
1181         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1182         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1183                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1184                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1185 }
1186
1187 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1188 {
1189         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1190         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1191         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1192         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1193         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1194         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1195         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1196         return Q3WAVEFUNC_NONE;
1197 }
1198
1199 void Mod_FreeQ3Shaders(void)
1200 {
1201         Mem_FreePool(&q3shaders_mem);
1202 }
1203
1204 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1205 {
1206         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1207         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1208         q3shader_hash_entry_t* lastEntry = NULL;
1209         while (entry != NULL)
1210         {
1211                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1212                 {
1213                         Con_Printf("Shader '%s' already defined\n", shader->name);
1214                         return;
1215                 }
1216                 lastEntry = entry;
1217                 entry = entry->chain;
1218         }
1219         if (entry == NULL)
1220         {
1221                 if (lastEntry->shader.name[0] != 0)
1222                 {
1223                         /* Add to chain */
1224                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1225                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1226
1227                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1228                         lastEntry->chain = newEntry;
1229                         newEntry->chain = NULL;
1230                         lastEntry = newEntry;
1231                 }
1232                 /* else: head of chain, in hash entry array */
1233                 entry = lastEntry;
1234         }
1235         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1236 }
1237
1238 extern cvar_t r_picmipworld;
1239 void Mod_LoadQ3Shaders(void)
1240 {
1241         int j;
1242         int fileindex;
1243         fssearch_t *search;
1244         char *f;
1245         const char *text;
1246         q3shaderinfo_t shader;
1247         q3shaderinfo_layer_t *layer;
1248         int numparameters;
1249         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1250
1251         Mod_FreeQ3Shaders();
1252
1253         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1254         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1255                 sizeof (q3shader_data_t));
1256         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1257                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1258         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1259                 q3shaders_mem, sizeof (char**), 256);
1260
1261         search = FS_Search("scripts/*.shader", true, false);
1262         if (!search)
1263                 return;
1264         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1265         {
1266                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1267                 if (!f)
1268                         continue;
1269                 while (COM_ParseToken_QuakeC(&text, false))
1270                 {
1271                         memset (&shader, 0, sizeof(shader));
1272                         shader.reflectmin = 0;
1273                         shader.reflectmax = 1;
1274                         shader.refractfactor = 1;
1275                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1276                         shader.reflectfactor = 1;
1277                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1278                         shader.r_water_wateralpha = 1;
1279
1280                         strlcpy(shader.name, com_token, sizeof(shader.name));
1281                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1282                         {
1283                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1284                                 break;
1285                         }
1286                         while (COM_ParseToken_QuakeC(&text, false))
1287                         {
1288                                 if (!strcasecmp(com_token, "}"))
1289                                         break;
1290                                 if (!strcasecmp(com_token, "{"))
1291                                 {
1292                                         static q3shaderinfo_layer_t dummy;
1293                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1294                                         {
1295                                                 layer = shader.layers + shader.numlayers++;
1296                                         }
1297                                         else
1298                                         {
1299                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1300                                                 memset(&dummy, 0, sizeof(dummy));
1301                                                 layer = &dummy;
1302                                         }
1303                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1304                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1305                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1306                                         layer->blendfunc[0] = GL_ONE;
1307                                         layer->blendfunc[1] = GL_ZERO;
1308                                         while (COM_ParseToken_QuakeC(&text, false))
1309                                         {
1310                                                 if (!strcasecmp(com_token, "}"))
1311                                                         break;
1312                                                 if (!strcasecmp(com_token, "\n"))
1313                                                         continue;
1314                                                 numparameters = 0;
1315                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1316                                                 {
1317                                                         if (j < TEXTURE_MAXFRAMES + 4)
1318                                                         {
1319                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1320                                                                 numparameters = j + 1;
1321                                                         }
1322                                                         if (!COM_ParseToken_QuakeC(&text, true))
1323                                                                 break;
1324                                                 }
1325                                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1326                                                         parameter[j][0] = 0;
1327                                                 if (developer.integer >= 100)
1328                                                 {
1329                                                         Con_Printf("%s %i: ", shader.name, shader.numlayers - 1);
1330                                                         for (j = 0;j < numparameters;j++)
1331                                                                 Con_Printf(" %s", parameter[j]);
1332                                                         Con_Print("\n");
1333                                                 }
1334                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1335                                                 {
1336                                                         if (numparameters == 2)
1337                                                         {
1338                                                                 if (!strcasecmp(parameter[1], "add"))
1339                                                                 {
1340                                                                         layer->blendfunc[0] = GL_ONE;
1341                                                                         layer->blendfunc[1] = GL_ONE;
1342                                                                 }
1343                                                                 else if (!strcasecmp(parameter[1], "filter"))
1344                                                                 {
1345                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1346                                                                         layer->blendfunc[1] = GL_ZERO;
1347                                                                 }
1348                                                                 else if (!strcasecmp(parameter[1], "blend"))
1349                                                                 {
1350                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1351                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1352                                                                 }
1353                                                         }
1354                                                         else if (numparameters == 3)
1355                                                         {
1356                                                                 int k;
1357                                                                 for (k = 0;k < 2;k++)
1358                                                                 {
1359                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1360                                                                                 layer->blendfunc[k] = GL_ONE;
1361                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1362                                                                                 layer->blendfunc[k] = GL_ZERO;
1363                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1364                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1365                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1366                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1367                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1368                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1369                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1370                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1371                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1372                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1373                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1374                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1375                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1376                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1377                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1378                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1379                                                                         else
1380                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1381                                                                 }
1382                                                         }
1383                                                 }
1384                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1385                                                         layer->alphatest = true;
1386                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1387                                                 {
1388                                                         if (!strcasecmp(parameter[0], "clampmap"))
1389                                                                 layer->clampmap = true;
1390                                                         layer->numframes = 1;
1391                                                         layer->framerate = 1;
1392                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1393                                                                 &q3shader_data->char_ptrs);
1394                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1395                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1396                                                                 shader.lighting = true;
1397                                                 }
1398                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1399                                                 {
1400                                                         int i;
1401                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1402                                                         layer->framerate = atof(parameter[1]);
1403                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1404                                                         for (i = 0;i < layer->numframes;i++)
1405                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1406                                                 }
1407                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1408                                                 {
1409                                                         int i;
1410                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1411                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1412                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1413                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1414                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1415                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1416                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1417                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1418                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1419                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1420                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1421                                                         else if (!strcasecmp(parameter[1], "wave"))
1422                                                         {
1423                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1424                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1425                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1426                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1427                                                         }
1428                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1429                                                 }
1430                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1431                                                 {
1432                                                         int i;
1433                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1434                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1435                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1436                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1437                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1438                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1439                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1440                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1441                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1442                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1443                                                         else if (!strcasecmp(parameter[1], "wave"))
1444                                                         {
1445                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1446                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1447                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1448                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1449                                                         }
1450                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1451                                                 }
1452                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1453                                                 {
1454                                                         int i;
1455                                                         // observed values: tcgen environment
1456                                                         // no other values have been observed in real shaders
1457                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1458                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1459                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1460                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1461                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1462                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1463                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1464                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1465                                                 }
1466                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1467                                                 {
1468                                                         int i, tcmodindex;
1469                                                         // observed values:
1470                                                         // tcmod rotate #
1471                                                         // tcmod scale # #
1472                                                         // tcmod scroll # #
1473                                                         // tcmod stretch sin # # # #
1474                                                         // tcmod stretch triangle # # # #
1475                                                         // tcmod transform # # # # # #
1476                                                         // tcmod turb # # # #
1477                                                         // tcmod turb sin # # # #  (this is bogus)
1478                                                         // no other values have been observed in real shaders
1479                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1480                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1481                                                                         break;
1482                                                         if (tcmodindex < Q3MAXTCMODS)
1483                                                         {
1484                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1485                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1486                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1487                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1488                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1489                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1490                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1491                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1492                                                                 {
1493                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1494                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1495                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1496                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1497                                                                 }
1498                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1499                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1500                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1501                                                         }
1502                                                         else
1503                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1504                                                 }
1505                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1506                                                 if (!strcasecmp(com_token, "}"))
1507                                                         break;
1508                                         }
1509                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1510                                                 shader.lighting = true;
1511                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1512                                         {
1513                                                 if (layer == shader.layers + 0)
1514                                                 {
1515                                                         // vertex controlled transparency
1516                                                         shader.vertexalpha = true;
1517                                                 }
1518                                                 else
1519                                                 {
1520                                                         // multilayer terrain shader or similar
1521                                                         shader.textureblendalpha = true;
1522                                                 }
1523                                         }
1524                                         layer->texflags = TEXF_ALPHA | TEXF_PRECACHE;
1525                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1526                                                 layer->texflags |= TEXF_MIPMAP;
1527                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1528                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1529                                         if (layer->clampmap)
1530                                                 layer->texflags |= TEXF_CLAMP;
1531                                         continue;
1532                                 }
1533                                 numparameters = 0;
1534                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1535                                 {
1536                                         if (j < TEXTURE_MAXFRAMES + 4)
1537                                         {
1538                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1539                                                 numparameters = j + 1;
1540                                         }
1541                                         if (!COM_ParseToken_QuakeC(&text, true))
1542                                                 break;
1543                                 }
1544                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1545                                         parameter[j][0] = 0;
1546                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1547                                         break;
1548                                 if (developer.integer >= 100)
1549                                 {
1550                                         Con_Printf("%s: ", shader.name);
1551                                         for (j = 0;j < numparameters;j++)
1552                                                 Con_Printf(" %s", parameter[j]);
1553                                         Con_Print("\n");
1554                                 }
1555                                 if (numparameters < 1)
1556                                         continue;
1557                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1558                                 {
1559                                         if (!strcasecmp(parameter[1], "alphashadow"))
1560                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1561                                         else if (!strcasecmp(parameter[1], "areaportal"))
1562                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1563                                         else if (!strcasecmp(parameter[1], "botclip"))
1564                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1565                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1566                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1567                                         else if (!strcasecmp(parameter[1], "detail"))
1568                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1569                                         else if (!strcasecmp(parameter[1], "donotenter"))
1570                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1571                                         else if (!strcasecmp(parameter[1], "dust"))
1572                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1573                                         else if (!strcasecmp(parameter[1], "hint"))
1574                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1575                                         else if (!strcasecmp(parameter[1], "fog"))
1576                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1577                                         else if (!strcasecmp(parameter[1], "lava"))
1578                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1579                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1580                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1581                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1582                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1583                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1584                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1585                                         else if (!strcasecmp(parameter[1], "nodamage"))
1586                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1587                                         else if (!strcasecmp(parameter[1], "nodlight"))
1588                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1589                                         else if (!strcasecmp(parameter[1], "nodraw"))
1590                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1591                                         else if (!strcasecmp(parameter[1], "nodrop"))
1592                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1593                                         else if (!strcasecmp(parameter[1], "noimpact"))
1594                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1595                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1596                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1597                                         else if (!strcasecmp(parameter[1], "nomarks"))
1598                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1599                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1600                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1601                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1602                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1603                                         else if (!strcasecmp(parameter[1], "origin"))
1604                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1605                                         else if (!strcasecmp(parameter[1], "playerclip"))
1606                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1607                                         else if (!strcasecmp(parameter[1], "sky"))
1608                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1609                                         else if (!strcasecmp(parameter[1], "slick"))
1610                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1611                                         else if (!strcasecmp(parameter[1], "slime"))
1612                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1613                                         else if (!strcasecmp(parameter[1], "structural"))
1614                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1615                                         else if (!strcasecmp(parameter[1], "trans"))
1616                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1617                                         else if (!strcasecmp(parameter[1], "water"))
1618                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1619                                         else if (!strcasecmp(parameter[1], "pointlight"))
1620                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1621                                         else if (!strcasecmp(parameter[1], "antiportal"))
1622                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1623                                         else
1624                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1625                                 }
1626                                 else if (!strcasecmp(parameter[0], "dpshadow"))
1627                                         shader.dpshadow = true;
1628                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1629                                         shader.dpnoshadow = true;
1630                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1631                                 {
1632                                         // some q3 skies don't have the sky parm set
1633                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1634                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1635                                 }
1636                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1637                                 {
1638                                         // some q3 skies don't have the sky parm set
1639                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1640                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1641                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1642                                 }
1643                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1644                                 {
1645                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1646                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1647                                 }
1648                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1649                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1650                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1651                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1652                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1653                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1654                                 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1655                                 {
1656                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
1657                                         shader.refractfactor = atof(parameter[1]);
1658                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1659                                 }
1660                                 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1661                                 {
1662                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
1663                                         shader.reflectfactor = atof(parameter[1]);
1664                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1665                                 }
1666                                 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 12)
1667                                 {
1668                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1669                                         shader.reflectmin = atof(parameter[1]);
1670                                         shader.reflectmax = atof(parameter[2]);
1671                                         shader.refractfactor = atof(parameter[3]);
1672                                         shader.reflectfactor = atof(parameter[4]);
1673                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1674                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1675                                         shader.r_water_wateralpha = atof(parameter[11]);
1676                                 }
1677                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1678                                 {
1679                                         int i, deformindex;
1680                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1681                                                 if (!shader.deforms[deformindex].deform)
1682                                                         break;
1683                                         if (deformindex < Q3MAXDEFORMS)
1684                                         {
1685                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1686                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
1687                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1688                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1689                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1690                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
1691                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
1692                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
1693                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
1694                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
1695                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
1696                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
1697                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
1698                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
1699                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
1700                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1701                                                 {
1702                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
1703                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1704                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1705                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1706                                                 }
1707                                                 else if (!strcasecmp(parameter[1], "move"            ))
1708                                                 {
1709                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
1710                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1711                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1712                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1713                                                 }
1714                                         }
1715                                 }
1716                         }
1717                         // pick the primary layer to render with
1718                         if (shader.numlayers)
1719                         {
1720                                 shader.backgroundlayer = -1;
1721                                 shader.primarylayer = 0;
1722                                 // if lightmap comes first this is definitely an ordinary texture
1723                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
1724                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
1725                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
1726                                 {
1727                                         shader.backgroundlayer = -1;
1728                                         shader.primarylayer = 1;
1729                                 }
1730                                 else if (shader.numlayers >= 2
1731                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
1732                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
1733                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
1734                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
1735                                 {
1736                                         // terrain blending or other effects
1737                                         shader.backgroundlayer = 0;
1738                                         shader.primarylayer = 1;
1739                                 }
1740                         }
1741                         // fix up multiple reflection types
1742                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
1743                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
1744
1745                         Q3Shader_AddToHash (&shader);
1746                 }
1747                 Mem_Free(f);
1748         }
1749 }
1750
1751 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
1752 {
1753         unsigned short hash;
1754         q3shader_hash_entry_t* entry;
1755         if (!q3shaders_mem)
1756                 Mod_LoadQ3Shaders();
1757         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
1758         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1759         while (entry != NULL)
1760         {
1761                 if (strcasecmp (entry->shader.name, name) == 0)
1762                         return &entry->shader;
1763                 entry = entry->chain;
1764         }
1765         return NULL;
1766 }
1767
1768 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
1769 {
1770         int j;
1771         qboolean success = true;
1772         q3shaderinfo_t *shader;
1773         if (!name)
1774                 name = "";
1775         strlcpy(texture->name, name, sizeof(texture->name));
1776         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
1777         if (shader)
1778         {
1779                 if (developer_loading.integer)
1780                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
1781                 texture->surfaceparms = shader->surfaceparms;
1782                 texture->textureflags = shader->textureflags;
1783
1784                 // allow disabling of picmip or compression by defaulttexflags
1785                 if(!(defaulttexflags & TEXF_PICMIP))
1786                         texture->textureflags &= ~TEXF_PICMIP;
1787                 if(!(defaulttexflags & TEXF_COMPRESS))
1788                         texture->textureflags &= ~TEXF_COMPRESS;
1789
1790                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
1791                 {
1792                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1793                         if (shader->skyboxname[0])
1794                         {
1795                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
1796                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
1797                         }
1798                 }
1799                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
1800                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1801                 else
1802                         texture->basematerialflags = MATERIALFLAG_WALL;
1803
1804                 if (shader->layers[0].alphatest)
1805                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1806                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
1807                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
1808                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
1809                         texture->biaspolygonoffset -= 2;
1810                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
1811                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
1812                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
1813                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
1814                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
1815                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
1816                 texture->customblendfunc[0] = GL_ONE;
1817                 texture->customblendfunc[1] = GL_ZERO;
1818                 if (shader->numlayers > 0)
1819                 {
1820                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
1821                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
1822 /*
1823 Q3 shader blendfuncs actually used in the game (* = supported by DP)
1824 * additive               GL_ONE GL_ONE
1825 additive weird         GL_ONE GL_SRC_ALPHA
1826 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
1827 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
1828 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
1829 brighten               GL_DST_COLOR GL_ONE
1830 brighten               GL_ONE GL_SRC_COLOR
1831 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
1832 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
1833 * modulate               GL_DST_COLOR GL_ZERO
1834 * modulate               GL_ZERO GL_SRC_COLOR
1835 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
1836 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
1837 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
1838 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
1839 * no blend               GL_ONE GL_ZERO
1840 nothing                GL_ZERO GL_ONE
1841 */
1842                         // if not opaque, figure out what blendfunc to use
1843                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
1844                         {
1845                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
1846                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1847                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
1848                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1849                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
1850                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1851                                 else
1852                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1853                         }
1854                 }
1855                 if (!shader->lighting)
1856                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1857                 if (shader->primarylayer >= 0)
1858                 {
1859                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
1860                         // copy over many primarylayer parameters
1861                         texture->rgbgen = primarylayer->rgbgen;
1862                         texture->alphagen = primarylayer->alphagen;
1863                         texture->tcgen = primarylayer->tcgen;
1864                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
1865                         // load the textures
1866                         texture->numskinframes = primarylayer->numframes;
1867                         texture->skinframerate = primarylayer->framerate;
1868                         for (j = 0;j < primarylayer->numframes;j++)
1869                         {
1870                                 if(cls.state == ca_dedicated)
1871                                 {
1872                                         texture->skinframes[j] = NULL;
1873                                 }
1874                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags, false)))
1875                                 {
1876                                         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);
1877                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
1878                                 }
1879                         }
1880                 }
1881                 if (shader->backgroundlayer >= 0)
1882                 {
1883                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
1884                         texture->backgroundnumskinframes = backgroundlayer->numframes;
1885                         texture->backgroundskinframerate = backgroundlayer->framerate;
1886                         for (j = 0;j < backgroundlayer->numframes;j++)
1887                         {
1888                                 if(cls.state == ca_dedicated)
1889                                 {
1890                                         texture->skinframes[j] = NULL;
1891                                 }
1892                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags, false)))
1893                                 {
1894                                         Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (background frame %i) for shader ^2\"%s\"\n", loadmodel->name, backgroundlayer->texturename[j], j, texture->name);
1895                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
1896                                 }
1897                         }
1898                 }
1899                 if (shader->dpshadow)
1900                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
1901                 if (shader->dpnoshadow)
1902                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1903                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
1904                 texture->reflectmin = shader->reflectmin;
1905                 texture->reflectmax = shader->reflectmax;
1906                 texture->refractfactor = shader->refractfactor;
1907                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
1908                 texture->reflectfactor = shader->reflectfactor;
1909                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
1910                 texture->r_water_wateralpha = shader->r_water_wateralpha;
1911         }
1912         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
1913         {
1914                 if (developer.integer >= 100)
1915                         Con_Printf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
1916                 texture->surfaceparms = 0;
1917         }
1918         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
1919         {
1920                 if (developer.integer >= 100)
1921                         Con_Printf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
1922                 texture->surfaceparms = 0;
1923                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1924         }
1925         else
1926         {
1927                 if (developer.integer >= 100)
1928                         Con_Printf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
1929                 texture->surfaceparms = 0;
1930                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
1931                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1932                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
1933                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1934                 else
1935                         texture->basematerialflags |= MATERIALFLAG_WALL;
1936                 texture->numskinframes = 1;
1937                 if(cls.state == ca_dedicated)
1938                 {
1939                         texture->skinframes[0] = NULL;
1940                 }
1941                 else
1942                 {
1943                         if (fallback)
1944                         {
1945                                 qboolean has_alpha;
1946                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal_CheckAlpha(texture->name, defaulttexflags, false, &has_alpha)))
1947                                 {
1948                                         if(has_alpha && (defaulttexflags & TEXF_ALPHA))
1949                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1950                                 }
1951                                 else
1952                                         success = false;
1953                         }
1954                         else
1955                                 success = false;
1956                         if (!success && warnmissing)
1957                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
1958                 }
1959         }
1960         // init the animation variables
1961         texture->currentframe = texture;
1962         if (texture->numskinframes < 1)
1963                 texture->numskinframes = 1;
1964         if (!texture->skinframes[0])
1965                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
1966         texture->currentskinframe = texture->skinframes[0];
1967         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
1968         return success;
1969 }
1970
1971 skinfile_t *Mod_LoadSkinFiles(void)
1972 {
1973         int i, words, line, wordsoverflow;
1974         char *text;
1975         const char *data;
1976         skinfile_t *skinfile = NULL, *first = NULL;
1977         skinfileitem_t *skinfileitem;
1978         char word[10][MAX_QPATH];
1979
1980 /*
1981 sample file:
1982 U_bodyBox,models/players/Legoman/BikerA2.tga
1983 U_RArm,models/players/Legoman/BikerA1.tga
1984 U_LArm,models/players/Legoman/BikerA1.tga
1985 U_armor,common/nodraw
1986 U_sword,common/nodraw
1987 U_shield,common/nodraw
1988 U_homb,common/nodraw
1989 U_backpack,common/nodraw
1990 U_colcha,common/nodraw
1991 tag_head,
1992 tag_weapon,
1993 tag_torso,
1994 */
1995         memset(word, 0, sizeof(word));
1996         for (i = 0;i < MAX_SKINS && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
1997         {
1998                 // If it's the first file we parse
1999                 if (skinfile == NULL)
2000                 {
2001                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2002                         first = skinfile;
2003                 }
2004                 else
2005                 {
2006                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2007                         skinfile = skinfile->next;
2008                 }
2009                 skinfile->next = NULL;
2010
2011                 for(line = 0;;line++)
2012                 {
2013                         // parse line
2014                         if (!COM_ParseToken_QuakeC(&data, true))
2015                                 break;
2016                         if (!strcmp(com_token, "\n"))
2017                                 continue;
2018                         words = 0;
2019                         wordsoverflow = false;
2020                         do
2021                         {
2022                                 if (words < 10)
2023                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2024                                 else
2025                                         wordsoverflow = true;
2026                         }
2027                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2028                         if (wordsoverflow)
2029                         {
2030                                 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);
2031                                 continue;
2032                         }
2033                         // words is always >= 1
2034                         if (!strcmp(word[0], "replace"))
2035                         {
2036                                 if (words == 3)
2037                                 {
2038                                         if (developer_loading.integer)
2039                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2040                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2041                                         skinfileitem->next = skinfile->items;
2042                                         skinfile->items = skinfileitem;
2043                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2044                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2045                                 }
2046                                 else
2047                                         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]);
2048                         }
2049                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2050                         {
2051                                 // tag name, like "tag_weapon,"
2052                                 // not used for anything (not even in Quake3)
2053                         }
2054                         else if (words >= 2 && !strcmp(word[1], ","))
2055                         {
2056                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2057                                 if (developer_loading.integer)
2058                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2059                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2060                                 skinfileitem->next = skinfile->items;
2061                                 skinfile->items = skinfileitem;
2062                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2063                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2064                         }
2065                         else
2066                                 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);
2067                 }
2068                 Mem_Free(text);
2069         }
2070         if (i)
2071                 loadmodel->numskins = i;
2072         return first;
2073 }
2074
2075 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2076 {
2077         skinfile_t *next;
2078         skinfileitem_t *skinfileitem, *nextitem;
2079         for (;skinfile;skinfile = next)
2080         {
2081                 next = skinfile->next;
2082                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2083                 {
2084                         nextitem = skinfileitem->next;
2085                         Mem_Free(skinfileitem);
2086                 }
2087                 Mem_Free(skinfile);
2088         }
2089 }
2090
2091 int Mod_CountSkinFiles(skinfile_t *skinfile)
2092 {
2093         int i;
2094         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2095         return i;
2096 }
2097
2098 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2099 {
2100         int i;
2101         double isnap = 1.0 / snap;
2102         for (i = 0;i < numvertices*numcomponents;i++)
2103                 vertices[i] = floor(vertices[i]*isnap)*snap;
2104 }
2105
2106 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2107 {
2108         int i, outtriangles;
2109         float edgedir1[3], edgedir2[3], temp[3];
2110         // a degenerate triangle is one with no width (thickness, surface area)
2111         // these are characterized by having all 3 points colinear (along a line)
2112         // or having two points identical
2113         // the simplest check is to calculate the triangle's area
2114         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2115         {
2116                 // calculate first edge
2117                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2118                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2119                 CrossProduct(edgedir1, edgedir2, temp);
2120                 if (VectorLength2(temp) < 0.001f)
2121                         continue; // degenerate triangle (no area)
2122                 // valid triangle (has area)
2123                 VectorCopy(inelement3i, outelement3i);
2124                 outelement3i += 3;
2125                 outtriangles++;
2126         }
2127         return outtriangles;
2128 }
2129
2130 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2131 {
2132         int i, e;
2133         int firstvertex, lastvertex;
2134         if (numelements > 0 && elements)
2135         {
2136                 firstvertex = lastvertex = elements[0];
2137                 for (i = 1;i < numelements;i++)
2138                 {
2139                         e = elements[i];
2140                         firstvertex = min(firstvertex, e);
2141                         lastvertex = max(lastvertex, e);
2142                 }
2143         }
2144         else
2145                 firstvertex = lastvertex = 0;
2146         if (firstvertexpointer)
2147                 *firstvertexpointer = firstvertex;
2148         if (lastvertexpointer)
2149                 *lastvertexpointer = lastvertex;
2150 }
2151
2152 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2153 {
2154         // make an optimal set of texture-sorted batches to draw...
2155         int j, t;
2156         int *firstsurfacefortexture;
2157         int *numsurfacesfortexture;
2158         if (!mod->sortedmodelsurfaces)
2159                 mod->sortedmodelsurfaces = Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2160         firstsurfacefortexture = Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2161         numsurfacesfortexture = Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2162         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2163         for (j = 0;j < mod->nummodelsurfaces;j++)
2164         {
2165                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2166                 int t = (int)(surface->texture - mod->data_textures);
2167                 numsurfacesfortexture[t]++;
2168         }
2169         j = 0;
2170         for (t = 0;t < mod->num_textures;t++)
2171         {
2172                 firstsurfacefortexture[t] = j;
2173                 j += numsurfacesfortexture[t];
2174         }
2175         for (j = 0;j < mod->nummodelsurfaces;j++)
2176         {
2177                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2178                 int t = (int)(surface->texture - mod->data_textures);
2179                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2180         }
2181         Mem_Free(firstsurfacefortexture);
2182         Mem_Free(numsurfacesfortexture);
2183 }
2184
2185 static void Mod_BuildVBOs(void)
2186 {
2187         if (!gl_support_arb_vertex_buffer_object)
2188                 return;
2189
2190         // element buffer is easy because it's just one array
2191         if (loadmodel->surfmesh.num_triangles)
2192         {
2193                 if (loadmodel->surfmesh.data_element3s)
2194                 {
2195                         int i;
2196                         for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2197                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2198                         loadmodel->surfmesh.ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]), loadmodel->name);
2199                 }
2200                 else
2201                         loadmodel->surfmesh.ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(unsigned int[3]), loadmodel->name);
2202         }
2203
2204         // vertex buffer is several arrays and we put them in the same buffer
2205         //
2206         // is this wise?  the texcoordtexture2f array is used with dynamic
2207         // vertex/svector/tvector/normal when rendering animated models, on the
2208         // other hand animated models don't use a lot of vertices anyway...
2209         if (loadmodel->surfmesh.num_vertices)
2210         {
2211                 size_t size;
2212                 unsigned char *mem;
2213                 size = 0;
2214                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2215                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2216                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2217                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2218                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2219                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2220                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2221                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2222                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2223                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2224                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2225                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2226                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2227                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2228                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2229                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2230                 Mem_Free(mem);
2231         }
2232 }
2233
2234 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2235 {
2236         int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2237         int a, b, c;
2238         const char *texname;
2239         const int *e;
2240         const float *v, *vn, *vt;
2241         size_t l;
2242         size_t outbufferpos = 0;
2243         size_t outbuffermax = 0x100000;
2244         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2245         const msurface_t *surface;
2246         const int maxtextures = 256;
2247         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2248
2249         // construct the mtllib file
2250         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2251         if (l > 0)
2252                 outbufferpos += l;
2253         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2254         {
2255                 countsurfaces++;
2256                 countvertices += surface->num_vertices;
2257                 countfaces += surface->num_triangles;
2258                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2259                 for (textureindex = 0;textureindex < maxtextures && texturenames[textureindex*MAX_QPATH];textureindex++)
2260                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2261                                 break;
2262                 if (textureindex >= maxtextures)
2263                         continue; // just a precaution
2264                 if (counttextures < textureindex + 1)
2265                         counttextures = textureindex + 1;
2266                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2267                 if (outbufferpos >= outbuffermax >> 1)
2268                 {
2269                         outbuffermax *= 2;
2270                         oldbuffer = outbuffer;
2271                         outbuffer = (char *) Z_Malloc(outbuffermax);
2272                         memcpy(outbuffer, oldbuffer, outbufferpos);
2273                         Z_Free(oldbuffer);
2274                 }
2275                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "newmtl %s\nNs 96.078431\nKa 0 0 0\nKd 0.64 0.64 0.64\nKs 0.5 0.5 0.5\nNi 1\nd 1\nillum 2\nmap_Kd %s%s\n\n", texname, texname, strstr(texname, ".tga") ? "" : ".tga");
2276                 if (l > 0)
2277                         outbufferpos += l;
2278         }
2279
2280         // write the mtllib file
2281         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2282         outbufferpos = 0;
2283
2284         // construct the obj file
2285         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# model exported from %s by darkplaces engine\n# %i vertices, %i faces, %i surfaces\nmtllib %s\n", originalfilename, countvertices, countfaces, countsurfaces, mtlfilename);
2286         if (l > 0)
2287                 outbufferpos += l;
2288         for (vertexindex = 0, v = model->surfmesh.data_vertex3f, vn = model->surfmesh.data_normal3f, vt = model->surfmesh.data_texcoordtexture2f;vertexindex < model->surfmesh.num_vertices;vertexindex++, v += 3, vn += 3, vt += 2)
2289         {
2290                 if (outbufferpos >= outbuffermax >> 1)
2291                 {
2292                         outbuffermax *= 2;
2293                         oldbuffer = outbuffer;
2294                         outbuffer = (char *) Z_Malloc(outbuffermax);
2295                         memcpy(outbuffer, oldbuffer, outbufferpos);
2296                         Z_Free(oldbuffer);
2297                 }
2298                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[2], -v[1], vn[0], vn[2], -vn[1], vt[0], 1-vt[1]);
2299                 if (l > 0)
2300                         outbufferpos += l;
2301         }
2302         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2303         {
2304                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2305                 if (l > 0)
2306                         outbufferpos += l;
2307                 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2308                 {
2309                         if (outbufferpos >= outbuffermax >> 1)
2310                         {
2311                                 outbuffermax *= 2;
2312                                 oldbuffer = outbuffer;
2313                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2314                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2315                                 Z_Free(oldbuffer);
2316                         }
2317                         a = e[0]+1;
2318                         b = e[2]+1;
2319                         c = e[1]+1;
2320                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,b,b,b,c,c,c);
2321                         if (l > 0)
2322                                 outbufferpos += l;
2323                 }
2324         }
2325
2326         // write the obj file
2327         FS_WriteFile(filename, outbuffer, outbufferpos);
2328
2329         // clean up
2330         Z_Free(outbuffer);
2331         Z_Free(texturenames);
2332
2333         // print some stats
2334         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2335 }
2336
2337 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2338 {
2339         int countnodes = 0, counttriangles = 0, countframes = 0;
2340         int surfaceindex;
2341         int triangleindex;
2342         int transformindex;
2343         int poseindex;
2344         int cornerindex;
2345         float modelscale;
2346         const int *e;
2347         const float *pose;
2348         size_t l;
2349         size_t outbufferpos = 0;
2350         size_t outbuffermax = 0x100000;
2351         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2352         const msurface_t *surface;
2353         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
2354         if (l > 0)
2355                 outbufferpos += l;
2356         modelscale = 1;
2357         if(model->num_poses >= 0)
2358                 modelscale = sqrt(model->data_poses[0] * model->data_poses[0] + model->data_poses[1] * model->data_poses[1] + model->data_poses[2] * model->data_poses[2]);
2359         if(fabs(modelscale - 1) > 1e-4)
2360         {
2361                 if(firstpose == 0) // only print the when writing the reference pose
2362                         Con_Printf("The model has an old-style model scale of %f\n", modelscale);
2363         }
2364         else
2365                 modelscale = 1;
2366         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2367         {
2368                 if (outbufferpos >= outbuffermax >> 1)
2369                 {
2370                         outbuffermax *= 2;
2371                         oldbuffer = outbuffer;
2372                         outbuffer = (char *) Z_Malloc(outbuffermax);
2373                         memcpy(outbuffer, oldbuffer, outbufferpos);
2374                         Z_Free(oldbuffer);
2375                 }
2376                 countnodes++;
2377                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2378                 if (l > 0)
2379                         outbufferpos += l;
2380         }
2381         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2382         if (l > 0)
2383                 outbufferpos += l;
2384         for (poseindex = 0, pose = model->data_poses + model->num_bones * 12 * firstpose;poseindex < numposes;poseindex++)
2385         {
2386                 countframes++;
2387                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2388                 if (l > 0)
2389                         outbufferpos += l;
2390                 for (transformindex = 0;transformindex < model->num_bones;transformindex++, pose += 12)
2391                 {
2392                         float a, b, c;
2393                         float angles[3];
2394                         float mtest[3][4];
2395                         if (outbufferpos >= outbuffermax >> 1)
2396                         {
2397                                 outbuffermax *= 2;
2398                                 oldbuffer = outbuffer;
2399                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2400                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2401                                 Z_Free(oldbuffer);
2402                         }
2403
2404                         // strangely the smd angles are for a transposed matrix, so we
2405                         // have to generate a transposed matrix, then convert that...
2406                         mtest[0][0] = pose[ 0];
2407                         mtest[0][1] = pose[ 4];
2408                         mtest[0][2] = pose[ 8];
2409                         mtest[0][3] = pose[ 3];
2410                         mtest[1][0] = pose[ 1];
2411                         mtest[1][1] = pose[ 5];
2412                         mtest[1][2] = pose[ 9];
2413                         mtest[1][3] = pose[ 7];
2414                         mtest[2][0] = pose[ 2];
2415                         mtest[2][1] = pose[ 6];
2416                         mtest[2][2] = pose[10];
2417                         mtest[2][3] = pose[11];
2418                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
2419                         if (angles[0] >= 180) angles[0] -= 360;
2420                         if (angles[1] >= 180) angles[1] -= 360;
2421                         if (angles[2] >= 180) angles[2] -= 360;
2422
2423                         a = DEG2RAD(angles[ROLL]);
2424                         b = DEG2RAD(angles[PITCH]);
2425                         c = DEG2RAD(angles[YAW]);
2426
2427 #if 0
2428 {
2429                         float cy, sy, cp, sp, cr, sr;
2430                         float test[3][4];
2431                         // smd matrix construction, for comparing to non-transposed m
2432                         sy = sin(c);
2433                         cy = cos(c);
2434                         sp = sin(b);
2435                         cp = cos(b);
2436                         sr = sin(a);
2437                         cr = cos(a);
2438
2439                         test[0][0] = cp*cy;
2440                         test[1][0] = cp*sy;
2441                         test[2][0] = -sp;
2442                         test[0][1] = sr*sp*cy+cr*-sy;
2443                         test[1][1] = sr*sp*sy+cr*cy;
2444                         test[2][1] = sr*cp;
2445                         test[0][2] = (cr*sp*cy+-sr*-sy);
2446                         test[1][2] = (cr*sp*sy+-sr*cy);
2447                         test[2][2] = cr*cp;
2448                         test[0][3] = pose[3];
2449                         test[1][3] = pose[7];
2450                         test[2][3] = pose[11];
2451 }
2452 #endif
2453                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, pose[3] * modelscale, pose[7] * modelscale, pose[11] * modelscale, DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
2454                         if (l > 0)
2455                                 outbufferpos += l;
2456                 }
2457         }
2458         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2459         if (l > 0)
2460                 outbufferpos += l;
2461         if (writetriangles)
2462         {
2463                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
2464                 if (l > 0)
2465                         outbufferpos += l;
2466                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2467                 {
2468                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2469                         {
2470                                 counttriangles++;
2471                                 if (outbufferpos >= outbuffermax >> 1)
2472                                 {
2473                                         outbuffermax *= 2;
2474                                         oldbuffer = outbuffer;
2475                                         outbuffer = (char *) Z_Malloc(outbuffermax);
2476                                         memcpy(outbuffer, oldbuffer, outbufferpos);
2477                                         Z_Free(oldbuffer);
2478                                 }
2479                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
2480                                 if (l > 0)
2481                                         outbufferpos += l;
2482                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
2483                                 {
2484                                         const int index = e[2-cornerindex];
2485                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
2486                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
2487                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
2488                                         const int *wi = model->surfmesh.data_vertexweightindex4i + index * 4;
2489                                         const float *wf = model->surfmesh.data_vertexweightinfluence4f + index * 4;
2490                                              if (wf[3]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 4 %i %f %i %f %i %f %i %f\n", wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2], wi[3], wf[3]);
2491                                         else if (wf[2]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 3 %i %f %i %f %i %f\n"      , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2]);
2492                                         else if (wf[1]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 2 %i %f %i %f\n"            , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1]);
2493                                         else            l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
2494                                         if (l > 0)
2495                                                 outbufferpos += l;
2496                                 }
2497                         }
2498                 }
2499                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2500                 if (l > 0)
2501                         outbufferpos += l;
2502         }
2503
2504         FS_WriteFile(filename, outbuffer, outbufferpos);
2505         Z_Free(outbuffer);
2506
2507         Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
2508 }
2509
2510 /*
2511 ================
2512 Mod_Decompile_f
2513
2514 decompiles a model to editable files
2515 ================
2516 */
2517 static void Mod_Decompile_f(void)
2518 {
2519         int i, j, k, l, first, count;
2520         dp_model_t *mod;
2521         char inname[MAX_QPATH];
2522         char outname[MAX_QPATH];
2523         char mtlname[MAX_QPATH];
2524         char basename[MAX_QPATH];
2525         char animname[MAX_QPATH];
2526         char animname2[MAX_QPATH];
2527         char zymtextbuffer[16384];
2528         char dpmtextbuffer[16384];
2529         int zymtextsize = 0;
2530         int dpmtextsize = 0;
2531
2532         if (Cmd_Argc() != 2)
2533         {
2534                 Con_Print("usage: modeldecompile <filename>\n");
2535                 return;
2536         }
2537
2538         strlcpy(inname, Cmd_Argv(1), sizeof(inname));
2539         FS_StripExtension(inname, basename, sizeof(basename));
2540
2541         mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
2542         if (mod->brush.submodel)
2543         {
2544                 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
2545                 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
2546                 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
2547                 outname[0] = 0;
2548         }
2549         if (!mod)
2550         {
2551                 Con_Print("No such model\n");
2552                 return;
2553         }
2554         if (!mod->surfmesh.num_triangles)
2555         {
2556                 Con_Print("Empty model (or sprite)\n");
2557                 return;
2558         }
2559
2560         // export OBJ if possible (not on sprites)
2561         if (mod->surfmesh.num_triangles)
2562         {
2563                 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
2564                 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
2565                 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
2566         }
2567
2568         // export SMD if possible (only for skeletal models)
2569         if (mod->surfmesh.num_triangles && mod->num_bones)
2570         {
2571                 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
2572                 Mod_Decompile_SMD(mod, outname, 0, 1, true);
2573                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
2574                 if (l > 0) zymtextsize += l;
2575                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
2576                 if (l > 0) dpmtextsize += l;
2577                 for (i = 0;i < mod->numframes;i = j)
2578                 {
2579                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2580                         first = mod->animscenes[i].firstframe;
2581                         if (mod->animscenes[i].framecount > 1)
2582                         {
2583                                 // framegroup anim
2584                                 count = mod->animscenes[i].framecount;
2585                                 j = i + 1;
2586                         }
2587                         else
2588                         {
2589                                 // individual frame
2590                                 // check for additional frames with same name
2591                                 for (l = 0, k = strlen(animname);animname[l];l++)
2592                                         if ((animname[l] < '0' || animname[l] > '9') && animname[l] != '_')
2593                                                 k = l + 1;
2594                                 animname[k] = 0;
2595                                 count = (mod->num_poses / mod->num_bones) - first;
2596                                 for (j = i + 1;j < mod->numframes;j++)
2597                                 {
2598                                         strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
2599                                         for (l = 0, k = strlen(animname2);animname2[l];l++)
2600                                                 if ((animname2[l] < '0' || animname2[l] > '9') && animname2[l] != '_')
2601                                                         k = l + 1;
2602                                         animname2[k] = 0;
2603                                         if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
2604                                         {
2605                                                 count = mod->animscenes[j].firstframe - first;
2606                                                 break;
2607                                         }
2608                                 }
2609                                 // if it's only one frame, use the original frame name
2610                                 if (j == i + 1)
2611                                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2612                                 
2613                         }
2614                         dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
2615                         Mod_Decompile_SMD(mod, outname, first, count, false);
2616                         if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
2617                         {
2618                                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g\n", animname, mod->animscenes[i].framerate);
2619                                 if (l > 0) zymtextsize += l;
2620                         }
2621                         if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
2622                         {
2623                                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd\n", animname);
2624                                 if (l > 0) dpmtextsize += l;
2625                         }
2626                 }
2627                 if (zymtextsize)
2628                         FS_WriteFile(va("%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
2629                 if (dpmtextsize)
2630                         FS_WriteFile(va("%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
2631         }
2632 }
2633