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