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