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