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