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