cmd: Reduce duplicate code with command lookup
[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 #include "polygon.h"
29
30 cvar_t r_mipskins = {CVAR_CLIENT | 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"};
31 cvar_t r_mipnormalmaps = {CVAR_CLIENT | CVAR_SAVE, "r_mipnormalmaps", "1", "mipmaps normalmaps (turning it off looks sharper but may have aliasing)"};
32 cvar_t mod_generatelightmaps_unitspersample = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
33 cvar_t mod_generatelightmaps_borderpixels = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
34 cvar_t mod_generatelightmaps_texturesize = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
35 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
36 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
37 cvar_t mod_generatelightmaps_gridsamples = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
38 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
39 cvar_t mod_generatelightmaps_vertexradius = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
40 cvar_t mod_generatelightmaps_gridradius = {CVAR_CLIENT | CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
41
42 dp_model_t *loadmodel;
43
44 // Supported model formats
45 static modloader_t loader[] =
46 {
47         {"obj", NULL, 0, Mod_OBJ_Load},
48         {NULL, "IDPO", 4, Mod_IDP0_Load},
49         {NULL, "IDP2", 4, Mod_IDP2_Load},
50         {NULL, "IDP3", 4, Mod_IDP3_Load},
51         {NULL, "IDSP", 4, Mod_IDSP_Load},
52         {NULL, "IDS2", 4, Mod_IDS2_Load},
53         {NULL, "\035", 1, Mod_Q1BSP_Load},
54         {NULL, "\036", 1, Mod_HLBSP_Load},
55         {NULL, "BSP2", 4, Mod_BSP2_Load},
56         {NULL, "2PSB", 4, Mod_2PSB_Load},
57         {NULL, "IBSP", 4, Mod_IBSP_Load},
58         {NULL, "ZYMOTICMODEL", 13, Mod_ZYMOTICMODEL_Load},
59         {NULL, "DARKPLACESMODEL", 16, Mod_DARKPLACESMODEL_Load},
60         {NULL, "PSKMODEL", 9, Mod_PSKMODEL_Load},
61         {NULL, "INTERQUAKEMODEL", 16, Mod_INTERQUAKEMODEL_Load},
62         {"map", NULL, 0, Mod_MAP_Load},
63         {NULL, NULL, 0, NULL}
64 };
65
66 static mempool_t *mod_mempool;
67 static memexpandablearray_t models;
68
69 static mempool_t* q3shaders_mem;
70 typedef struct q3shader_hash_entry_s
71 {
72   shader_t shader;
73   struct q3shader_hash_entry_s* chain;
74 } q3shader_hash_entry_t;
75 #define Q3SHADER_HASH_SIZE  1021
76 typedef struct q3shader_data_s
77 {
78   memexpandablearray_t hash_entries;
79   q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
80   memexpandablearray_t char_ptrs;
81 } q3shader_data_t;
82 static q3shader_data_t* q3shader_data;
83
84 static void mod_start(void)
85 {
86         int i, count;
87         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
88         dp_model_t *mod;
89
90         SCR_PushLoadingScreen("Loading models", 1.0);
91         count = 0;
92         for (i = 0;i < nummodels;i++)
93                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
94                         if (mod->used)
95                                 ++count;
96         for (i = 0;i < nummodels;i++)
97                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
98                         if (mod->used)
99                         {
100                                 SCR_PushLoadingScreen(mod->name, 1.0 / count);
101                                 Mod_LoadModel(mod, true, false);
102                                 SCR_PopLoadingScreen(false);
103                         }
104         SCR_PopLoadingScreen(false);
105 }
106
107 static void mod_shutdown(void)
108 {
109         int i;
110         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
111         dp_model_t *mod;
112
113         for (i = 0;i < nummodels;i++)
114                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
115                         Mod_UnloadModel(mod);
116
117         Mod_FreeQ3Shaders();
118         Mod_Skeletal_FreeBuffers();
119 }
120
121 static void mod_newmap(void)
122 {
123         msurface_t *surface;
124         int i, j, k, l, surfacenum, ssize, tsize;
125         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
126         dp_model_t *mod;
127
128         for (i = 0;i < nummodels;i++)
129         {
130                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
131                 {
132                         for (j = 0;j < mod->num_textures && mod->data_textures;j++)
133                         {
134                                 // note that materialshaderpass and backgroundshaderpass point to shaderpasses[] and so do the pre/post shader ranges, so this catches all of them...
135                                 for (l = 0; l < Q3SHADER_MAXLAYERS; l++)
136                                         if (mod->data_textures[j].shaderpasses[l])
137                                                 for (k = 0; k < mod->data_textures[j].shaderpasses[l]->numframes; k++)
138                                                         R_SkinFrame_MarkUsed(mod->data_textures[j].shaderpasses[l]->skinframes[k]);
139                         }
140                         if (mod->brush.solidskyskinframe)
141                                 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
142                         if (mod->brush.alphaskyskinframe)
143                                 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
144                 }
145         }
146
147         if (!cl_stainmaps_clearonload.integer)
148                 return;
149
150         for (i = 0;i < nummodels;i++)
151         {
152                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
153                 {
154                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
155                         {
156                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
157                                 {
158                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
159                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
160                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
161                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
162                                 }
163                         }
164                 }
165         }
166 }
167
168 /*
169 ===============
170 Mod_Init
171 ===============
172 */
173 static void Mod_Print_f(cmd_state_t *cmd);
174 static void Mod_Precache_f(cmd_state_t *cmd);
175 static void Mod_Decompile_f(cmd_state_t *cmd);
176 static void Mod_GenerateLightmaps_f(cmd_state_t *cmd);
177 void Mod_Init (void)
178 {
179         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
180         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
181
182         Mod_BrushInit();
183         Mod_AliasInit();
184         Mod_SpriteInit();
185
186         Cvar_RegisterVariable(&r_mipskins);
187         Cvar_RegisterVariable(&r_mipnormalmaps);
188         Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
189         Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
190         Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
191
192         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
193         Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
194         Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
195         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
196         Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
197         Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
198
199         Cmd_AddCommand(CMD_CLIENT, "modellist", Mod_Print_f, "prints a list of loaded models");
200         Cmd_AddCommand(CMD_CLIENT, "modelprecache", Mod_Precache_f, "load a model");
201         Cmd_AddCommand(CMD_CLIENT, "modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
202         Cmd_AddCommand(CMD_CLIENT, "mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
203 }
204
205 void Mod_RenderInit(void)
206 {
207         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap, NULL, NULL);
208 }
209
210 void Mod_UnloadModel (dp_model_t *mod)
211 {
212         char name[MAX_QPATH];
213         qboolean used;
214         dp_model_t *parentmodel;
215
216         if (developer_loading.integer)
217                 Con_Printf("unloading model %s\n", mod->name);
218
219         strlcpy(name, mod->name, sizeof(name));
220         parentmodel = mod->brush.parentmodel;
221         used = mod->used;
222         if (mod->mempool)
223         {
224                 if (mod->surfmesh.data_element3i_indexbuffer && !mod->surfmesh.data_element3i_indexbuffer->isdynamic)
225                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
226                 mod->surfmesh.data_element3i_indexbuffer = NULL;
227                 if (mod->surfmesh.data_element3s_indexbuffer && !mod->surfmesh.data_element3s_indexbuffer->isdynamic)
228                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
229                 mod->surfmesh.data_element3s_indexbuffer = NULL;
230                 if (mod->surfmesh.data_vertex3f_vertexbuffer && !mod->surfmesh.data_vertex3f_vertexbuffer->isdynamic)
231                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_vertex3f_vertexbuffer);
232                 mod->surfmesh.data_vertex3f_vertexbuffer = NULL;
233                 mod->surfmesh.data_svector3f_vertexbuffer = NULL;
234                 mod->surfmesh.data_tvector3f_vertexbuffer = NULL;
235                 mod->surfmesh.data_normal3f_vertexbuffer = NULL;
236                 mod->surfmesh.data_texcoordtexture2f_vertexbuffer = NULL;
237                 mod->surfmesh.data_texcoordlightmap2f_vertexbuffer = NULL;
238                 mod->surfmesh.data_lightmapcolor4f_vertexbuffer = NULL;
239                 mod->surfmesh.data_skeletalindex4ub_vertexbuffer = NULL;
240                 mod->surfmesh.data_skeletalweight4ub_vertexbuffer = NULL;
241         }
242         // free textures/memory attached to the model
243         R_FreeTexturePool(&mod->texturepool);
244         Mem_FreePool(&mod->mempool);
245         // clear the struct to make it available
246         memset(mod, 0, sizeof(dp_model_t));
247         // restore the fields we want to preserve
248         strlcpy(mod->name, name, sizeof(mod->name));
249         mod->brush.parentmodel = parentmodel;
250         mod->used = used;
251         mod->loaded = false;
252 }
253
254 static void R_Model_Null_Draw(entity_render_t *ent)
255 {
256         return;
257 }
258
259
260 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, const char *name, void *pass);
261
262 static int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
263 {
264         const char *bufptr;
265         int start, len;
266         float fps;
267         unsigned int i;
268         qboolean loop;
269         char name[64];
270
271         bufptr = buf;
272         i = 0;
273         while(bufptr)
274         {
275                 // an anim scene!
276
277                 // REQUIRED: fetch start
278                 COM_ParseToken_Simple(&bufptr, true, false, true);
279                 if (!bufptr)
280                         break; // end of file
281                 if (!strcmp(com_token, "\n"))
282                         continue; // empty line
283                 start = atoi(com_token);
284
285                 // REQUIRED: fetch length
286                 COM_ParseToken_Simple(&bufptr, true, false, true);
287                 if (!bufptr || !strcmp(com_token, "\n"))
288                 {
289                         Con_Printf("framegroups file: missing number of frames\n");
290                         continue;
291                 }
292                 len = atoi(com_token);
293
294                 // OPTIONAL args start
295                 COM_ParseToken_Simple(&bufptr, true, false, true);
296
297                 // OPTIONAL: fetch fps
298                 fps = 20;
299                 if (bufptr && strcmp(com_token, "\n"))
300                 {
301                         fps = atof(com_token);
302                         COM_ParseToken_Simple(&bufptr, true, false, true);
303                 }
304
305                 // OPTIONAL: fetch loopflag
306                 loop = true;
307                 if (bufptr && strcmp(com_token, "\n"))
308                 {
309                         loop = (atoi(com_token) != 0);
310                         COM_ParseToken_Simple(&bufptr, true, false, true);
311                 }
312
313                 // OPTIONAL: fetch name
314                 name[0] = 0;
315                 if (bufptr && strcmp(com_token, "\n"))
316                 {
317                         strlcpy(name, com_token, sizeof(name));
318                         COM_ParseToken_Simple(&bufptr, true, false, true);
319                 }
320
321                 // OPTIONAL: remaining unsupported tokens (eat them)
322                 while (bufptr && strcmp(com_token, "\n"))
323                         COM_ParseToken_Simple(&bufptr, true, false, true);
324
325                 //Con_Printf("data: %d %d %d %f %d (%s)\n", i, start, len, fps, loop, name);
326
327                 if(cb)
328                         cb(i, start, len, fps, loop, (name[0] ? name : NULL), pass);
329                 ++i;
330         }
331
332         return i;
333 }
334
335 static void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, const char *name, void *pass)
336 {
337         dp_model_t *mod = (dp_model_t *) pass;
338         animscene_t *anim = &mod->animscenes[i];
339         if(name)
340                 strlcpy(anim->name, name, sizeof(anim[i].name));
341         else
342                 dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
343         anim->firstframe = bound(0, start, mod->num_poses - 1);
344         anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
345         anim->framerate = max(1, fps);
346         anim->loop = !!loop;
347         //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
348 }
349
350 static void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
351 {
352         unsigned int cnt;
353
354         // 0. count
355         cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
356         if(!cnt)
357         {
358                 Con_Printf("no scene found in framegroups file, aborting\n");
359                 return;
360         }
361         mod->numframes = cnt;
362
363         // 1. reallocate
364         // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
365         mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
366
367         // 2. parse
368         Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
369 }
370
371 static void Mod_FindPotentialDeforms(dp_model_t *mod)
372 {
373         int i, j;
374         texture_t *texture;
375         mod->wantnormals = false;
376         mod->wanttangents = false;
377         for (i = 0;i < mod->num_textures;i++)
378         {
379                 texture = mod->data_textures + i;
380                 if (texture->materialshaderpass && texture->materialshaderpass->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
381                         mod->wantnormals = true;
382                 if (texture->materialshaderpass && texture->materialshaderpass->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
383                         mod->wantnormals = true;
384                 for (j = 0;j < Q3MAXDEFORMS;j++)
385                 {
386                         if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
387                         {
388                                 mod->wanttangents = true;
389                                 mod->wantnormals = true;
390                                 break;
391                         }
392                         if (texture->deforms[j].deform != Q3DEFORM_NONE)
393                                 mod->wantnormals = true;
394                 }
395         }
396 }
397
398 /*
399 ==================
400 Mod_LoadModel
401
402 Loads a model
403 ==================
404 */
405 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
406 {
407         unsigned int crc;
408         void *buf;
409         fs_offset_t filesize = 0;
410         char vabuf[1024];
411
412         mod->used = true;
413
414         if (mod->name[0] == '*') // submodel
415                 return mod;
416         
417         if (!strcmp(mod->name, "null"))
418         {
419                 if(mod->loaded)
420                         return mod;
421
422                 if (mod->loaded || mod->mempool)
423                         Mod_UnloadModel(mod);
424
425                 if (developer_loading.integer)
426                         Con_Printf("loading model %s\n", mod->name);
427
428                 mod->used = true;
429                 mod->crc = (unsigned int)-1;
430                 mod->loaded = false;
431
432                 VectorClear(mod->normalmins);
433                 VectorClear(mod->normalmaxs);
434                 VectorClear(mod->yawmins);
435                 VectorClear(mod->yawmaxs);
436                 VectorClear(mod->rotatedmins);
437                 VectorClear(mod->rotatedmaxs);
438
439                 mod->modeldatatypestring = "null";
440                 mod->type = mod_null;
441                 mod->Draw = R_Model_Null_Draw;
442                 mod->numframes = 2;
443                 mod->numskins = 1;
444
445                 // no fatal errors occurred, so this model is ready to use.
446                 mod->loaded = true;
447
448                 return mod;
449         }
450
451         crc = 0;
452         buf = NULL;
453
454         // even if the model is loaded it still may need reloading...
455
456         // if it is not loaded or checkdisk is true we need to calculate the crc
457         if (!mod->loaded || checkdisk)
458         {
459                 if (checkdisk && mod->loaded)
460                         Con_DPrintf("checking model %s\n", mod->name);
461                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
462                 if (buf)
463                 {
464                         crc = CRC_Block((unsigned char *)buf, filesize);
465                         // we need to reload the model if the crc does not match
466                         if (mod->crc != crc)
467                                 mod->loaded = false;
468                 }
469         }
470
471         // if the model is already loaded and checks passed, just return
472         if (mod->loaded)
473         {
474                 if (buf)
475                         Mem_Free(buf);
476                 return mod;
477         }
478
479         if (developer_loading.integer)
480                 Con_Printf("loading model %s\n", mod->name);
481         
482         SCR_PushLoadingScreen(mod->name, 1);
483
484         // LadyHavoc: unload the existing model in this slot (if there is one)
485         if (mod->loaded || mod->mempool)
486                 Mod_UnloadModel(mod);
487
488         // load the model
489         mod->used = true;
490         mod->crc = crc;
491         // errors can prevent the corresponding mod->loaded = true;
492         mod->loaded = false;
493
494         // default lightmap scale
495         mod->lightmapscale = 1;
496
497         // default model radius and bounding box (mainly for missing models)
498         mod->radius = 16;
499         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
500         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
501         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
502         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
503         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
504         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
505
506         if (!q3shaders_mem)
507         {
508                 // load q3 shaders for the first time, or after a level change
509                 Mod_LoadQ3Shaders();
510         }
511
512         if (buf)
513         {
514                 int i;
515                 const char *ext = FS_FileExtension(mod->name);  
516                 char *bufend = (char *)buf + filesize;
517                 // all models use memory, so allocate a memory pool
518                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
519
520                 // call the apropriate loader
521                 loadmodel = mod;
522
523                 // Try matching magic bytes.
524                 for (i = 0; loader[i].Load; i++)
525                 {
526                         // Headerless formats can just load based on extension. Otherwise match the magic string.
527                         if((loader[i].extension && !strcasecmp(ext, loader[i].extension) && !loader[i].header) ||
528                            (loader[i].header && !memcmp(buf, loader[i].header, loader[i].headersize)))
529                         {
530                                 // Matched. Load it.
531                                 loader[i].Load(mod, buf, bufend);
532                                 Mem_Free(buf);
533
534                                 Mod_FindPotentialDeforms(mod);
535
536                                 buf = FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.framegroups", mod->name), tempmempool, false, &filesize);
537                                 if(buf)
538                                 {
539                                         Mod_FrameGroupify(mod, (const char *)buf);
540                                         Mem_Free(buf);
541                                 }
542
543                                 Mod_BuildVBOs();
544                                 break;
545                         }
546                 }
547                 if(!loader[i].Load)
548                         Con_Printf(CON_ERROR "Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
549         }
550         else if (crash)
551                 // LadyHavoc: Sys_Error was *ANNOYING*
552                 Con_Printf (CON_ERROR "Mod_LoadModel: %s not found\n", mod->name);
553
554         // no fatal errors occurred, so this model is ready to use.
555         mod->loaded = true;
556
557         SCR_PopLoadingScreen(false);
558
559         return mod;
560 }
561
562 void Mod_ClearUsed(void)
563 {
564         int i;
565         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
566         dp_model_t *mod;
567         for (i = 0;i < nummodels;i++)
568                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
569                         mod->used = false;
570 }
571
572 void Mod_PurgeUnused(void)
573 {
574         int i;
575         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
576         dp_model_t *mod;
577         for (i = 0;i < nummodels;i++)
578         {
579                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
580                 {
581                         Mod_UnloadModel(mod);
582                         Mem_ExpandableArray_FreeRecord(&models, mod);
583                 }
584         }
585 }
586
587 /*
588 ==================
589 Mod_FindName
590
591 ==================
592 */
593 dp_model_t *Mod_FindName(const char *name, const char *parentname)
594 {
595         int i;
596         int nummodels;
597         dp_model_t *mod;
598
599         if (!parentname)
600                 parentname = "";
601
602         nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
603
604         if (!name[0])
605                 Host_Error ("Mod_ForName: empty name");
606
607         // search the currently loaded models
608         for (i = 0;i < nummodels;i++)
609         {
610                 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))))
611                 {
612                         mod->used = true;
613                         return mod;
614                 }
615         }
616
617         // no match found, create a new one
618         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
619         strlcpy(mod->name, name, sizeof(mod->name));
620         if (parentname[0])
621                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
622         else
623                 mod->brush.parentmodel = NULL;
624         mod->loaded = false;
625         mod->used = true;
626         return mod;
627 }
628
629 /*
630 ==================
631 Mod_ForName
632
633 Loads in a model for the given name
634 ==================
635 */
636 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
637 {
638         dp_model_t *model;
639         model = Mod_FindName(name, parentname);
640         if (!model->loaded || checkdisk)
641                 Mod_LoadModel(model, crash, checkdisk);
642         return model;
643 }
644
645 /*
646 ==================
647 Mod_Reload
648
649 Reloads all models if they have changed
650 ==================
651 */
652 void Mod_Reload(void)
653 {
654         int i, count;
655         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
656         dp_model_t *mod;
657
658         SCR_PushLoadingScreen("Reloading models", 1.0);
659         count = 0;
660         for (i = 0;i < nummodels;i++)
661                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
662                         ++count;
663         for (i = 0;i < nummodels;i++)
664                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
665                 {
666                         SCR_PushLoadingScreen(mod->name, 1.0 / count);
667                         Mod_LoadModel(mod, true, true);
668                         SCR_PopLoadingScreen(false);
669                 }
670         SCR_PopLoadingScreen(false);
671 }
672
673 unsigned char *mod_base;
674
675
676 //=============================================================================
677
678 /*
679 ================
680 Mod_Print
681 ================
682 */
683 static void Mod_Print_f(cmd_state_t *cmd)
684 {
685         int i;
686         int nummodels = (int)Mem_ExpandableArray_IndexRange(&models);
687         dp_model_t *mod;
688
689         Con_Print("Loaded models:\n");
690         for (i = 0;i < nummodels;i++)
691         {
692                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
693                 {
694                         if (mod->brush.numsubmodels)
695                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
696                         else
697                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
698                 }
699         }
700 }
701
702 /*
703 ================
704 Mod_Precache
705 ================
706 */
707 static void Mod_Precache_f(cmd_state_t *cmd)
708 {
709         if (Cmd_Argc(cmd) == 2)
710                 Mod_ForName(Cmd_Argv(cmd, 1), false, true, Cmd_Argv(cmd, 1)[0] == '*' ? cl.model_name[1] : NULL);
711         else
712                 Con_Print("usage: modelprecache <filename>\n");
713 }
714
715 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
716 {
717         int i, count;
718         unsigned char *used;
719         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
720         memset(used, 0, numvertices);
721         for (i = 0;i < numelements;i++)
722                 used[elements[i]] = 1;
723         for (i = 0, count = 0;i < numvertices;i++)
724                 remapvertices[i] = used[i] ? count++ : -1;
725         Mem_Free(used);
726         return count;
727 }
728
729 qboolean Mod_ValidateElements(int *element3i, unsigned short *element3s, int numtriangles, int firstvertex, int numvertices, const char *filename, int fileline)
730 {
731         int first = firstvertex, last = first + numvertices - 1, numelements = numtriangles * 3;
732         int i;
733         int invalidintcount = 0, invalidintexample = 0;
734         int invalidshortcount = 0, invalidshortexample = 0;
735         int invalidmismatchcount = 0, invalidmismatchexample = 0;
736         if (element3i)
737         {
738                 for (i = 0; i < numelements; i++)
739                 {
740                         if (element3i[i] < first || element3i[i] > last)
741                         {
742                                 invalidintcount++;
743                                 invalidintexample = i;
744                         }
745                 }
746         }
747         if (element3s)
748         {
749                 for (i = 0; i < numelements; i++)
750                 {
751                         if (element3s[i] < first || element3s[i] > last)
752                         {
753                                 invalidintcount++;
754                                 invalidintexample = i;
755                         }
756                 }
757         }
758         if (element3i && element3s)
759         {
760                 for (i = 0; i < numelements; i++)
761                 {
762                         if (element3s[i] != element3i[i])
763                         {
764                                 invalidmismatchcount++;
765                                 invalidmismatchexample = i;
766                         }
767                 }
768         }
769         if (invalidintcount || invalidshortcount || invalidmismatchcount)
770         {
771                 Con_Printf("Mod_ValidateElements(%i, %i, %i, %p, %p) called at %s:%d", numelements, first, last, (void *)element3i, (void *)element3s, filename, fileline);
772                 Con_Printf(", %i elements are invalid in element3i (example: element3i[%i] == %i)", invalidintcount, invalidintexample, element3i ? element3i[invalidintexample] : 0);
773                 Con_Printf(", %i elements are invalid in element3s (example: element3s[%i] == %i)", invalidshortcount, invalidshortexample, element3s ? element3s[invalidshortexample] : 0);
774                 Con_Printf(", %i elements mismatch between element3i and element3s (example: element3s[%i] is %i and element3i[%i] is %i)", invalidmismatchcount, invalidmismatchexample, element3s ? element3s[invalidmismatchexample] : 0, invalidmismatchexample, element3i ? element3i[invalidmismatchexample] : 0);
775                 Con_Print(".  Please debug the engine code - these elements have been modified to not crash, but nothing more.\n");
776
777                 // edit the elements to make them safer, as the driver will crash otherwise
778                 if (element3i)
779                         for (i = 0; i < numelements; i++)
780                                 if (element3i[i] < first || element3i[i] > last)
781                                         element3i[i] = first;
782                 if (element3s)
783                         for (i = 0; i < numelements; i++)
784                                 if (element3s[i] < first || element3s[i] > last)
785                                         element3s[i] = first;
786                 if (element3i && element3s)
787                         for (i = 0; i < numelements; i++)
788                                 if (element3s[i] != element3i[i])
789                                         element3s[i] = element3i[i];
790
791                 return false;
792         }
793         return true;
794 }
795
796 // warning: this is an expensive function!
797 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
798 {
799         int i, j;
800         const int *element;
801         float *vectorNormal;
802         float areaNormal[3];
803         // clear the vectors
804         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
805         // process each vertex of each triangle and accumulate the results
806         // use area-averaging, to make triangles with a big area have a bigger
807         // weighting on the vertex normal than triangles with a small area
808         // to do so, just add the 'normals' together (the bigger the area
809         // the greater the length of the normal is
810         element = elements;
811         for (i = 0; i < numtriangles; i++, element += 3)
812         {
813                 TriangleNormal(
814                         vertex3f + element[0] * 3,
815                         vertex3f + element[1] * 3,
816                         vertex3f + element[2] * 3,
817                         areaNormal
818                         );
819
820                 if (!areaweighting)
821                         VectorNormalize(areaNormal);
822
823                 for (j = 0;j < 3;j++)
824                 {
825                         vectorNormal = normal3f + element[j] * 3;
826                         vectorNormal[0] += areaNormal[0];
827                         vectorNormal[1] += areaNormal[1];
828                         vectorNormal[2] += areaNormal[2];
829                 }
830         }
831         // and just normalize the accumulated vertex normal in the end
832         vectorNormal = normal3f + 3 * firstvertex;
833         for (i = 0; i < numvertices; i++, vectorNormal += 3)
834                 VectorNormalize(vectorNormal);
835 }
836
837 #if 0
838 static 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)
839 {
840         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
841         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
842         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
843
844         // 6 multiply, 9 subtract
845         VectorSubtract(v1, v0, v10);
846         VectorSubtract(v2, v0, v20);
847         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
848         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
849         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
850         // 12 multiply, 10 subtract
851         tc10[1] = tc1[1] - tc0[1];
852         tc20[1] = tc2[1] - tc0[1];
853         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
854         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
855         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
856         tc10[0] = tc1[0] - tc0[0];
857         tc20[0] = tc2[0] - tc0[0];
858         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
859         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
860         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
861         // 12 multiply, 4 add, 6 subtract
862         f = DotProduct(svector3f, normal3f);
863         svector3f[0] -= f * normal3f[0];
864         svector3f[1] -= f * normal3f[1];
865         svector3f[2] -= f * normal3f[2];
866         f = DotProduct(tvector3f, normal3f);
867         tvector3f[0] -= f * normal3f[0];
868         tvector3f[1] -= f * normal3f[1];
869         tvector3f[2] -= f * normal3f[2];
870         // if texture is mapped the wrong way (counterclockwise), the tangents
871         // have to be flipped, this is detected by calculating a normal from the
872         // two tangents, and seeing if it is opposite the surface normal
873         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
874         CrossProduct(tvector3f, svector3f, tangentcross);
875         if (DotProduct(tangentcross, normal3f) < 0)
876         {
877                 VectorNegate(svector3f, svector3f);
878                 VectorNegate(tvector3f, tvector3f);
879         }
880 }
881 #endif
882
883 // warning: this is a very expensive function!
884 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)
885 {
886         int i, tnum;
887         float sdir[3], tdir[3], normal[3], *svec, *tvec;
888         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
889         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
890         const int *e;
891         // clear the vectors
892         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
893         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
894         // process each vertex of each triangle and accumulate the results
895         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
896         {
897                 v0 = vertex3f + e[0] * 3;
898                 v1 = vertex3f + e[1] * 3;
899                 v2 = vertex3f + e[2] * 3;
900                 tc0 = texcoord2f + e[0] * 2;
901                 tc1 = texcoord2f + e[1] * 2;
902                 tc2 = texcoord2f + e[2] * 2;
903
904                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
905                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
906
907                 // calculate the edge directions and surface normal
908                 // 6 multiply, 9 subtract
909                 VectorSubtract(v1, v0, v10);
910                 VectorSubtract(v2, v0, v20);
911                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
912                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
913                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
914
915                 // calculate the tangents
916                 // 12 multiply, 10 subtract
917                 tc10[1] = tc1[1] - tc0[1];
918                 tc20[1] = tc2[1] - tc0[1];
919                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
920                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
921                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
922                 tc10[0] = tc1[0] - tc0[0];
923                 tc20[0] = tc2[0] - tc0[0];
924                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
925                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
926                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
927
928                 // if texture is mapped the wrong way (counterclockwise), the tangents
929                 // have to be flipped, this is detected by calculating a normal from the
930                 // two tangents, and seeing if it is opposite the surface normal
931                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
932                 CrossProduct(tdir, sdir, tangentcross);
933                 if (DotProduct(tangentcross, normal) < 0)
934                 {
935                         VectorNegate(sdir, sdir);
936                         VectorNegate(tdir, tdir);
937                 }
938
939                 if (!areaweighting)
940                 {
941                         VectorNormalize(sdir);
942                         VectorNormalize(tdir);
943                 }
944                 for (i = 0;i < 3;i++)
945                 {
946                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
947                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
948                 }
949         }
950         // make the tangents completely perpendicular to the surface normal, and
951         // then normalize them
952         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
953         for (i = 0, svec = svector3f + 3 * firstvertex, tvec = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, svec += 3, tvec += 3, n += 3)
954         {
955                 f = -DotProduct(svec, n);
956                 VectorMA(svec, f, n, svec);
957                 VectorNormalize(svec);
958                 f = -DotProduct(tvec, n);
959                 VectorMA(tvec, f, n, tvec);
960                 VectorNormalize(tvec);
961         }
962 }
963
964 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors)
965 {
966         unsigned char *data;
967         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 * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0));
968         loadmodel->surfmesh.num_vertices = numvertices;
969         loadmodel->surfmesh.num_triangles = numtriangles;
970         if (loadmodel->surfmesh.num_vertices)
971         {
972                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
973                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
974                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
975                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
976                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
977                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
978                 if (vertexcolors)
979                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
980                 if (lightmapoffsets)
981                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
982         }
983         if (loadmodel->surfmesh.num_triangles)
984         {
985                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
986                 if (loadmodel->surfmesh.num_vertices <= 65536)
987                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
988         }
989 }
990
991 shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts, int maxtriangles)
992 {
993         shadowmesh_t *newmesh;
994         newmesh = (shadowmesh_t *)Mem_Alloc(mempool, sizeof(shadowmesh_t));
995         newmesh->mempool = mempool;
996         newmesh->maxverts = maxverts;
997         newmesh->maxtriangles = maxtriangles;
998         newmesh->numverts = 0;
999         newmesh->numtriangles = 0;
1000         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
1001         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
1002
1003         newmesh->vertex3f = (float *)Mem_Alloc(mempool, maxverts * sizeof(float[3]));
1004         newmesh->element3i = (int *)Mem_Alloc(mempool, maxtriangles * sizeof(int[3]));
1005         newmesh->vertexhashtable = (shadowmeshvertexhash_t **)Mem_Alloc(mempool, SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *));
1006         newmesh->vertexhashentries = (shadowmeshvertexhash_t *)Mem_Alloc(mempool, maxverts * sizeof(shadowmeshvertexhash_t));
1007         return newmesh;
1008 }
1009
1010 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, const float *vertex3f)
1011 {
1012         int hashindex, vnum;
1013         shadowmeshvertexhash_t *hash;
1014         // this uses prime numbers intentionally
1015         hashindex = (unsigned int) (vertex3f[0] * 2003 + vertex3f[1] * 4001 + vertex3f[2] * 7919) % SHADOWMESHVERTEXHASH;
1016         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1017         {
1018                 vnum = (hash - mesh->vertexhashentries);
1019                 if (mesh->vertex3f[vnum * 3 + 0] == vertex3f[0] && mesh->vertex3f[vnum * 3 + 1] == vertex3f[1] && mesh->vertex3f[vnum * 3 + 2] == vertex3f[2])
1020                         return hash - mesh->vertexhashentries;
1021         }
1022         vnum = mesh->numverts++;
1023         hash = mesh->vertexhashentries + vnum;
1024         hash->next = mesh->vertexhashtable[hashindex];
1025         mesh->vertexhashtable[hashindex] = hash;
1026         mesh->vertex3f[vnum * 3 + 0] = vertex3f[0];
1027         mesh->vertex3f[vnum * 3 + 1] = vertex3f[1];
1028         mesh->vertex3f[vnum * 3 + 2] = vertex3f[2];
1029         return vnum;
1030 }
1031
1032 void Mod_ShadowMesh_AddMesh(shadowmesh_t *mesh, const float *vertex3f, int numtris, const int *element3i)
1033 {
1034         int i;
1035
1036         for (i = 0;i < numtris;i++)
1037         {
1038                 mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex3f + 3 * element3i[i * 3 + 0]);
1039                 mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex3f + 3 * element3i[i * 3 + 1]);
1040                 mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex3f + 3 * element3i[i * 3 + 2]);
1041                 mesh->numtriangles++;
1042         }
1043
1044         // the triangle calculation can take a while, so let's do a keepalive here
1045         CL_KeepaliveMessage(false);
1046 }
1047
1048 shadowmesh_t *Mod_ShadowMesh_Begin(mempool_t *mempool, int maxverts, int maxtriangles)
1049 {
1050         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1051         CL_KeepaliveMessage(false);
1052
1053         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles);
1054 }
1055
1056 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1057 {
1058         if (!mesh->numverts)
1059                 return;
1060
1061         // make sure we don't crash inside the driver if something went wrong, as it's annoying to debug
1062         Mod_ValidateElements(mesh->element3i, mesh->element3s, mesh->numtriangles, 0, mesh->numverts, __FILE__, __LINE__);
1063
1064         // upload short indices as a buffer
1065         if (mesh->element3s && !mesh->element3s_indexbuffer)
1066                 mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), "shadowmesh", true, false, false, true);
1067
1068         // upload int indices as a buffer
1069         if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
1070                 mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), "shadowmesh", true, false, false, false);
1071
1072         // vertex buffer is several arrays and we put them in the same buffer
1073         //
1074         // is this wise?  the texcoordtexture2f array is used with dynamic
1075         // vertex/svector/tvector/normal when rendering animated models, on the
1076         // other hand animated models don't use a lot of vertices anyway...
1077         if (!mesh->vbo_vertexbuffer)
1078         {
1079                 mesh->vbooffset_vertex3f = 0;
1080                 mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mesh->vertex3f, mesh->numverts * sizeof(float[3]), "shadowmesh", false, false, false, false);
1081         }
1082 }
1083
1084 shadowmesh_t *Mod_ShadowMesh_Finish(shadowmesh_t *mesh, qboolean createvbo)
1085 {
1086         if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1087         {
1088                 if (mesh->vertexhashentries)
1089                         Mem_Free(mesh->vertexhashentries);
1090                 mesh->vertexhashentries = NULL;
1091                 if (mesh->vertexhashtable)
1092                         Mem_Free(mesh->vertexhashtable);
1093                 mesh->vertexhashtable = NULL;
1094                 if (mesh->maxverts > mesh->numverts)
1095                 {
1096                         mesh->vertex3f = (float *)Mem_Realloc(mesh->mempool, mesh->vertex3f, mesh->numverts * sizeof(float[3]));
1097                         mesh->maxverts = mesh->numverts;
1098                 }
1099                 if (mesh->maxtriangles > mesh->numtriangles)
1100                 {
1101                         mesh->element3i = (int *)Mem_Realloc(mesh->mempool, mesh->element3i, mesh->numtriangles * sizeof(int[3]));
1102                         mesh->maxtriangles = mesh->numtriangles;
1103                 }
1104                 if (mesh->numverts <= 65536)
1105                 {
1106                         int i;
1107                         mesh->element3s = (unsigned short *)Mem_Alloc(mesh->mempool, mesh->numtriangles * sizeof(unsigned short[3]));
1108                         for (i = 0;i < mesh->numtriangles*3;i++)
1109                                 mesh->element3s[i] = mesh->element3i[i];
1110                 }
1111                 if (createvbo)
1112                         Mod_ShadowMesh_CreateVBOs(mesh);
1113         }
1114
1115         // this can take a while, so let's do a keepalive here
1116         CL_KeepaliveMessage(false);
1117
1118         return mesh;
1119 }
1120
1121 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *mesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1122 {
1123         int i;
1124         vec3_t nmins, nmaxs, ncenter, temp;
1125         float nradius2, dist2, *v;
1126         VectorClear(nmins);
1127         VectorClear(nmaxs);
1128         // calculate bbox
1129         VectorCopy(mesh->vertex3f, nmins);
1130         VectorCopy(mesh->vertex3f, nmaxs);
1131         for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1132         {
1133                 if (nmins[0] > v[0]) { nmins[0] = v[0]; } if (nmaxs[0] < v[0]) { nmaxs[0] = v[0]; }
1134                 if (nmins[1] > v[1]) { nmins[1] = v[1]; } if (nmaxs[1] < v[1]) { nmaxs[1] = v[1]; }
1135                 if (nmins[2] > v[2]) { nmins[2] = v[2]; } if (nmaxs[2] < v[2]) { nmaxs[2] = v[2]; }
1136         }
1137         // calculate center and radius
1138         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1139         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1140         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1141         nradius2 = 0;
1142         for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1143         {
1144                 VectorSubtract(v, ncenter, temp);
1145                 dist2 = DotProduct(temp, temp);
1146                 if (nradius2 < dist2)
1147                         nradius2 = dist2;
1148         }
1149         // return data
1150         if (mins)
1151                 VectorCopy(nmins, mins);
1152         if (maxs)
1153                 VectorCopy(nmaxs, maxs);
1154         if (center)
1155                 VectorCopy(ncenter, center);
1156         if (radius)
1157                 *radius = sqrt(nradius2);
1158 }
1159
1160 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1161 {
1162         if (mesh->element3i_indexbuffer)
1163                 R_Mesh_DestroyMeshBuffer(mesh->element3i_indexbuffer);
1164         if (mesh->element3s_indexbuffer)
1165                 R_Mesh_DestroyMeshBuffer(mesh->element3s_indexbuffer);
1166         if (mesh->vbo_vertexbuffer)
1167                 R_Mesh_DestroyMeshBuffer(mesh->vbo_vertexbuffer);
1168         if (mesh->vertex3f)
1169                 Mem_Free(mesh->vertex3f);
1170         if (mesh->element3i)
1171                 Mem_Free(mesh->element3i);
1172         if (mesh->element3s)
1173                 Mem_Free(mesh->element3s);
1174         if (mesh->vertexhashentries)
1175                 Mem_Free(mesh->vertexhashentries);
1176         if (mesh->vertexhashtable)
1177                 Mem_Free(mesh->vertexhashtable);
1178         Mem_Free(mesh);
1179 }
1180
1181 void Mod_CreateCollisionMesh(dp_model_t *mod)
1182 {
1183         int k, numcollisionmeshtriangles;
1184         qboolean usesinglecollisionmesh = false;
1185         const msurface_t *surface = NULL;
1186
1187         mempool_t *mempool = mod->mempool;
1188         if (!mempool && mod->brush.parentmodel)
1189                 mempool = mod->brush.parentmodel->mempool;
1190         // make a single combined collision mesh for physics engine use
1191         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1192         numcollisionmeshtriangles = 0;
1193         for (k = 0;k < mod->nummodelsurfaces;k++)
1194         {
1195                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1196                 if (!strcmp(surface->texture->name, "collision") || !strcmp(surface->texture->name, "collisionconvex")) // found collision mesh
1197                 {
1198                         usesinglecollisionmesh = true;
1199                         numcollisionmeshtriangles = surface->num_triangles;
1200                         break;
1201                 }
1202                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1203                         continue;
1204                 numcollisionmeshtriangles += surface->num_triangles;
1205         }
1206         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles);
1207         if (usesinglecollisionmesh)
1208                 Mod_ShadowMesh_AddMesh(mod->brush.collisionmesh, mod->surfmesh.data_vertex3f, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
1209         else
1210         {
1211                 for (k = 0;k < mod->nummodelsurfaces;k++)
1212                 {
1213                         surface = mod->data_surfaces + mod->firstmodelsurface + k;
1214                         if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1215                                 continue;
1216                         Mod_ShadowMesh_AddMesh(mod->brush.collisionmesh, mod->surfmesh.data_vertex3f, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
1217                 }
1218         }
1219         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mod->brush.collisionmesh, false);
1220 }
1221
1222 #if 0
1223 static 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)
1224 {
1225         float v[3], tc[3];
1226         v[0] = ix;
1227         v[1] = iy;
1228         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1229                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1230         else
1231                 v[2] = 0;
1232         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1233         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1234         texcoord2f[0] = tc[0];
1235         texcoord2f[1] = tc[1];
1236 }
1237
1238 static 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)
1239 {
1240         float vup[3], vdown[3], vleft[3], vright[3];
1241         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1242         float sv[3], tv[3], nl[3];
1243         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1244         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1245         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1246         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1247         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1248         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1249         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1250         VectorAdd(svector3f, sv, svector3f);
1251         VectorAdd(tvector3f, tv, tvector3f);
1252         VectorAdd(normal3f, nl, normal3f);
1253         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1254         VectorAdd(svector3f, sv, svector3f);
1255         VectorAdd(tvector3f, tv, tvector3f);
1256         VectorAdd(normal3f, nl, normal3f);
1257         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1258         VectorAdd(svector3f, sv, svector3f);
1259         VectorAdd(tvector3f, tv, tvector3f);
1260         VectorAdd(normal3f, nl, normal3f);
1261 }
1262
1263 static void Mod_ConstructTerrainPatchFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int x1, int y1, int width, int height, int *element3i, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1264 {
1265         int x, y, ix, iy, *e;
1266         e = element3i;
1267         for (y = 0;y < height;y++)
1268         {
1269                 for (x = 0;x < width;x++)
1270                 {
1271                         e[0] = (y + 1) * (width + 1) + (x + 0);
1272                         e[1] = (y + 0) * (width + 1) + (x + 0);
1273                         e[2] = (y + 1) * (width + 1) + (x + 1);
1274                         e[3] = (y + 0) * (width + 1) + (x + 0);
1275                         e[4] = (y + 0) * (width + 1) + (x + 1);
1276                         e[5] = (y + 1) * (width + 1) + (x + 1);
1277                         e += 6;
1278                 }
1279         }
1280         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1281                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1282                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1283 }
1284 #endif
1285
1286 #if 0
1287 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1288 {
1289         float mins[3];
1290         float maxs[3];
1291         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1292         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1293         float viewvector[3];
1294         unsigned int firstvertex;
1295         unsigned int *e;
1296         float *v;
1297         if (chunkwidth < 2 || chunkheight < 2)
1298                 return;
1299         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]);
1300         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]);
1301         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1302         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1303         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1304         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1305         {
1306                 // too close for this stepsize, emit as 4 chunks instead
1307                 stepsize /= 2;
1308                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1309                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1310                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1311                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1312                 return;
1313         }
1314         // emit the geometry at stepsize into our vertex buffer / index buffer
1315         // we add two columns and two rows for skirt
1316         outwidth = chunkwidth+2;
1317         outheight = chunkheight+2;
1318         outwidth2 = outwidth-1;
1319         outheight2 = outheight-1;
1320         outwidth3 = outwidth+1;
1321         outheight3 = outheight+1;
1322         firstvertex = numvertices;
1323         e = model->terrain.element3i + numtriangles;
1324         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1325         v = model->terrain.vertex3f + numvertices;
1326         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1327         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1328         for (ty = 0;ty < outheight;ty++)
1329         {
1330                 for (tx = 0;tx < outwidth;tx++)
1331                 {
1332                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1333                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1334                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1335                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1336                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1337                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1338                 }
1339         }
1340         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1341         for (ty = 0;ty <= outheight;ty++)
1342         {
1343                 skirtrow = ty == 0 || ty == outheight;
1344                 ry = y+bound(1, ty, outheight)*stepsize;
1345                 for (tx = 0;tx <= outwidth;tx++)
1346                 {
1347                         skirt = skirtrow || tx == 0 || tx == outwidth;
1348                         rx = x+bound(1, tx, outwidth)*stepsize;
1349                         v[0] = rx*scale[0];
1350                         v[1] = ry*scale[1];
1351                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1352                         v += 3;
1353                 }
1354         }
1355         // TODO: emit skirt vertices
1356 }
1357
1358 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1359 {
1360         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1361         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1362         Mod_Terrain_BuildChunk(model, 
1363 }
1364 #endif
1365
1366 static int Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1367 {
1368         int offset = 0;
1369         if (!strncasecmp(s, "user", 4)) // parse stuff like "user1sin", always user<n>func
1370         {
1371                 offset = bound(0, s[4] - '0', 9);
1372                 offset = (offset + 1) << Q3WAVEFUNC_USER_SHIFT;
1373                 s += 4;
1374                 if(*s)
1375                         ++s;
1376         }
1377         if (!strcasecmp(s, "sin"))             return offset | Q3WAVEFUNC_SIN;
1378         if (!strcasecmp(s, "square"))          return offset | Q3WAVEFUNC_SQUARE;
1379         if (!strcasecmp(s, "triangle"))        return offset | Q3WAVEFUNC_TRIANGLE;
1380         if (!strcasecmp(s, "sawtooth"))        return offset | Q3WAVEFUNC_SAWTOOTH;
1381         if (!strcasecmp(s, "inversesawtooth")) return offset | Q3WAVEFUNC_INVERSESAWTOOTH;
1382         if (!strcasecmp(s, "noise"))           return offset | Q3WAVEFUNC_NOISE;
1383         if (!strcasecmp(s, "none"))            return offset | Q3WAVEFUNC_NONE;
1384         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1385         return offset | Q3WAVEFUNC_NONE;
1386 }
1387
1388 void Mod_FreeQ3Shaders(void)
1389 {
1390         Mem_FreePool(&q3shaders_mem);
1391 }
1392
1393 static void Q3Shader_AddToHash (shader_t* shader)
1394 {
1395         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1396         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1397         q3shader_hash_entry_t* lastEntry = NULL;
1398         do
1399         {
1400                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1401                 {
1402                         // redeclaration
1403                         if(shader->dpshaderkill)
1404                         {
1405                                 // killed shader is a redeclarion? we can safely ignore it
1406                                 return;
1407                         }
1408                         else if(entry->shader.dpshaderkill)
1409                         {
1410                                 // replace the old shader!
1411                                 // this will skip the entry allocating part
1412                                 // below and just replace the shader
1413                                 break;
1414                         }
1415                         else
1416                         {
1417                                 unsigned char *start, *end, *start2;
1418                                 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1419                                 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1420                                 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1421                                 if(memcmp(start, start2, end - start))
1422                                         Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1423                                 else
1424                                         Con_DPrintf("Shader '%s' already defined\n", shader->name);
1425                                 return;
1426                         }
1427                 }
1428                 lastEntry = entry;
1429                 entry = entry->chain;
1430         }
1431         while (entry != NULL);
1432         if (entry == NULL)
1433         {
1434                 if (lastEntry->shader.name[0] != 0)
1435                 {
1436                         /* Add to chain */
1437                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1438                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1439
1440                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1441                         lastEntry->chain = newEntry;
1442                         newEntry->chain = NULL;
1443                         lastEntry = newEntry;
1444                 }
1445                 /* else: head of chain, in hash entry array */
1446                 entry = lastEntry;
1447         }
1448         memcpy (&entry->shader, shader, sizeof (shader_t));
1449 }
1450
1451 void Mod_LoadQ3Shaders(void)
1452 {
1453         int j;
1454         int fileindex;
1455         fssearch_t *search;
1456         char *f;
1457         const char *text;
1458         shader_t shader;
1459         q3shaderinfo_layer_t *layer;
1460         int numparameters;
1461         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1462         char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1463         unsigned long custsurfaceflags[256]; 
1464         int numcustsurfaceflags;
1465         qboolean dpshaderkill;
1466
1467         Mod_FreeQ3Shaders();
1468
1469         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1470         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1471                 sizeof (q3shader_data_t));
1472         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1473                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1474         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1475                 q3shaders_mem, sizeof (char**), 256);
1476
1477         // parse custinfoparms.txt
1478         numcustsurfaceflags = 0;
1479         if ((text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL)) != NULL)
1480         {
1481                 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1482                         Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1483                 else
1484                 {
1485                         while (COM_ParseToken_QuakeC(&text, false))
1486                                 if (!strcasecmp(com_token, "}"))
1487                                         break;
1488                         // custom surfaceflags section
1489                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1490                                 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1491                         else
1492                         {
1493                                 while(COM_ParseToken_QuakeC(&text, false))
1494                                 {
1495                                         if (!strcasecmp(com_token, "}"))
1496                                                 break;  
1497                                         // register surfaceflag
1498                                         if (numcustsurfaceflags >= 256)
1499                                         {
1500                                                 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1501                                                 break;
1502                                         }
1503                                         // name
1504                                         j = (int)strlen(com_token)+1;
1505                                         custsurfaceparmnames[numcustsurfaceflags] = (char *)Mem_Alloc(tempmempool, j);
1506                                         strlcpy(custsurfaceparmnames[numcustsurfaceflags], com_token, j+1);
1507                                         // value
1508                                         if (COM_ParseToken_QuakeC(&text, false))
1509                                                 custsurfaceflags[numcustsurfaceflags] = strtol(com_token, NULL, 0);
1510                                         else
1511                                                 custsurfaceflags[numcustsurfaceflags] = 0;
1512                                         numcustsurfaceflags++;
1513                                 }
1514                         }
1515                 }
1516                 Mem_Free(f);
1517         }
1518
1519         // parse shaders
1520         search = FS_Search("scripts/*.shader", true, false, NULL);
1521         if (!search)
1522                 return;
1523         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1524         {
1525                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1526                 if (!f)
1527                         continue;
1528                 while (COM_ParseToken_QuakeC(&text, false))
1529                 {
1530                         memset (&shader, 0, sizeof(shader));
1531                         shader.name[0] = 0;
1532                         shader.surfaceparms = 0;
1533                         shader.surfaceflags = 0;
1534                         shader.textureflags = 0;
1535                         shader.numlayers = 0;
1536                         shader.lighting = false;
1537                         shader.vertexalpha = false;
1538                         shader.textureblendalpha = false;
1539                         shader.skyboxname[0] = 0;
1540                         shader.deforms[0].deform = Q3DEFORM_NONE;
1541                         shader.dpnortlight = false;
1542                         shader.dpshadow = false;
1543                         shader.dpnoshadow = false;
1544                         shader.dpmeshcollisions = false;
1545                         shader.dpshaderkill = false;
1546                         shader.dpreflectcube[0] = 0;
1547                         shader.reflectmin = 0;
1548                         shader.reflectmax = 1;
1549                         shader.refractfactor = 1;
1550                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1551                         shader.reflectfactor = 1;
1552                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1553                         shader.r_water_wateralpha = 1;
1554                         shader.r_water_waterscroll[0] = 0;
1555                         shader.r_water_waterscroll[1] = 0;
1556                         shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1557                         shader.offsetscale = mod_q3shader_default_offsetmapping_scale.value;
1558                         shader.offsetbias = mod_q3shader_default_offsetmapping_bias.value;
1559                         shader.biaspolygonoffset = mod_q3shader_default_polygonoffset.value;
1560                         shader.biaspolygonfactor = mod_q3shader_default_polygonfactor.value;
1561                         shader.transparentsort = TRANSPARENTSORT_DISTANCE;
1562                         shader.specularscalemod = 1;
1563                         shader.specularpowermod = 1;
1564                         shader.rtlightambient = 0;
1565                         // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1566                         // JUST GREP FOR "specularscalemod = 1".
1567
1568                         strlcpy(shader.name, com_token, sizeof(shader.name));
1569                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1570                         {
1571                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1572                                 break;
1573                         }
1574                         while (COM_ParseToken_QuakeC(&text, false))
1575                         {
1576                                 if (!strcasecmp(com_token, "}"))
1577                                         break;
1578                                 if (!strcasecmp(com_token, "{"))
1579                                 {
1580                                         static q3shaderinfo_layer_t dummy;
1581                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1582                                         {
1583                                                 layer = shader.layers + shader.numlayers++;
1584                                         }
1585                                         else
1586                                         {
1587                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1588                                                 memset(&dummy, 0, sizeof(dummy));
1589                                                 layer = &dummy;
1590                                         }
1591                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1592                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1593                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1594                                         layer->blendfunc[0] = GL_ONE;
1595                                         layer->blendfunc[1] = GL_ZERO;
1596                                         while (COM_ParseToken_QuakeC(&text, false))
1597                                         {
1598                                                 if (!strcasecmp(com_token, "}"))
1599                                                         break;
1600                                                 if (!strcasecmp(com_token, "\n"))
1601                                                         continue;
1602                                                 numparameters = 0;
1603                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1604                                                 {
1605                                                         if (j < TEXTURE_MAXFRAMES + 4)
1606                                                         {
1607                                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1608                                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1609                                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1610                                                                 else
1611                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1612                                                                 numparameters = j + 1;
1613                                                         }
1614                                                         if (!COM_ParseToken_QuakeC(&text, true))
1615                                                                 break;
1616                                                 }
1617                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1618                                                 //      parameter[j][0] = 0;
1619                                                 if (developer_insane.integer)
1620                                                 {
1621                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1622                                                         for (j = 0;j < numparameters;j++)
1623                                                                 Con_DPrintf(" %s", parameter[j]);
1624                                                         Con_DPrint("\n");
1625                                                 }
1626                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1627                                                 {
1628                                                         if (numparameters == 2)
1629                                                         {
1630                                                                 if (!strcasecmp(parameter[1], "add"))
1631                                                                 {
1632                                                                         layer->blendfunc[0] = GL_ONE;
1633                                                                         layer->blendfunc[1] = GL_ONE;
1634                                                                 }
1635                                                                 else if (!strcasecmp(parameter[1], "addalpha"))
1636                                                                 {
1637                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1638                                                                         layer->blendfunc[1] = GL_ONE;
1639                                                                 }
1640                                                                 else if (!strcasecmp(parameter[1], "filter"))
1641                                                                 {
1642                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1643                                                                         layer->blendfunc[1] = GL_ZERO;
1644                                                                 }
1645                                                                 else if (!strcasecmp(parameter[1], "blend"))
1646                                                                 {
1647                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1648                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1649                                                                 }
1650                                                         }
1651                                                         else if (numparameters == 3)
1652                                                         {
1653                                                                 int k;
1654                                                                 for (k = 0;k < 2;k++)
1655                                                                 {
1656                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1657                                                                                 layer->blendfunc[k] = GL_ONE;
1658                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1659                                                                                 layer->blendfunc[k] = GL_ZERO;
1660                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1661                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1662                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1663                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1664                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1665                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1666                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1667                                                                                 layer->blendfunc[k] = GL_DST_ALPHA;
1668                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1669                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1670                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1671                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1672                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1673                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1674                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1675                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1676                                                                         else
1677                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1678                                                                 }
1679                                                         }
1680                                                 }
1681                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1682                                                         layer->alphatest = true;
1683                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1684                                                 {
1685                                                         if (!strcasecmp(parameter[0], "clampmap"))
1686                                                                 layer->clampmap = true;
1687                                                         layer->numframes = 1;
1688                                                         layer->framerate = 1;
1689                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1690                                                                 &q3shader_data->char_ptrs);
1691                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1692                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1693                                                                 shader.lighting = true;
1694                                                 }
1695                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1696                                                 {
1697                                                         int i;
1698                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1699                                                         layer->framerate = atof(parameter[1]);
1700                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1701                                                         for (i = 0;i < layer->numframes;i++)
1702                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1703                                                 }
1704                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1705                                                 {
1706                                                         int i;
1707                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1708                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1709                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1710                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1711                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1712                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1713                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1714                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1715                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1716                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1717                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1718                                                         else if (!strcasecmp(parameter[1], "wave"))
1719                                                         {
1720                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1721                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1722                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1723                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1724                                                         }
1725                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1726                                                 }
1727                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1728                                                 {
1729                                                         int i;
1730                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1731                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1732                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1733                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1734                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1735                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1736                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1737                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1738                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1739                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1740                                                         else if (!strcasecmp(parameter[1], "wave"))
1741                                                         {
1742                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1743                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1744                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1745                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1746                                                         }
1747                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1748                                                 }
1749                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1750                                                 {
1751                                                         int i;
1752                                                         // observed values: tcgen environment
1753                                                         // no other values have been observed in real shaders
1754                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1755                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1756                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1757                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1758                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1759                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1760                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1761                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1762                                                 }
1763                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1764                                                 {
1765                                                         int i, tcmodindex;
1766                                                         // observed values:
1767                                                         // tcmod rotate #
1768                                                         // tcmod scale # #
1769                                                         // tcmod scroll # #
1770                                                         // tcmod stretch sin # # # #
1771                                                         // tcmod stretch triangle # # # #
1772                                                         // tcmod transform # # # # # #
1773                                                         // tcmod turb # # # #
1774                                                         // tcmod turb sin # # # #  (this is bogus)
1775                                                         // no other values have been observed in real shaders
1776                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1777                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1778                                                                         break;
1779                                                         if (tcmodindex < Q3MAXTCMODS)
1780                                                         {
1781                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1782                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1783                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1784                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1785                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1786                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1787                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1788                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1789                                                                 {
1790                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1791                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1792                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1793                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1794                                                                 }
1795                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1796                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1797                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1798                                                         }
1799                                                         else
1800                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1801                                                 }
1802                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1803                                                 if (!strcasecmp(com_token, "}"))
1804                                                         break;
1805                                         }
1806                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1807                                                 shader.lighting = true;
1808                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1809                                         {
1810                                                 if (layer == shader.layers + 0)
1811                                                 {
1812                                                         // vertex controlled transparency
1813                                                         shader.vertexalpha = true;
1814                                                 }
1815                                                 else
1816                                                 {
1817                                                         // multilayer terrain shader or similar
1818                                                         shader.textureblendalpha = true;
1819                                                         if (mod_q3shader_force_terrain_alphaflag.integer)
1820                                                                 shader.layers[0].dptexflags |= TEXF_ALPHA;
1821                                                 }
1822                                         }
1823
1824                                         if(mod_q3shader_force_addalpha.integer)
1825                                         {
1826                                                 // for a long while, DP treated GL_ONE GL_ONE as GL_SRC_ALPHA GL_ONE
1827                                                 // this cvar brings back this behaviour
1828                                                 if(layer->blendfunc[0] == GL_ONE && layer->blendfunc[1] == GL_ONE)
1829                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1830                                         }
1831                                         
1832                                         layer->dptexflags = 0;
1833                                         if (layer->alphatest)
1834                                                 layer->dptexflags |= TEXF_ALPHA;
1835                                         switch(layer->blendfunc[0])
1836                                         {
1837                                                 case GL_SRC_ALPHA:
1838                                                 case GL_ONE_MINUS_SRC_ALPHA:
1839                                                         layer->dptexflags |= TEXF_ALPHA;
1840                                                         break;
1841                                         }
1842                                         switch(layer->blendfunc[1])
1843                                         {
1844                                                 case GL_SRC_ALPHA:
1845                                                 case GL_ONE_MINUS_SRC_ALPHA:
1846                                                         layer->dptexflags |= TEXF_ALPHA;
1847                                                         break;
1848                                         }
1849                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1850                                                 layer->dptexflags |= TEXF_MIPMAP;
1851                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1852                                                 layer->dptexflags |= TEXF_PICMIP | TEXF_COMPRESS;
1853                                         if (layer->clampmap)
1854                                                 layer->dptexflags |= TEXF_CLAMP;
1855                                         continue;
1856                                 }
1857                                 numparameters = 0;
1858                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1859                                 {
1860                                         if (j < TEXTURE_MAXFRAMES + 4)
1861                                         {
1862                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1863                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1864                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1865                                                 else
1866                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1867                                                 numparameters = j + 1;
1868                                         }
1869                                         if (!COM_ParseToken_QuakeC(&text, true))
1870                                                 break;
1871                                 }
1872                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1873                                 //      parameter[j][0] = 0;
1874                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1875                                         break;
1876                                 if (developer_insane.integer)
1877                                 {
1878                                         Con_DPrintf("%s: ", shader.name);
1879                                         for (j = 0;j < numparameters;j++)
1880                                                 Con_DPrintf(" %s", parameter[j]);
1881                                         Con_DPrint("\n");
1882                                 }
1883                                 if (numparameters < 1)
1884                                         continue;
1885                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1886                                 {
1887                                         if (!strcasecmp(parameter[1], "alphashadow"))
1888                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1889                                         else if (!strcasecmp(parameter[1], "areaportal"))
1890                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1891                                         else if (!strcasecmp(parameter[1], "botclip"))
1892                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1893                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1894                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1895                                         else if (!strcasecmp(parameter[1], "detail"))
1896                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1897                                         else if (!strcasecmp(parameter[1], "donotenter"))
1898                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1899                                         else if (!strcasecmp(parameter[1], "dust"))
1900                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1901                                         else if (!strcasecmp(parameter[1], "hint"))
1902                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1903                                         else if (!strcasecmp(parameter[1], "fog"))
1904                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1905                                         else if (!strcasecmp(parameter[1], "lava"))
1906                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1907                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1908                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1909                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1910                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1911                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1912                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1913                                         else if (!strcasecmp(parameter[1], "nodamage"))
1914                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1915                                         else if (!strcasecmp(parameter[1], "nodlight"))
1916                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1917                                         else if (!strcasecmp(parameter[1], "nodraw"))
1918                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1919                                         else if (!strcasecmp(parameter[1], "nodrop"))
1920                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1921                                         else if (!strcasecmp(parameter[1], "noimpact"))
1922                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1923                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1924                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1925                                         else if (!strcasecmp(parameter[1], "nomarks"))
1926                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1927                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1928                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1929                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1930                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1931                                         else if (!strcasecmp(parameter[1], "origin"))
1932                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1933                                         else if (!strcasecmp(parameter[1], "playerclip"))
1934                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1935                                         else if (!strcasecmp(parameter[1], "sky"))
1936                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1937                                         else if (!strcasecmp(parameter[1], "slick"))
1938                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1939                                         else if (!strcasecmp(parameter[1], "slime"))
1940                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1941                                         else if (!strcasecmp(parameter[1], "structural"))
1942                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1943                                         else if (!strcasecmp(parameter[1], "trans"))
1944                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1945                                         else if (!strcasecmp(parameter[1], "water"))
1946                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1947                                         else if (!strcasecmp(parameter[1], "pointlight"))
1948                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1949                                         else if (!strcasecmp(parameter[1], "antiportal"))
1950                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1951                                         else if (!strcasecmp(parameter[1], "skip"))
1952                                                 ; // shader.surfaceparms |= Q3SURFACEPARM_SKIP; FIXME we don't have enough #defines for this any more, and the engine doesn't need this one anyway
1953                                         else
1954                                         {
1955                                                 // try custom surfaceparms
1956                                                 for (j = 0; j < numcustsurfaceflags; j++)
1957                                                 {
1958                                                         if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
1959                                                         {
1960                                                                 shader.surfaceflags |= custsurfaceflags[j];
1961                                                                 break;
1962                                                         }
1963                                                 }
1964                                                 // failed all
1965                                                 if (j == numcustsurfaceflags)
1966                                                         Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1967                                         }
1968                                 }
1969                                 else if (!strcasecmp(parameter[0], "dpshadow"))
1970                                         shader.dpshadow = true;
1971                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1972                                         shader.dpnoshadow = true;
1973                                 else if (!strcasecmp(parameter[0], "dpnortlight"))
1974                                         shader.dpnortlight = true;
1975                                 else if (!strcasecmp(parameter[0], "dpreflectcube"))
1976                                         strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
1977                                 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
1978                                         shader.dpmeshcollisions = true;
1979                                 // this sets dpshaderkill to true if dpshaderkillifcvarzero was used, and to false if dpnoshaderkillifcvarzero was used
1980                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvarzero")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvarzero")) && numparameters >= 2)
1981                                 {
1982                                         if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) == 0.0f)
1983                                                 shader.dpshaderkill = dpshaderkill;
1984                                 }
1985                                 // this sets dpshaderkill to true if dpshaderkillifcvar was used, and to false if dpnoshaderkillifcvar was used
1986                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvar")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvar")) && numparameters >= 2)
1987                                 {
1988                                         const char *op = NULL;
1989                                         if (numparameters >= 3)
1990                                                 op = parameter[2];
1991                                         if(!op)
1992                                         {
1993                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) != 0.0f)
1994                                                         shader.dpshaderkill = dpshaderkill;
1995                                         }
1996                                         else if (numparameters >= 4 && !strcmp(op, "=="))
1997                                         {
1998                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) == atof(parameter[3]))
1999                                                         shader.dpshaderkill = dpshaderkill;
2000                                         }
2001                                         else if (numparameters >= 4 && !strcmp(op, "!="))
2002                                         {
2003                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) != atof(parameter[3]))
2004                                                         shader.dpshaderkill = dpshaderkill;
2005                                         }
2006                                         else if (numparameters >= 4 && !strcmp(op, ">"))
2007                                         {
2008                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) > atof(parameter[3]))
2009                                                         shader.dpshaderkill = dpshaderkill;
2010                                         }
2011                                         else if (numparameters >= 4 && !strcmp(op, "<"))
2012                                         {
2013                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) < atof(parameter[3]))
2014                                                         shader.dpshaderkill = dpshaderkill;
2015                                         }
2016                                         else if (numparameters >= 4 && !strcmp(op, ">="))
2017                                         {
2018                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) >= atof(parameter[3]))
2019                                                         shader.dpshaderkill = dpshaderkill;
2020                                         }
2021                                         else if (numparameters >= 4 && !strcmp(op, "<="))
2022                                         {
2023                                                 if (Cvar_VariableValue(&cvars_all, parameter[1], ~0) <= atof(parameter[3]))
2024                                                         shader.dpshaderkill = dpshaderkill;
2025                                         }
2026                                         else
2027                                         {
2028                                                 Con_DPrintf("%s parsing warning: unknown dpshaderkillifcvar op \"%s\", or not enough arguments\n", search->filenames[fileindex], op);
2029                                         }
2030                                 }
2031                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2032                                 {
2033                                         // some q3 skies don't have the sky parm set
2034                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2035                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2036                                 }
2037                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2038                                 {
2039                                         // some q3 skies don't have the sky parm set
2040                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2041                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2042                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2043                                 }
2044                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2045                                 {
2046                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2047                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2048                                 }
2049                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
2050                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2051                                 else if (!strcasecmp(parameter[0], "nopicmip"))
2052                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2053                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
2054                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2055                                 else if (!strcasecmp(parameter[0], "dppolygonoffset"))
2056                                 {
2057                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2058                                         if(numparameters >= 2)
2059                                         {
2060                                                 shader.biaspolygonfactor = atof(parameter[1]);
2061                                                 if(numparameters >= 3)
2062                                                         shader.biaspolygonoffset = atof(parameter[2]);
2063                                                 else
2064                                                         shader.biaspolygonoffset = 0;
2065                                         }
2066                                 }
2067                                 else if (!strcasecmp(parameter[0], "dptransparentsort") && numparameters >= 2)
2068                                 {
2069                                         shader.textureflags |= Q3TEXTUREFLAG_TRANSPARENTSORT;
2070                                         if (!strcasecmp(parameter[1], "sky"))
2071                                                 shader.transparentsort = TRANSPARENTSORT_SKY;
2072                                         else if (!strcasecmp(parameter[1], "distance"))
2073                                                 shader.transparentsort = TRANSPARENTSORT_DISTANCE;
2074                                         else if (!strcasecmp(parameter[1], "hud"))
2075                                                 shader.transparentsort = TRANSPARENTSORT_HUD;
2076                                         else
2077                                                 Con_DPrintf("%s parsing warning: unknown dptransparentsort category \"%s\", or not enough arguments\n", search->filenames[fileindex], parameter[1]);
2078                                 }
2079                                 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2080                                 {
2081                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2082                                         shader.refractfactor = atof(parameter[1]);
2083                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2084                                 }
2085                                 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2086                                 {
2087                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2088                                         shader.reflectfactor = atof(parameter[1]);
2089                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2090                                 }
2091                                 else if (!strcasecmp(parameter[0], "dpcamera"))
2092                                 {
2093                                         shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2094                                 }
2095                                 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2096                                 {
2097                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2098                                         shader.reflectmin = atof(parameter[1]);
2099                                         shader.reflectmax = atof(parameter[2]);
2100                                         shader.refractfactor = atof(parameter[3]);
2101                                         shader.reflectfactor = atof(parameter[4]);
2102                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2103                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2104                                         shader.r_water_wateralpha = atof(parameter[11]);
2105                                 }
2106                                 else if (!strcasecmp(parameter[0], "dpwaterscroll") && numparameters >= 3)
2107                                 {
2108                                         shader.r_water_waterscroll[0] = 1/atof(parameter[1]);
2109                                         shader.r_water_waterscroll[1] = 1/atof(parameter[2]);
2110                                 }
2111                                 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2112                                 {
2113                                         shader.specularscalemod = atof(parameter[1]);
2114                                 }
2115                                 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2116                                 {
2117                                         shader.specularpowermod = atof(parameter[1]);
2118                                 }
2119                                 else if (!strcasecmp(parameter[0], "dprtlightambient") && numparameters >= 2)
2120                                 {
2121                                         shader.rtlightambient = atof(parameter[1]);
2122                                 }
2123                                 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 2)
2124                                 {
2125                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2126                                                 shader.offsetmapping = OFFSETMAPPING_OFF;
2127                                         else if (!strcasecmp(parameter[1], "default") || !strcasecmp(parameter[1], "normal"))
2128                                                 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2129                                         else if (!strcasecmp(parameter[1], "linear"))
2130                                                 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2131                                         else if (!strcasecmp(parameter[1], "relief"))
2132                                                 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2133                                         if (numparameters >= 3)
2134                                                 shader.offsetscale = atof(parameter[2]);
2135                                         if (numparameters >= 5)
2136                                         {
2137                                                 if(!strcasecmp(parameter[3], "bias"))
2138                                                         shader.offsetbias = atof(parameter[4]);
2139                                                 else if(!strcasecmp(parameter[3], "match"))
2140                                                         shader.offsetbias = 1.0f - atof(parameter[4]);
2141                                                 else if(!strcasecmp(parameter[3], "match8"))
2142                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 255.0f;
2143                                                 else if(!strcasecmp(parameter[3], "match16"))
2144                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 65535.0f;
2145                                         }
2146                                 }
2147                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2148                                 {
2149                                         int i, deformindex;
2150                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2151                                                 if (!shader.deforms[deformindex].deform)
2152                                                         break;
2153                                         if (deformindex < Q3MAXDEFORMS)
2154                                         {
2155                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2156                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2157                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2158                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2159                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2160                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2161                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2162                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2163                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2164                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2165                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2166                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2167                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2168                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2169                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2170                                                 else if (!strcasecmp(parameter[1], "wave"            ))
2171                                                 {
2172                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2173                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2174                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2175                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2176                                                 }
2177                                                 else if (!strcasecmp(parameter[1], "move"            ))
2178                                                 {
2179                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2180                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2181                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2182                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2183                                                 }
2184                                         }
2185                                 }
2186                         }
2187                         // hide this shader if a cvar said it should be killed
2188                         if (shader.dpshaderkill)
2189                                 shader.numlayers = 0;
2190                         // fix up multiple reflection types
2191                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2192                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2193
2194                         Q3Shader_AddToHash (&shader);
2195                 }
2196                 Mem_Free(f);
2197         }
2198         FS_FreeSearch(search);
2199         // free custinfoparm values
2200         for (j = 0; j < numcustsurfaceflags; j++)
2201                 Mem_Free(custsurfaceparmnames[j]);
2202 }
2203
2204 shader_t *Mod_LookupQ3Shader(const char *name)
2205 {
2206         unsigned short hash;
2207         q3shader_hash_entry_t* entry;
2208         if (!q3shaders_mem)
2209                 Mod_LoadQ3Shaders();
2210         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2211         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2212         while (entry != NULL)
2213         {
2214                 if (strcasecmp (entry->shader.name, name) == 0)
2215                         return &entry->shader;
2216                 entry = entry->chain;
2217         }
2218         return NULL;
2219 }
2220
2221 texture_shaderpass_t *Mod_CreateShaderPass(mempool_t *mempool, skinframe_t *skinframe)
2222 {
2223         texture_shaderpass_t *shaderpass = (texture_shaderpass_t *)Mem_Alloc(mempool, sizeof(*shaderpass));
2224         shaderpass->framerate = 0.0f;
2225         shaderpass->numframes = 1;
2226         shaderpass->blendfunc[0] = GL_ONE;
2227         shaderpass->blendfunc[1] = GL_ZERO;
2228         shaderpass->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
2229         shaderpass->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
2230         shaderpass->alphatest = false;
2231         shaderpass->tcgen.tcgen = Q3TCGEN_TEXTURE;
2232         shaderpass->skinframes[0] = skinframe;
2233         return shaderpass;
2234 }
2235
2236 texture_shaderpass_t *Mod_CreateShaderPassFromQ3ShaderLayer(mempool_t *mempool, const char *modelname, q3shaderinfo_layer_t *layer, int layerindex, int texflags, const char *texturename)
2237 {
2238         int j;
2239         texture_shaderpass_t *shaderpass = (texture_shaderpass_t *)Mem_Alloc(mempool, sizeof(*shaderpass));
2240         shaderpass->alphatest = layer->alphatest != 0;
2241         shaderpass->framerate = layer->framerate;
2242         shaderpass->numframes = layer->numframes;
2243         shaderpass->blendfunc[0] = layer->blendfunc[0];
2244         shaderpass->blendfunc[1] = layer->blendfunc[1];
2245         shaderpass->rgbgen = layer->rgbgen;
2246         shaderpass->alphagen = layer->alphagen;
2247         shaderpass->tcgen = layer->tcgen;
2248         for (j = 0; j < Q3MAXTCMODS && layer->tcmods[j].tcmod != Q3TCMOD_NONE; j++)
2249                 shaderpass->tcmods[j] = layer->tcmods[j];
2250         for (j = 0; j < layer->numframes; j++)
2251         {
2252                 for (int i = 0; layer->texturename[j][i]; i++)
2253                         if(layer->texturename[j][i] == '\\')
2254                                 layer->texturename[j][i] = '/';
2255                 shaderpass->skinframes[j] = R_SkinFrame_LoadExternal(layer->texturename[j], texflags, false, true);
2256         }
2257         return shaderpass;
2258 }
2259
2260 qboolean Mod_LoadTextureFromQ3Shader(mempool_t *mempool, const char *modelname, texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags, int defaultmaterialflags)
2261 {
2262         int texflagsmask, texflagsor;
2263         qboolean success = true;
2264         shader_t *shader;
2265         if (!name)
2266                 name = "";
2267         strlcpy(texture->name, name, sizeof(texture->name));
2268         texture->basealpha = 1.0f;
2269         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2270
2271         // allow disabling of picmip or compression by defaulttexflags
2272         texflagsmask = ~0;
2273         if(!(defaulttexflags & TEXF_PICMIP))
2274                 texflagsmask &= ~TEXF_PICMIP;
2275         if(!(defaulttexflags & TEXF_COMPRESS))
2276                 texflagsmask &= ~TEXF_COMPRESS;
2277         texflagsor = 0;
2278         if(defaulttexflags & TEXF_ISWORLD)
2279                 texflagsor |= TEXF_ISWORLD;
2280         if(defaulttexflags & TEXF_ISSPRITE)
2281                 texflagsor |= TEXF_ISSPRITE;
2282         // unless later loaded from the shader
2283         texture->offsetmapping = (mod_noshader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2284         texture->offsetscale = 1;
2285         texture->offsetbias = 0;
2286         texture->specularscalemod = 1;
2287         texture->specularpowermod = 1; 
2288         texture->rtlightambient = 0;
2289         texture->transparentsort = TRANSPARENTSORT_DISTANCE;
2290         // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
2291         // JUST GREP FOR "specularscalemod = 1".
2292
2293         if (shader)
2294         {
2295                 if (developer_loading.integer)
2296                         Con_Printf("%s: loaded shader for %s\n", modelname, name);
2297
2298                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2299                 {
2300                         texture->basematerialflags = MATERIALFLAG_SKY;
2301                         if (shader->skyboxname[0] && loadmodel)
2302                         {
2303                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2304                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2305                         }
2306                 }
2307                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2308                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2309                 else
2310                         texture->basematerialflags = MATERIALFLAG_WALL;
2311
2312                 if (shader->layers[0].alphatest)
2313                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2314                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2315                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2316                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2317                 {
2318                         texture->biaspolygonoffset += shader->biaspolygonoffset;
2319                         texture->biaspolygonfactor += shader->biaspolygonfactor;
2320                 }
2321                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2322                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2323                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2324                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2325                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2326                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2327                 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2328                         texture->basematerialflags |= MATERIALFLAG_CAMERA;
2329                 texture->customblendfunc[0] = GL_ONE;
2330                 texture->customblendfunc[1] = GL_ZERO;
2331                 texture->transparentsort = shader->transparentsort;
2332                 if (shader->numlayers > 0)
2333                 {
2334                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2335                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2336 /*
2337 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2338 * additive               GL_ONE GL_ONE
2339 additive weird         GL_ONE GL_SRC_ALPHA
2340 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2341 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2342 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2343 brighten               GL_DST_COLOR GL_ONE
2344 brighten               GL_ONE GL_SRC_COLOR
2345 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2346 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2347 * modulate               GL_DST_COLOR GL_ZERO
2348 * modulate               GL_ZERO GL_SRC_COLOR
2349 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2350 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2351 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2352 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2353 * no blend               GL_ONE GL_ZERO
2354 nothing                GL_ZERO GL_ONE
2355 */
2356                         // if not opaque, figure out what blendfunc to use
2357                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2358                         {
2359                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2360                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2361                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2362                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2363                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2364                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2365                                 else
2366                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2367                         }
2368                 }
2369                 if (!shader->lighting)
2370                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2371
2372                 // here be dragons: convert quake3 shaders to material
2373                 if (shader->numlayers > 0)
2374                 {
2375                         int i;
2376                         int terrainbackgroundlayer = -1;
2377                         int lightmaplayer = -1;
2378                         int alphagenspecularlayer = -1;
2379                         int rgbgenvertexlayer = -1;
2380                         int rgbgendiffuselayer = -1;
2381                         int materiallayer = -1;
2382                         int endofprelayers = 0;
2383                         int firstpostlayer = 0;
2384                         int shaderpassindex = 0;
2385                         for (i = 0; i < shader->numlayers; i++)
2386                         {
2387                                 if (shader->layers[i].texturename != NULL && !strcasecmp(shader->layers[i].texturename[0], "$lightmap"))
2388                                         lightmaplayer = i;
2389                                 if (shader->layers[i].rgbgen.rgbgen == Q3RGBGEN_VERTEX)
2390                                         rgbgenvertexlayer = i;
2391                                 if (shader->layers[i].rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE)
2392                                         rgbgendiffuselayer = i;
2393                                 if (shader->layers[i].alphagen.alphagen == Q3ALPHAGEN_LIGHTINGSPECULAR)
2394                                         alphagenspecularlayer = i;
2395                         }
2396                         if (shader->numlayers >= 2
2397                          && shader->layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2398                          && (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ZERO && !shader->layers[0].alphatest)
2399                          && ((shader->layers[1].blendfunc[0] == GL_SRC_ALPHA && shader->layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2400                                  || (shader->layers[1].blendfunc[0] == GL_ONE && shader->layers[1].blendfunc[1] == GL_ZERO && shader->layers[1].alphatest)))
2401                         {
2402                                 // terrain blend or certain other effects involving alphatest over a regular layer
2403                                 terrainbackgroundlayer = 0;
2404                                 materiallayer = 1;
2405                                 // terrain may be vertex lit (in which case both layers are rgbGen vertex) or lightmapped (in which ase the third layer is lightmap)
2406                                 firstpostlayer = lightmaplayer >= 0 ? lightmaplayer + 1 : materiallayer + 1;
2407                         }
2408                         else if (lightmaplayer == 0)
2409                         {
2410                                 // ordinary texture but with $lightmap before diffuse
2411                                 materiallayer = 1;
2412                                 firstpostlayer = lightmaplayer + 2;
2413                         }
2414                         else if (lightmaplayer >= 1)
2415                         {
2416                                 // ordinary texture - we don't properly apply lighting to the prelayers, but oh well...
2417                                 endofprelayers = lightmaplayer - 1;
2418                                 materiallayer = lightmaplayer - 1;
2419                                 firstpostlayer = lightmaplayer + 1;
2420                         }
2421                         else if (rgbgenvertexlayer >= 0)
2422                         {
2423                                 // map models with baked lighting
2424                                 materiallayer = rgbgenvertexlayer;
2425                                 endofprelayers = rgbgenvertexlayer;
2426                                 firstpostlayer = rgbgenvertexlayer + 1;
2427                                 // special case for rgbgen vertex if MATERIALFLAG_VERTEXCOLOR is expected on this material
2428                                 if (defaultmaterialflags & MATERIALFLAG_VERTEXCOLOR)
2429                                         texture->basematerialflags |= MATERIALFLAG_VERTEXCOLOR | MATERIALFLAG_ALPHAGEN_VERTEX;
2430                         }
2431                         else if (rgbgendiffuselayer >= 0)
2432                         {
2433                                 // entity models with dynamic lighting
2434                                 materiallayer = rgbgendiffuselayer;
2435                                 endofprelayers = rgbgendiffuselayer;
2436                                 firstpostlayer = rgbgendiffuselayer + 1;
2437                                 // player models often have specular as a pass after diffuse - we don't currently make use of that specular texture (would need to meld it into the skinframe)...
2438                                 if (alphagenspecularlayer >= 0)
2439                                         firstpostlayer = alphagenspecularlayer + 1;
2440                         }
2441                         else
2442                         {
2443                                 // special effects shaders - treat first as primary layer and do everything else as post
2444                                 endofprelayers = 0;
2445                                 materiallayer = 0;
2446                                 firstpostlayer = 1;
2447                         }
2448                         // convert the main material layer
2449                         // FIXME: if alphagenspecularlayer is used, we should pass a specular texture name to R_SkinFrame_LoadExternal and have it load that texture instead of the assumed name for _gloss texture
2450                         if (materiallayer >= 0)
2451                                 texture->materialshaderpass = texture->shaderpasses[shaderpassindex++] = Mod_CreateShaderPassFromQ3ShaderLayer(mempool, modelname, &shader->layers[materiallayer], materiallayer, (shader->layers[materiallayer].dptexflags & texflagsmask) | texflagsor, texture->name);
2452                         // convert the terrain background blend layer (if any)
2453                         if (terrainbackgroundlayer >= 0)
2454                                 texture->backgroundshaderpass = texture->shaderpasses[shaderpassindex++] = Mod_CreateShaderPassFromQ3ShaderLayer(mempool, modelname, &shader->layers[terrainbackgroundlayer], terrainbackgroundlayer, (shader->layers[terrainbackgroundlayer].dptexflags & texflagsmask) | texflagsor, texture->name);
2455                         // convert the prepass layers (if any)
2456                         texture->startpreshaderpass = shaderpassindex;
2457                         for (i = 0; i < endofprelayers; i++)
2458                                 texture->shaderpasses[shaderpassindex++] = Mod_CreateShaderPassFromQ3ShaderLayer(mempool, modelname, &shader->layers[i], i, (shader->layers[i].dptexflags & texflagsmask) | texflagsor, texture->name);
2459                         texture->endpreshaderpass = shaderpassindex;
2460                         texture->startpostshaderpass = shaderpassindex;
2461                         // convert the postpass layers (if any)
2462                         for (i = firstpostlayer; i < shader->numlayers; i++)
2463                                 texture->shaderpasses[shaderpassindex++] = Mod_CreateShaderPassFromQ3ShaderLayer(mempool, modelname, &shader->layers[i], i, (shader->layers[i].dptexflags & texflagsmask) | texflagsor, texture->name);
2464                         texture->startpostshaderpass = shaderpassindex;
2465                 }
2466
2467                 if (shader->dpshadow)
2468                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2469                 if (shader->dpnoshadow)
2470                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2471                 if (shader->dpnortlight)
2472                         texture->basematerialflags |= MATERIALFLAG_NORTLIGHT;
2473                 if (shader->vertexalpha)
2474                         texture->basematerialflags |= MATERIALFLAG_ALPHAGEN_VERTEX;
2475                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2476                 texture->reflectmin = shader->reflectmin;
2477                 texture->reflectmax = shader->reflectmax;
2478                 texture->refractfactor = shader->refractfactor;
2479                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2480                 texture->reflectfactor = shader->reflectfactor;
2481                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2482                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2483                 Vector2Copy(shader->r_water_waterscroll, texture->r_water_waterscroll);
2484                 texture->offsetmapping = shader->offsetmapping;
2485                 texture->offsetscale = shader->offsetscale;
2486                 texture->offsetbias = shader->offsetbias;
2487                 texture->specularscalemod = shader->specularscalemod;
2488                 texture->specularpowermod = shader->specularpowermod;
2489                 texture->rtlightambient = shader->rtlightambient;
2490                 texture->refractive_index = mod_q3shader_default_refractive_index.value;
2491                 if (shader->dpreflectcube[0])
2492                         texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2493
2494                 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2495                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2496                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents  = SUPERCONTENTS_LAVA         ;
2497                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents  = SUPERCONTENTS_SLIME        ;
2498                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents  = SUPERCONTENTS_WATER        ;
2499                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents  = 0                          ;
2500                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents  = SUPERCONTENTS_PLAYERCLIP   ;
2501                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents  = SUPERCONTENTS_MONSTERCLIP  ;
2502                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents  = SUPERCONTENTS_SKY          ;
2503
2504         //      if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW  ;
2505         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL   ;
2506         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2507         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->supercontents |= SUPERCONTENTS_DETAIL       ;
2508                 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->supercontents |= SUPERCONTENTS_DONOTENTER   ;
2509         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->supercontents |= SUPERCONTENTS_FOG          ;
2510                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents |= SUPERCONTENTS_LAVA         ;
2511         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER  ;
2512         //      if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->supercontents |= SUPERCONTENTS_METALSTEPS   ;
2513         //      if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->supercontents |= SUPERCONTENTS_NODAMAGE     ;
2514         //      if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->supercontents |= SUPERCONTENTS_NODLIGHT     ;
2515         //      if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->supercontents |= SUPERCONTENTS_NODRAW       ;
2516                 if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->supercontents |= SUPERCONTENTS_NODROP       ;
2517         //      if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->supercontents |= SUPERCONTENTS_NOIMPACT     ;
2518         //      if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP   ;
2519         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->supercontents |= SUPERCONTENTS_NOMARKS      ;
2520         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS    ;
2521                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents &=~SUPERCONTENTS_SOLID        ;
2522         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->supercontents |= SUPERCONTENTS_ORIGIN       ;
2523                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP   ;
2524                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents |= SUPERCONTENTS_SKY          ;
2525         //      if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->supercontents |= SUPERCONTENTS_SLICK        ;
2526                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents |= SUPERCONTENTS_SLIME        ;
2527         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL   ;
2528         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->supercontents |= SUPERCONTENTS_TRANS        ;
2529                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents |= SUPERCONTENTS_WATER        ;
2530         //      if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT   ;
2531         //      if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->supercontents |= SUPERCONTENTS_HINT         ;
2532         //      if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->supercontents |= SUPERCONTENTS_DUST         ;
2533                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents |= SUPERCONTENTS_BOTCLIP      | SUPERCONTENTS_MONSTERCLIP;
2534         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID    ;
2535         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL   ;
2536
2537                 texture->surfaceflags = shader->surfaceflags;
2538                 if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->surfaceflags |= Q3SURFACEFLAG_ALPHASHADOW  ;
2539         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->surfaceflags |= Q3SURFACEFLAG_AREAPORTAL   ;
2540         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->surfaceflags |= Q3SURFACEFLAG_CLUSTERPORTAL;
2541         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->surfaceflags |= Q3SURFACEFLAG_DETAIL       ;
2542         //      if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->surfaceflags |= Q3SURFACEFLAG_DONOTENTER   ;
2543         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->surfaceflags |= Q3SURFACEFLAG_FOG          ;
2544         //      if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->surfaceflags |= Q3SURFACEFLAG_LAVA         ;
2545                 if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->surfaceflags |= Q3SURFACEFLAG_LIGHTFILTER  ;
2546                 if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->surfaceflags |= Q3SURFACEFLAG_METALSTEPS   ;
2547                 if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->surfaceflags |= Q3SURFACEFLAG_NODAMAGE     ;
2548                 if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->surfaceflags |= Q3SURFACEFLAG_NODLIGHT     ;
2549                 if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->surfaceflags |= Q3SURFACEFLAG_NODRAW       ;
2550         //      if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->surfaceflags |= Q3SURFACEFLAG_NODROP       ;
2551                 if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->surfaceflags |= Q3SURFACEFLAG_NOIMPACT     ;
2552                 if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->surfaceflags |= Q3SURFACEFLAG_NOLIGHTMAP   ;
2553                 if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->surfaceflags |= Q3SURFACEFLAG_NOMARKS      ;
2554         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->surfaceflags |= Q3SURFACEFLAG_NOMIPMAPS    ;
2555                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->surfaceflags |= Q3SURFACEFLAG_NONSOLID     ;
2556         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->surfaceflags |= Q3SURFACEFLAG_ORIGIN       ;
2557         //      if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->surfaceflags |= Q3SURFACEFLAG_PLAYERCLIP   ;
2558                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->surfaceflags |= Q3SURFACEFLAG_SKY          ;
2559                 if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->surfaceflags |= Q3SURFACEFLAG_SLICK        ;
2560         //      if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->surfaceflags |= Q3SURFACEFLAG_SLIME        ;
2561         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->surfaceflags |= Q3SURFACEFLAG_STRUCTURAL   ;
2562         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->surfaceflags |= Q3SURFACEFLAG_TRANS        ;
2563         //      if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->surfaceflags |= Q3SURFACEFLAG_WATER        ;
2564                 if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->surfaceflags |= Q3SURFACEFLAG_POINTLIGHT   ;
2565                 if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->surfaceflags |= Q3SURFACEFLAG_HINT         ;
2566                 if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->surfaceflags |= Q3SURFACEFLAG_DUST         ;
2567         //      if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->surfaceflags |= Q3SURFACEFLAG_BOTCLIP      ;
2568         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->surfaceflags |= Q3SURFACEFLAG_LIGHTGRID    ;
2569         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->surfaceflags |= Q3SURFACEFLAG_ANTIPORTAL   ;
2570
2571                 if (shader->dpmeshcollisions)
2572                         texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2573                 if (shader->dpshaderkill && developer_extra.integer)
2574                         Con_DPrintf("^1%s:^7 killing shader ^3\"%s\" because of cvar\n", modelname, name);
2575         }
2576         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2577         {
2578                 if (developer_extra.integer)
2579                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", modelname, name);
2580                 texture->basematerialflags = defaultmaterialflags;
2581                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2582         }
2583         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2584         {
2585                 if (developer_extra.integer)
2586                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", modelname, name);
2587                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2588                 texture->supercontents = SUPERCONTENTS_SOLID;
2589         }
2590         else
2591         {
2592                 if (developer_extra.integer)
2593                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", modelname, texture->name);
2594                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2595                 {
2596                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2597                         texture->supercontents = SUPERCONTENTS_SOLID;
2598                 }
2599                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2600                 {
2601                         texture->basematerialflags = MATERIALFLAG_SKY;
2602                         texture->supercontents = SUPERCONTENTS_SKY;
2603                 }
2604                 else
2605                 {
2606                         texture->basematerialflags = defaultmaterialflags;
2607                         texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2608                 }
2609                 if(cls.state == ca_dedicated)
2610                 {
2611                         texture->materialshaderpass = NULL;
2612                         success = false;
2613                 }
2614                 else
2615                 {
2616                         skinframe_t *skinframe = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false, fallback);
2617                         if (skinframe)
2618                         {
2619                                 texture->materialshaderpass = texture->shaderpasses[0] = Mod_CreateShaderPass(mempool, skinframe);
2620                                 if (texture->materialshaderpass->skinframes[0]->hasalpha)
2621                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2622                                 if (texture->q2contents)
2623                                         texture->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(texture->q2contents);
2624                         }
2625                         else
2626                                 success = false;
2627                         if (!success && warnmissing)
2628                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", modelname, texture->name);
2629                 }
2630         }
2631         // init the animation variables
2632         texture->currentframe = texture;
2633         texture->currentmaterialflags = texture->basematerialflags;
2634         if (!texture->materialshaderpass)
2635                 texture->materialshaderpass = texture->shaderpasses[0] = Mod_CreateShaderPass(mempool, R_SkinFrame_LoadMissing());
2636         if (!texture->materialshaderpass->skinframes[0])
2637                 texture->materialshaderpass->skinframes[0] = R_SkinFrame_LoadMissing();
2638         texture->currentskinframe = texture->materialshaderpass ? texture->materialshaderpass->skinframes[0] : NULL;
2639         texture->backgroundcurrentskinframe = texture->backgroundshaderpass ? texture->backgroundshaderpass->skinframes[0] : NULL;
2640         return success;
2641 }
2642
2643 void Mod_LoadCustomMaterial(mempool_t *mempool, texture_t *texture, const char *name, int supercontents, int materialflags, skinframe_t *skinframe)
2644 {
2645         if (!(materialflags & (MATERIALFLAG_WALL | MATERIALFLAG_SKY)))
2646                 Con_DPrintf("^1Custom texture ^3\"%s\" does not have MATERIALFLAG_WALL set\n", texture->name);
2647
2648         strlcpy(texture->name, name, sizeof(texture->name));
2649         texture->basealpha = 1.0f;
2650         texture->basematerialflags = materialflags;
2651         texture->supercontents = supercontents;
2652
2653         texture->offsetmapping = (mod_noshader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2654         texture->offsetscale = 1;
2655         texture->offsetbias = 0;
2656         texture->specularscalemod = 1;
2657         texture->specularpowermod = 1;
2658         texture->rtlightambient = 0;
2659         texture->transparentsort = TRANSPARENTSORT_DISTANCE;
2660         // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
2661         // JUST GREP FOR "specularscalemod = 1".
2662
2663         if (developer_extra.integer)
2664                 Con_DPrintf("^1Custom texture ^3\"%s\"\n", texture->name);
2665         if (skinframe)
2666                 texture->materialshaderpass = texture->shaderpasses[0] = Mod_CreateShaderPass(mempool, skinframe);
2667
2668         // init the animation variables
2669         texture->currentmaterialflags = texture->basematerialflags;
2670         texture->currentframe = texture;
2671         texture->currentskinframe = skinframe;
2672         texture->backgroundcurrentskinframe = NULL;
2673 }
2674
2675 void Mod_UnloadCustomMaterial(texture_t *texture, qboolean purgeskins)
2676 {
2677         long unsigned int i, j;
2678         for (i = 0; i < sizeof(texture->shaderpasses) / sizeof(texture->shaderpasses[0]); i++)
2679         {
2680                 if (texture->shaderpasses[i])
2681                 {
2682                         if (purgeskins)
2683                                 for (j = 0; j < sizeof(texture->shaderpasses[i]->skinframes) / sizeof(skinframe_t *);j++)
2684                                         if (texture->shaderpasses[i]->skinframes[j] && texture->shaderpasses[i]->skinframes[j]->base)
2685                                                 R_SkinFrame_PurgeSkinFrame(texture->shaderpasses[i]->skinframes[j]);
2686                         Mem_Free(texture->shaderpasses[i]);
2687                         texture->shaderpasses[i] = NULL;
2688                 }
2689         }
2690         texture->materialshaderpass = NULL;
2691         texture->currentskinframe = NULL;
2692         texture->backgroundcurrentskinframe = NULL;
2693 }
2694
2695 skinfile_t *Mod_LoadSkinFiles(void)
2696 {
2697         int i, words, line, wordsoverflow;
2698         char *text;
2699         const char *data;
2700         skinfile_t *skinfile = NULL, *first = NULL;
2701         skinfileitem_t *skinfileitem;
2702         char word[10][MAX_QPATH];
2703         char vabuf[1024];
2704
2705 /*
2706 sample file:
2707 U_bodyBox,models/players/Legoman/BikerA2.tga
2708 U_RArm,models/players/Legoman/BikerA1.tga
2709 U_LArm,models/players/Legoman/BikerA1.tga
2710 U_armor,common/nodraw
2711 U_sword,common/nodraw
2712 U_shield,common/nodraw
2713 U_homb,common/nodraw
2714 U_backpack,common/nodraw
2715 U_colcha,common/nodraw
2716 tag_head,
2717 tag_weapon,
2718 tag_torso,
2719 */
2720         memset(word, 0, sizeof(word));
2721         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2722         {
2723                 // If it's the first file we parse
2724                 if (skinfile == NULL)
2725                 {
2726                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2727                         first = skinfile;
2728                 }
2729                 else
2730                 {
2731                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2732                         skinfile = skinfile->next;
2733                 }
2734                 skinfile->next = NULL;
2735
2736                 for(line = 0;;line++)
2737                 {
2738                         // parse line
2739                         if (!COM_ParseToken_QuakeC(&data, true))
2740                                 break;
2741                         if (!strcmp(com_token, "\n"))
2742                                 continue;
2743                         words = 0;
2744                         wordsoverflow = false;
2745                         do
2746                         {
2747                                 if (words < 10)
2748                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2749                                 else
2750                                         wordsoverflow = true;
2751                         }
2752                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2753                         if (wordsoverflow)
2754                         {
2755                                 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);
2756                                 continue;
2757                         }
2758                         // words is always >= 1
2759                         if (!strcmp(word[0], "replace"))
2760                         {
2761                                 if (words == 3)
2762                                 {
2763                                         if (developer_loading.integer)
2764                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2765                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2766                                         skinfileitem->next = skinfile->items;
2767                                         skinfile->items = skinfileitem;
2768                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2769                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2770                                 }
2771                                 else
2772                                         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]);
2773                         }
2774                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2775                         {
2776                                 // tag name, like "tag_weapon,"
2777                                 // not used for anything (not even in Quake3)
2778                         }
2779                         else if (words >= 2 && !strcmp(word[1], ","))
2780                         {
2781                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2782                                 if (developer_loading.integer)
2783                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2784                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2785                                 skinfileitem->next = skinfile->items;
2786                                 skinfile->items = skinfileitem;
2787                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2788                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2789                         }
2790                         else
2791                                 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);
2792                 }
2793                 Mem_Free(text);
2794         }
2795         if (i)
2796                 loadmodel->numskins = i;
2797         return first;
2798 }
2799
2800 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2801 {
2802         skinfile_t *next;
2803         skinfileitem_t *skinfileitem, *nextitem;
2804         for (;skinfile;skinfile = next)
2805         {
2806                 next = skinfile->next;
2807                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2808                 {
2809                         nextitem = skinfileitem->next;
2810                         Mem_Free(skinfileitem);
2811                 }
2812                 Mem_Free(skinfile);
2813         }
2814 }
2815
2816 int Mod_CountSkinFiles(skinfile_t *skinfile)
2817 {
2818         int i;
2819         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2820         return i;
2821 }
2822
2823 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2824 {
2825         int i;
2826         double isnap = 1.0 / snap;
2827         for (i = 0;i < numvertices*numcomponents;i++)
2828                 vertices[i] = floor(vertices[i]*isnap)*snap;
2829 }
2830
2831 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2832 {
2833         int i, outtriangles;
2834         float edgedir1[3], edgedir2[3], temp[3];
2835         // a degenerate triangle is one with no width (thickness, surface area)
2836         // these are characterized by having all 3 points colinear (along a line)
2837         // or having two points identical
2838         // the simplest check is to calculate the triangle's area
2839         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2840         {
2841                 // calculate first edge
2842                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2843                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2844                 CrossProduct(edgedir1, edgedir2, temp);
2845                 if (VectorLength2(temp) < 0.001f)
2846                         continue; // degenerate triangle (no area)
2847                 // valid triangle (has area)
2848                 VectorCopy(inelement3i, outelement3i);
2849                 outelement3i += 3;
2850                 outtriangles++;
2851         }
2852         return outtriangles;
2853 }
2854
2855 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2856 {
2857         int i, e;
2858         int firstvertex, lastvertex;
2859         if (numelements > 0 && elements)
2860         {
2861                 firstvertex = lastvertex = elements[0];
2862                 for (i = 1;i < numelements;i++)
2863                 {
2864                         e = elements[i];
2865                         firstvertex = min(firstvertex, e);
2866                         lastvertex = max(lastvertex, e);
2867                 }
2868         }
2869         else
2870                 firstvertex = lastvertex = 0;
2871         if (firstvertexpointer)
2872                 *firstvertexpointer = firstvertex;
2873         if (lastvertexpointer)
2874                 *lastvertexpointer = lastvertex;
2875 }
2876
2877 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2878 {
2879         // make an optimal set of texture-sorted batches to draw...
2880         int j, t;
2881         int *firstsurfacefortexture;
2882         int *numsurfacesfortexture;
2883         if (!mod->sortedmodelsurfaces)
2884                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2885         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2886         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2887         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2888         for (j = 0;j < mod->nummodelsurfaces;j++)
2889         {
2890                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2891                 if(!surface->texture)
2892                         continue;
2893                 t = (int)(surface->texture - mod->data_textures);
2894                 numsurfacesfortexture[t]++;
2895         }
2896         j = 0;
2897         for (t = 0;t < mod->num_textures;t++)
2898         {
2899                 firstsurfacefortexture[t] = j;
2900                 j += numsurfacesfortexture[t];
2901         }
2902         for (j = 0;j < mod->nummodelsurfaces;j++)
2903         {
2904                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2905                 if (!surface->texture)
2906                         continue;
2907                 t = (int)(surface->texture - mod->data_textures);
2908                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2909         }
2910         Mem_Free(firstsurfacefortexture);
2911         Mem_Free(numsurfacesfortexture);
2912 }
2913
2914 void Mod_BuildVBOs(void)
2915 {
2916         if(cls.state == ca_dedicated)
2917                 return;
2918
2919         if (!loadmodel->surfmesh.num_vertices)
2920                 return;
2921
2922         if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2923         {
2924                 int i;
2925                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2926                 {
2927                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2928                         {
2929                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2930                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2931                         }
2932                 }
2933         }
2934
2935         // upload short indices as a buffer
2936         if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
2937                 loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false, false, true);
2938
2939         // upload int indices as a buffer
2940         if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
2941                 loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false, false, false);
2942
2943         // only build a vbo if one has not already been created (this is important for brush models which load specially)
2944         // we put several vertex data streams in the same buffer
2945         if (!loadmodel->surfmesh.data_vertex3f_vertexbuffer)
2946         {
2947                 int size;
2948                 unsigned char *mem;
2949                 size = 0;
2950                 loadmodel->surfmesh.data_vertex3f_bufferoffset           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2951                 loadmodel->surfmesh.data_svector3f_bufferoffset          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2952                 loadmodel->surfmesh.data_tvector3f_bufferoffset          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2953                 loadmodel->surfmesh.data_normal3f_bufferoffset           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2954                 loadmodel->surfmesh.data_texcoordtexture2f_bufferoffset  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2955                 loadmodel->surfmesh.data_texcoordlightmap2f_bufferoffset = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2956                 loadmodel->surfmesh.data_lightmapcolor4f_bufferoffset    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2957                 loadmodel->surfmesh.data_skeletalindex4ub_bufferoffset   = size;if (loadmodel->surfmesh.data_skeletalindex4ub  ) size += loadmodel->surfmesh.num_vertices * sizeof(unsigned char[4]);
2958                 loadmodel->surfmesh.data_skeletalweight4ub_bufferoffset  = size;if (loadmodel->surfmesh.data_skeletalweight4ub ) size += loadmodel->surfmesh.num_vertices * sizeof(unsigned char[4]);
2959                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2960                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.data_vertex3f_bufferoffset          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2961                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.data_svector3f_bufferoffset         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2962                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.data_tvector3f_bufferoffset         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2963                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.data_normal3f_bufferoffset          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2964                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.data_texcoordtexture2f_bufferoffset , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2965                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.data_texcoordlightmap2f_bufferoffset, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2966                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.data_lightmapcolor4f_bufferoffset   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2967                 if (loadmodel->surfmesh.data_skeletalindex4ub  ) memcpy(mem + loadmodel->surfmesh.data_skeletalindex4ub_bufferoffset  , loadmodel->surfmesh.data_skeletalindex4ub  , loadmodel->surfmesh.num_vertices * sizeof(unsigned char[4]));
2968                 if (loadmodel->surfmesh.data_skeletalweight4ub ) memcpy(mem + loadmodel->surfmesh.data_skeletalweight4ub_bufferoffset , loadmodel->surfmesh.data_skeletalweight4ub , loadmodel->surfmesh.num_vertices * sizeof(unsigned char[4]));
2969                 loadmodel->surfmesh.data_vertex3f_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false, false, false);
2970                 loadmodel->surfmesh.data_svector3f_vertexbuffer = loadmodel->surfmesh.data_svector3f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2971                 loadmodel->surfmesh.data_tvector3f_vertexbuffer = loadmodel->surfmesh.data_tvector3f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2972                 loadmodel->surfmesh.data_normal3f_vertexbuffer = loadmodel->surfmesh.data_normal3f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2973                 loadmodel->surfmesh.data_texcoordtexture2f_vertexbuffer = loadmodel->surfmesh.data_texcoordtexture2f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2974                 loadmodel->surfmesh.data_texcoordlightmap2f_vertexbuffer = loadmodel->surfmesh.data_texcoordlightmap2f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2975                 loadmodel->surfmesh.data_lightmapcolor4f_vertexbuffer = loadmodel->surfmesh.data_lightmapcolor4f ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2976                 loadmodel->surfmesh.data_skeletalindex4ub_vertexbuffer = loadmodel->surfmesh.data_skeletalindex4ub ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2977                 loadmodel->surfmesh.data_skeletalweight4ub_vertexbuffer = loadmodel->surfmesh.data_skeletalweight4ub ? loadmodel->surfmesh.data_vertex3f_vertexbuffer : NULL;
2978                 Mem_Free(mem);
2979         }
2980 }
2981
2982 extern cvar_t mod_obj_orientation;
2983 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2984 {
2985         int submodelindex, vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2986         int a, b, c;
2987         const char *texname;
2988         const int *e;
2989         const float *v, *vn, *vt;
2990         size_t l;
2991         size_t outbufferpos = 0;
2992         size_t outbuffermax = 0x100000;
2993         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2994         const msurface_t *surface;
2995         const int maxtextures = 256;
2996         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2997         dp_model_t *submodel;
2998
2999         // construct the mtllib file
3000         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
3001         if (l > 0)
3002                 outbufferpos += l;
3003         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3004         {
3005                 countsurfaces++;
3006                 countvertices += surface->num_vertices;
3007                 countfaces += surface->num_triangles;
3008                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
3009                 for (textureindex = 0;textureindex < counttextures;textureindex++)
3010                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
3011                                 break;
3012                 if (textureindex < counttextures)
3013                         continue; // already wrote this material entry
3014                 if (textureindex >= maxtextures)
3015                         continue; // just a precaution
3016                 textureindex = counttextures++;
3017                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
3018                 if (outbufferpos >= outbuffermax >> 1)
3019                 {
3020                         outbuffermax *= 2;
3021                         oldbuffer = outbuffer;
3022                         outbuffer = (char *) Z_Malloc(outbuffermax);
3023                         memcpy(outbuffer, oldbuffer, outbufferpos);
3024                         Z_Free(oldbuffer);
3025                 }
3026                 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");
3027                 if (l > 0)
3028                         outbufferpos += l;
3029         }
3030
3031         // write the mtllib file
3032         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
3033
3034         // construct the obj file
3035         outbufferpos = 0;
3036         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);
3037         if (l > 0)
3038                 outbufferpos += l;
3039
3040         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)
3041         {
3042                 if (outbufferpos >= outbuffermax >> 1)
3043                 {
3044                         outbuffermax *= 2;
3045                         oldbuffer = outbuffer;
3046                         outbuffer = (char *) Z_Malloc(outbuffermax);
3047                         memcpy(outbuffer, oldbuffer, outbufferpos);
3048                         Z_Free(oldbuffer);
3049                 }
3050                 if(mod_obj_orientation.integer)
3051                         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]);
3052                 else
3053                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1-vt[1]);
3054                 if (l > 0)
3055                         outbufferpos += l;
3056         }
3057
3058         for (submodelindex = 0;submodelindex < max(1, model->brush.numsubmodels);submodelindex++)
3059         {
3060                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "o %i\n", submodelindex);
3061                 if (l > 0)
3062                         outbufferpos += l;
3063                 submodel = model->brush.numsubmodels ? model->brush.submodels[submodelindex] : model;
3064                 for (surfaceindex = 0;surfaceindex < submodel->nummodelsurfaces;surfaceindex++)
3065                 {
3066                         surface = model->data_surfaces + submodel->sortedmodelsurfaces[surfaceindex];
3067                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
3068                         if (l > 0)
3069                                 outbufferpos += l;
3070                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3071                         {
3072                                 if (outbufferpos >= outbuffermax >> 1)
3073                                 {
3074                                         outbuffermax *= 2;
3075                                         oldbuffer = outbuffer;
3076                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3077                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3078                                         Z_Free(oldbuffer);
3079                                 }
3080                                 a = e[0]+1;
3081                                 b = e[1]+1;
3082                                 c = e[2]+1;
3083                                 if(mod_obj_orientation.integer)
3084                                         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);
3085                                 else
3086                                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,c,c,c,b,b,b);
3087                                 if (l > 0)
3088                                         outbufferpos += l;
3089                         }
3090                 }
3091         }
3092
3093         // write the obj file
3094         FS_WriteFile(filename, outbuffer, outbufferpos);
3095
3096         // clean up
3097         Z_Free(outbuffer);
3098         Z_Free(texturenames);
3099
3100         // print some stats
3101         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
3102 }
3103
3104 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
3105 {
3106         int countnodes = 0, counttriangles = 0, countframes = 0;
3107         int surfaceindex;
3108         int triangleindex;
3109         int transformindex;
3110         int poseindex;
3111         int cornerindex;
3112         const int *e;
3113         size_t l;
3114         size_t outbufferpos = 0;
3115         size_t outbuffermax = 0x100000;
3116         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
3117         const msurface_t *surface;
3118         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
3119         if (l > 0)
3120                 outbufferpos += l;
3121         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3122         {
3123                 if (outbufferpos >= outbuffermax >> 1)
3124                 {
3125                         outbuffermax *= 2;
3126                         oldbuffer = outbuffer;
3127                         outbuffer = (char *) Z_Malloc(outbuffermax);
3128                         memcpy(outbuffer, oldbuffer, outbufferpos);
3129                         Z_Free(oldbuffer);
3130                 }
3131                 countnodes++;
3132                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
3133                 if (l > 0)
3134                         outbufferpos += l;
3135         }
3136         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
3137         if (l > 0)
3138                 outbufferpos += l;
3139         for (poseindex = 0;poseindex < numposes;poseindex++)
3140         {
3141                 countframes++;
3142                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
3143                 if (l > 0)
3144                         outbufferpos += l;
3145                 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3146                 {
3147                         float angles[3];
3148                         float mtest[4][3];
3149                         matrix4x4_t posematrix;
3150                         if (outbufferpos >= outbuffermax >> 1)
3151                         {
3152                                 outbuffermax *= 2;
3153                                 oldbuffer = outbuffer;
3154                                 outbuffer = (char *) Z_Malloc(outbuffermax);
3155                                 memcpy(outbuffer, oldbuffer, outbufferpos);
3156                                 Z_Free(oldbuffer);
3157                         }
3158
3159                         // strangely the smd angles are for a transposed matrix, so we
3160                         // have to generate a transposed matrix, then convert that...
3161                         Matrix4x4_FromBonePose7s(&posematrix, model->num_posescale, model->data_poses7s + 7*(model->num_bones * poseindex + transformindex));
3162                         Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
3163                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
3164                         if (angles[0] >= 180) angles[0] -= 360;
3165                         if (angles[1] >= 180) angles[1] -= 360;
3166                         if (angles[2] >= 180) angles[2] -= 360;
3167
3168 #if 0
3169 {
3170                         float a = DEG2RAD(angles[ROLL]);
3171                         float b = DEG2RAD(angles[PITCH]);
3172                         float c = DEG2RAD(angles[YAW]);
3173                         float cy, sy, cp, sp, cr, sr;
3174                         float test[4][3];
3175                         // smd matrix construction, for comparing
3176                         sy = sin(c);
3177                         cy = cos(c);
3178                         sp = sin(b);
3179                         cp = cos(b);
3180                         sr = sin(a);
3181                         cr = cos(a);
3182
3183                         test[0][0] = cp*cy;
3184                         test[0][1] = cp*sy;
3185                         test[0][2] = -sp;
3186                         test[1][0] = sr*sp*cy+cr*-sy;
3187                         test[1][1] = sr*sp*sy+cr*cy;
3188                         test[1][2] = sr*cp;
3189                         test[2][0] = (cr*sp*cy+-sr*-sy);
3190                         test[2][1] = (cr*sp*sy+-sr*cy);
3191                         test[2][2] = cr*cp;
3192                         test[3][0] = pose[9];
3193                         test[3][1] = pose[10];
3194                         test[3][2] = pose[11];
3195 }
3196 #endif
3197                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, mtest[3][0], mtest[3][1], mtest[3][2], DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
3198                         if (l > 0)
3199                                 outbufferpos += l;
3200                 }
3201         }
3202         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3203         if (l > 0)
3204                 outbufferpos += l;
3205         if (writetriangles)
3206         {
3207                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
3208                 if (l > 0)
3209                         outbufferpos += l;
3210                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3211                 {
3212                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3213                         {
3214                                 counttriangles++;
3215                                 if (outbufferpos >= outbuffermax >> 1)
3216                                 {
3217                                         outbuffermax *= 2;
3218                                         oldbuffer = outbuffer;
3219                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3220                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3221                                         Z_Free(oldbuffer);
3222                                 }
3223                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
3224                                 if (l > 0)
3225                                         outbufferpos += l;
3226                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
3227                                 {
3228                                         const int index = e[2-cornerindex];
3229                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
3230                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
3231                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
3232                                         const int b = model->surfmesh.blends[index];
3233                                         if (b < model->num_bones)
3234                                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , b, v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
3235                                         else
3236                                         {
3237                                                 const blendweights_t *w = model->surfmesh.data_blendweights + b - model->num_bones;
3238                                                 const unsigned char *wi = w->index;
3239                                                 const unsigned char *wf = w->influence;
3240                                             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]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f, wi[3], wf[3]/255.0f);
3241                                                 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]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f);
3242                                                 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]/255.0f, wi[1], wf[1]/255.0f);
3243                                                 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]);
3244                                         }
3245                                         if (l > 0)
3246                                                 outbufferpos += l;
3247                                 }
3248                         }
3249                 }
3250                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3251                 if (l > 0)
3252                         outbufferpos += l;
3253         }
3254
3255         FS_WriteFile(filename, outbuffer, outbufferpos);
3256         Z_Free(outbuffer);
3257
3258         Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
3259 }
3260
3261 /*
3262 ================
3263 Mod_Decompile_f
3264
3265 decompiles a model to editable files
3266 ================
3267 */
3268 static void Mod_Decompile_f(cmd_state_t *cmd)
3269 {
3270         int i, j, k, l, first, count;
3271         dp_model_t *mod;
3272         char inname[MAX_QPATH];
3273         char outname[MAX_QPATH];
3274         char mtlname[MAX_QPATH];
3275         char basename[MAX_QPATH];
3276         char animname[MAX_QPATH];
3277         char animname2[MAX_QPATH];
3278         char zymtextbuffer[16384];
3279         char dpmtextbuffer[16384];
3280         char framegroupstextbuffer[16384];
3281         int zymtextsize = 0;
3282         int dpmtextsize = 0;
3283         int framegroupstextsize = 0;
3284         char vabuf[1024];
3285
3286         if (Cmd_Argc(cmd) != 2)
3287         {
3288                 Con_Print("usage: modeldecompile <filename>\n");
3289                 return;
3290         }
3291
3292         strlcpy(inname, Cmd_Argv(cmd, 1), sizeof(inname));
3293         FS_StripExtension(inname, basename, sizeof(basename));
3294
3295         mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
3296         if (!mod)
3297         {
3298                 Con_Print("No such model\n");
3299                 return;
3300         }
3301         if (mod->brush.submodel)
3302         {
3303                 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
3304                 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
3305                 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
3306                 outname[0] = 0;
3307         }
3308         if (!mod->surfmesh.num_triangles)
3309         {
3310                 Con_Print("Empty model (or sprite)\n");
3311                 return;
3312         }
3313
3314         // export OBJ if possible (not on sprites)
3315         if (mod->surfmesh.num_triangles)
3316         {
3317                 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
3318                 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
3319                 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
3320         }
3321
3322         // export SMD if possible (only for skeletal models)
3323         if (mod->surfmesh.num_triangles && mod->num_bones)
3324         {
3325                 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
3326                 Mod_Decompile_SMD(mod, outname, 0, 1, true);
3327                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
3328                 if (l > 0) zymtextsize += l;
3329                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
3330                 if (l > 0) dpmtextsize += l;
3331                 for (i = 0;i < mod->numframes;i = j)
3332                 {
3333                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3334                         first = mod->animscenes[i].firstframe;
3335                         if (mod->animscenes[i].framecount > 1)
3336                         {
3337                                 // framegroup anim
3338                                 count = mod->animscenes[i].framecount;
3339                                 j = i + 1;
3340                         }
3341                         else
3342                         {
3343                                 // individual frame
3344                                 // check for additional frames with same name
3345                                 for (l = 0, k = (int)strlen(animname);animname[l];l++)
3346                                         if(animname[l] < '0' || animname[l] > '9')
3347                                                 k = l + 1;
3348                                 if(k > 0 && animname[k-1] == '_')
3349                                         --k;
3350                                 animname[k] = 0;
3351                                 count = mod->num_poses - first;
3352                                 for (j = i + 1;j < mod->numframes;j++)
3353                                 {
3354                                         strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
3355