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