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