9c7e2c386fdd1d2f43138ede76c11e5698dbadfa
[divverent/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);
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 = 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 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1536 {
1537         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1538         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1539         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1540         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1541         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1542         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1543         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1544         return Q3WAVEFUNC_NONE;
1545 }
1546
1547 void Mod_FreeQ3Shaders(void)
1548 {
1549         Mem_FreePool(&q3shaders_mem);
1550 }
1551
1552 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1553 {
1554         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1555         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1556         q3shader_hash_entry_t* lastEntry = NULL;
1557         while (entry != NULL)
1558         {
1559                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1560                 {
1561                         unsigned char *start, *end, *start2;
1562                         start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1563                         end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1564                         start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1565                         if(memcmp(start, start2, end - start))
1566                                 Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1567                         else
1568                                 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1569                         return;
1570                 }
1571                 lastEntry = entry;
1572                 entry = entry->chain;
1573         }
1574         if (entry == NULL)
1575         {
1576                 if (lastEntry->shader.name[0] != 0)
1577                 {
1578                         /* Add to chain */
1579                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1580                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1581
1582                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1583                         lastEntry->chain = newEntry;
1584                         newEntry->chain = NULL;
1585                         lastEntry = newEntry;
1586                 }
1587                 /* else: head of chain, in hash entry array */
1588                 entry = lastEntry;
1589         }
1590         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1591 }
1592
1593 extern cvar_t r_picmipworld;
1594 extern cvar_t mod_q3shader_default_offsetmapping;
1595 void Mod_LoadQ3Shaders(void)
1596 {
1597         int j;
1598         int fileindex;
1599         fssearch_t *search;
1600         char *f;
1601         const char *text;
1602         q3shaderinfo_t shader;
1603         q3shaderinfo_layer_t *layer;
1604         int numparameters;
1605         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1606         char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1607         unsigned long custsurfaceparms[256]; 
1608         int numcustsurfaceparms;
1609
1610         Mod_FreeQ3Shaders();
1611
1612         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1613         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1614                 sizeof (q3shader_data_t));
1615         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1616                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1617         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1618                 q3shaders_mem, sizeof (char**), 256);
1619
1620         // parse custinfoparms.txt
1621         numcustsurfaceparms = 0;
1622         if (text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL))
1623         {
1624                 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1625                         Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1626                 else
1627                 {
1628                         while (COM_ParseToken_QuakeC(&text, false))
1629                                 if (!strcasecmp(com_token, "}"))
1630                                         break;
1631                         // custom surfaceflags section
1632                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1633                                 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1634                         else
1635                         {
1636                                 while(COM_ParseToken_QuakeC(&text, false))
1637                                 {
1638                                         if (!strcasecmp(com_token, "}"))
1639                                                 break;  
1640                                         // register surfaceflag
1641                                         if (numcustsurfaceparms >= 256)
1642                                         {
1643                                                 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1644                                                 break;
1645                                         }
1646                                         // name
1647                                         j = strlen(com_token)+1;
1648                                         custsurfaceparmnames[numcustsurfaceparms] = (char *)Mem_Alloc(tempmempool, j);
1649                                         strlcpy(custsurfaceparmnames[numcustsurfaceparms], com_token, j+1);
1650                                         // value
1651                                         if (COM_ParseToken_QuakeC(&text, false))
1652                                                 custsurfaceparms[numcustsurfaceparms] = strtol(com_token, NULL, 0);
1653                                         else
1654                                                 custsurfaceparms[numcustsurfaceparms] = 0;
1655                                         numcustsurfaceparms++;
1656                                 }
1657                         }
1658                 }
1659                 Mem_Free(f);
1660         }
1661
1662         // parse shaders
1663         search = FS_Search("scripts/*.shader", true, false);
1664         if (!search)
1665                 return;
1666         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1667         {
1668                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1669                 if (!f)
1670                         continue;
1671                 while (COM_ParseToken_QuakeC(&text, false))
1672                 {
1673                         memset (&shader, 0, sizeof(shader));
1674                         shader.reflectmin = 0;
1675                         shader.reflectmax = 1;
1676                         shader.refractfactor = 1;
1677                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1678                         shader.reflectfactor = 1;
1679                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1680                         shader.r_water_wateralpha = 1;
1681                         shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1682                         shader.offsetscale = 1;
1683                         shader.specularscalemod = 1;
1684                         shader.specularpowermod = 1;
1685
1686                         strlcpy(shader.name, com_token, sizeof(shader.name));
1687                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1688                         {
1689                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1690                                 break;
1691                         }
1692                         while (COM_ParseToken_QuakeC(&text, false))
1693                         {
1694                                 if (!strcasecmp(com_token, "}"))
1695                                         break;
1696                                 if (!strcasecmp(com_token, "{"))
1697                                 {
1698                                         static q3shaderinfo_layer_t dummy;
1699                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1700                                         {
1701                                                 layer = shader.layers + shader.numlayers++;
1702                                         }
1703                                         else
1704                                         {
1705                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1706                                                 memset(&dummy, 0, sizeof(dummy));
1707                                                 layer = &dummy;
1708                                         }
1709                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1710                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1711                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1712                                         layer->blendfunc[0] = GL_ONE;
1713                                         layer->blendfunc[1] = GL_ZERO;
1714                                         while (COM_ParseToken_QuakeC(&text, false))
1715                                         {
1716                                                 if (!strcasecmp(com_token, "}"))
1717                                                         break;
1718                                                 if (!strcasecmp(com_token, "\n"))
1719                                                         continue;
1720                                                 numparameters = 0;
1721                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1722                                                 {
1723                                                         if (j < TEXTURE_MAXFRAMES + 4)
1724                                                         {
1725                                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1726                                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1727                                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1728                                                                 else
1729                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1730                                                                 numparameters = j + 1;
1731                                                         }
1732                                                         if (!COM_ParseToken_QuakeC(&text, true))
1733                                                                 break;
1734                                                 }
1735                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1736                                                 //      parameter[j][0] = 0;
1737                                                 if (developer_insane.integer)
1738                                                 {
1739                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1740                                                         for (j = 0;j < numparameters;j++)
1741                                                                 Con_DPrintf(" %s", parameter[j]);
1742                                                         Con_DPrint("\n");
1743                                                 }
1744                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1745                                                 {
1746                                                         if (numparameters == 2)
1747                                                         {
1748                                                                 if (!strcasecmp(parameter[1], "add"))
1749                                                                 {
1750                                                                         layer->blendfunc[0] = GL_ONE;
1751                                                                         layer->blendfunc[1] = GL_ONE;
1752                                                                 }
1753                                                                 else if (!strcasecmp(parameter[1], "filter"))
1754                                                                 {
1755                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1756                                                                         layer->blendfunc[1] = GL_ZERO;
1757                                                                 }
1758                                                                 else if (!strcasecmp(parameter[1], "blend"))
1759                                                                 {
1760                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1761                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1762                                                                 }
1763                                                         }
1764                                                         else if (numparameters == 3)
1765                                                         {
1766                                                                 int k;
1767                                                                 for (k = 0;k < 2;k++)
1768                                                                 {
1769                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1770                                                                                 layer->blendfunc[k] = GL_ONE;
1771                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1772                                                                                 layer->blendfunc[k] = GL_ZERO;
1773                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1774                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1775                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1776                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1777                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1778                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1779                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1780                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1781                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1782                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1783                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1784                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1785                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1786                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1787                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1788                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1789                                                                         else
1790                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1791                                                                 }
1792                                                         }
1793                                                 }
1794                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1795                                                         layer->alphatest = true;
1796                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1797                                                 {
1798                                                         if (!strcasecmp(parameter[0], "clampmap"))
1799                                                                 layer->clampmap = true;
1800                                                         layer->numframes = 1;
1801                                                         layer->framerate = 1;
1802                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1803                                                                 &q3shader_data->char_ptrs);
1804                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1805                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1806                                                                 shader.lighting = true;
1807                                                 }
1808                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1809                                                 {
1810                                                         int i;
1811                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1812                                                         layer->framerate = atof(parameter[1]);
1813                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1814                                                         for (i = 0;i < layer->numframes;i++)
1815                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1816                                                 }
1817                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1818                                                 {
1819                                                         int i;
1820                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1821                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1822                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1823                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1824                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1825                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1826                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1827                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1828                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1829                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1830                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1831                                                         else if (!strcasecmp(parameter[1], "wave"))
1832                                                         {
1833                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1834                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1835                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1836                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1837                                                         }
1838                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1839                                                 }
1840                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1841                                                 {
1842                                                         int i;
1843                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1844                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1845                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1846                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1847                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1848                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1849                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1850                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1851                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1852                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1853                                                         else if (!strcasecmp(parameter[1], "wave"))
1854                                                         {
1855                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1856                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1857                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1858                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1859                                                         }
1860                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1861                                                 }
1862                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1863                                                 {
1864                                                         int i;
1865                                                         // observed values: tcgen environment
1866                                                         // no other values have been observed in real shaders
1867                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1868                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1869                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1870                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1871                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1872                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1873                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1874                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1875                                                 }
1876                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1877                                                 {
1878                                                         int i, tcmodindex;
1879                                                         // observed values:
1880                                                         // tcmod rotate #
1881                                                         // tcmod scale # #
1882                                                         // tcmod scroll # #
1883                                                         // tcmod stretch sin # # # #
1884                                                         // tcmod stretch triangle # # # #
1885                                                         // tcmod transform # # # # # #
1886                                                         // tcmod turb # # # #
1887                                                         // tcmod turb sin # # # #  (this is bogus)
1888                                                         // no other values have been observed in real shaders
1889                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1890                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1891                                                                         break;
1892                                                         if (tcmodindex < Q3MAXTCMODS)
1893                                                         {
1894                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1895                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1896                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1897                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1898                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1899                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1900                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1901                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1902                                                                 {
1903                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1904                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1905                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1906                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1907                                                                 }
1908                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1909                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1910                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1911                                                         }
1912                                                         else
1913                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1914                                                 }
1915                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1916                                                 if (!strcasecmp(com_token, "}"))
1917                                                         break;
1918                                         }
1919                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1920                                                 shader.lighting = true;
1921                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1922                                         {
1923                                                 if (layer == shader.layers + 0)
1924                                                 {
1925                                                         // vertex controlled transparency
1926                                                         shader.vertexalpha = true;
1927                                                 }
1928                                                 else
1929                                                 {
1930                                                         // multilayer terrain shader or similar
1931                                                         shader.textureblendalpha = true;
1932                                                 }
1933                                         }
1934                                         layer->texflags = TEXF_ALPHA;
1935                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1936                                                 layer->texflags |= TEXF_MIPMAP;
1937                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1938                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1939                                         if (layer->clampmap)
1940                                                 layer->texflags |= TEXF_CLAMP;
1941                                         continue;
1942                                 }
1943                                 numparameters = 0;
1944                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1945                                 {
1946                                         if (j < TEXTURE_MAXFRAMES + 4)
1947                                         {
1948                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1949                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1950                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1951                                                 else
1952                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1953                                                 numparameters = j + 1;
1954                                         }
1955                                         if (!COM_ParseToken_QuakeC(&text, true))
1956                                                 break;
1957                                 }
1958                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1959                                 //      parameter[j][0] = 0;
1960                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1961                                         break;
1962                                 if (developer_insane.integer)
1963                                 {
1964                                         Con_DPrintf("%s: ", shader.name);
1965                                         for (j = 0;j < numparameters;j++)
1966                                                 Con_DPrintf(" %s", parameter[j]);
1967                                         Con_DPrint("\n");
1968                                 }
1969                                 if (numparameters < 1)
1970                                         continue;
1971                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1972                                 {
1973                                         if (!strcasecmp(parameter[1], "alphashadow"))
1974                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1975                                         else if (!strcasecmp(parameter[1], "areaportal"))
1976                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1977                                         else if (!strcasecmp(parameter[1], "botclip"))
1978                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1979                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1980                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1981                                         else if (!strcasecmp(parameter[1], "detail"))
1982                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1983                                         else if (!strcasecmp(parameter[1], "donotenter"))
1984                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1985                                         else if (!strcasecmp(parameter[1], "dust"))
1986                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1987                                         else if (!strcasecmp(parameter[1], "hint"))
1988                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1989                                         else if (!strcasecmp(parameter[1], "fog"))
1990                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1991                                         else if (!strcasecmp(parameter[1], "lava"))
1992                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1993                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1994                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1995                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1996                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1997                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1998                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1999                                         else if (!strcasecmp(parameter[1], "nodamage"))
2000                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
2001                                         else if (!strcasecmp(parameter[1], "nodlight"))
2002                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
2003                                         else if (!strcasecmp(parameter[1], "nodraw"))
2004                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
2005                                         else if (!strcasecmp(parameter[1], "nodrop"))
2006                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
2007                                         else if (!strcasecmp(parameter[1], "noimpact"))
2008                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
2009                                         else if (!strcasecmp(parameter[1], "nolightmap"))
2010                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
2011                                         else if (!strcasecmp(parameter[1], "nomarks"))
2012                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
2013                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
2014                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2015                                         else if (!strcasecmp(parameter[1], "nonsolid"))
2016                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
2017                                         else if (!strcasecmp(parameter[1], "origin"))
2018                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
2019                                         else if (!strcasecmp(parameter[1], "playerclip"))
2020                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
2021                                         else if (!strcasecmp(parameter[1], "sky"))
2022                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2023                                         else if (!strcasecmp(parameter[1], "slick"))
2024                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
2025                                         else if (!strcasecmp(parameter[1], "slime"))
2026                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
2027                                         else if (!strcasecmp(parameter[1], "structural"))
2028                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
2029                                         else if (!strcasecmp(parameter[1], "trans"))
2030                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
2031                                         else if (!strcasecmp(parameter[1], "water"))
2032                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
2033                                         else if (!strcasecmp(parameter[1], "pointlight"))
2034                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
2035                                         else if (!strcasecmp(parameter[1], "antiportal"))
2036                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
2037                                         else
2038                                         {
2039                                                 // try custom surfaceparms
2040                                                 for (j = 0; j < numcustsurfaceparms; j++)
2041                                                 {
2042                                                         if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
2043                                                         {
2044                                                                 shader.surfaceparms |= custsurfaceparms[j];
2045                                                                 break;
2046                                                         }
2047                                                 }
2048                                                 // failed all
2049                                                 if (j == numcustsurfaceparms)
2050                                                         Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
2051                                         }
2052                                 }
2053                                 else if (!strcasecmp(parameter[0], "dpshadow"))
2054                                         shader.dpshadow = true;
2055                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
2056                                         shader.dpnoshadow = true;
2057                                 else if (!strcasecmp(parameter[0], "dpreflectcube"))
2058                                         strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
2059                                 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
2060                                         shader.dpmeshcollisions = true;
2061                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2062                                 {
2063                                         // some q3 skies don't have the sky parm set
2064                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2065                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2066                                 }
2067                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2068                                 {
2069                                         // some q3 skies don't have the sky parm set
2070                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2071                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2072                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2073                                 }
2074                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2075                                 {
2076                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2077                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2078                                 }
2079                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
2080                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2081                                 else if (!strcasecmp(parameter[0], "nopicmip"))
2082                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2083                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
2084                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2085                                 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2086                                 {
2087                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2088                                         shader.refractfactor = atof(parameter[1]);
2089                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2090                                 }
2091                                 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2092                                 {
2093                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2094                                         shader.reflectfactor = atof(parameter[1]);
2095                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2096                                 }
2097                                 else if (!strcasecmp(parameter[0], "dpcamera"))
2098                                 {
2099                                         shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2100                                 }
2101                                 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2102                                 {
2103                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2104                                         shader.reflectmin = atof(parameter[1]);
2105                                         shader.reflectmax = atof(parameter[2]);
2106                                         shader.refractfactor = atof(parameter[3]);
2107                                         shader.reflectfactor = atof(parameter[4]);
2108                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2109                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2110                                         shader.r_water_wateralpha = atof(parameter[11]);
2111                                 }
2112                                 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2113                                 {
2114                                         shader.specularscalemod = atof(parameter[1]);
2115                                 }
2116                                 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2117                                 {
2118                                         shader.specularpowermod = atof(parameter[1]);
2119                                 }
2120                                 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 3)
2121                                 {
2122                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2123                                                 shader.offsetmapping = OFFSETMAPPING_OFF;
2124                                         else if (!strcasecmp(parameter[1], "default"))
2125                                                 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2126                                         else if (!strcasecmp(parameter[1], "linear"))
2127                                                 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2128                                         else if (!strcasecmp(parameter[1], "relief"))
2129                                                 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2130                                         shader.offsetscale = atof(parameter[2]);
2131                                 }
2132                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2133                                 {
2134                                         int i, deformindex;
2135                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2136                                                 if (!shader.deforms[deformindex].deform)
2137                                                         break;
2138                                         if (deformindex < Q3MAXDEFORMS)
2139                                         {
2140                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2141                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2142                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2143                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2144                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2145                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2146                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2147                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2148                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2149                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2150                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2151                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2152                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2153                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2154                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2155                                                 else if (!strcasecmp(parameter[1], "wave"            ))
2156                                                 {
2157                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2158                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2159                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2160                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2161                                                 }
2162                                                 else if (!strcasecmp(parameter[1], "move"            ))
2163                                                 {
2164                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2165                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2166                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2167                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2168                                                 }
2169                                         }
2170                                 }
2171                         }
2172                         // pick the primary layer to render with
2173                         if (shader.numlayers)
2174                         {
2175                                 shader.backgroundlayer = -1;
2176                                 shader.primarylayer = 0;
2177                                 // if lightmap comes first this is definitely an ordinary texture
2178                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2179                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
2180                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2181                                 {
2182                                         shader.backgroundlayer = -1;
2183                                         shader.primarylayer = 1;
2184                                 }
2185                                 else if (shader.numlayers >= 2
2186                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2187                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2188                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2189                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2190                                 {
2191                                         // terrain blending or other effects
2192                                         shader.backgroundlayer = 0;
2193                                         shader.primarylayer = 1;
2194                                 }
2195                         }
2196                         // fix up multiple reflection types
2197                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2198                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2199
2200                         Q3Shader_AddToHash (&shader);
2201                 }
2202                 Mem_Free(f);
2203         }
2204         FS_FreeSearch(search);
2205         // free custinfoparm values
2206         for (j = 0; j < numcustsurfaceparms; j++)
2207                 Mem_Free(custsurfaceparmnames[j]);
2208 }
2209
2210 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2211 {
2212         unsigned short hash;
2213         q3shader_hash_entry_t* entry;
2214         if (!q3shaders_mem)
2215                 Mod_LoadQ3Shaders();
2216         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2217         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2218         while (entry != NULL)
2219         {
2220                 if (strcasecmp (entry->shader.name, name) == 0)
2221                         return &entry->shader;
2222                 entry = entry->chain;
2223         }
2224         return NULL;
2225 }
2226
2227 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2228 {
2229         int j;
2230         int texflagsmask;
2231         qboolean success = true;
2232         q3shaderinfo_t *shader;
2233         if (!name)
2234                 name = "";
2235         strlcpy(texture->name, name, sizeof(texture->name));
2236         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2237
2238         texflagsmask = ~0;
2239         if(!(defaulttexflags & TEXF_PICMIP))
2240                 texflagsmask &= ~TEXF_PICMIP;
2241         if(!(defaulttexflags & TEXF_COMPRESS))
2242                 texflagsmask &= ~TEXF_COMPRESS;
2243         // unless later loaded from the shader
2244         texture->offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2245         texture->offsetscale = 1;
2246         texture->specularscalemod = 1;
2247         texture->specularpowermod = 1; 
2248         // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2249         // HERE, AND Q1BSP LOADING
2250         // JUST GREP FOR "specularscalemod = 1".
2251
2252         if (shader)
2253         {
2254                 if (developer_loading.integer)
2255                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2256                 texture->surfaceparms = shader->surfaceparms;
2257
2258                 // allow disabling of picmip or compression by defaulttexflags
2259                 texture->textureflags = shader->textureflags & texflagsmask;
2260
2261                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2262                 {
2263                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2264                         if (shader->skyboxname[0])
2265                         {
2266                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2267                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2268                         }
2269                 }
2270                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2271                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2272                 else
2273                         texture->basematerialflags = MATERIALFLAG_WALL;
2274
2275                 if (shader->layers[0].alphatest)
2276                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2277                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2278                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2279                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2280                         texture->biaspolygonoffset -= 2;
2281                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2282                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2283                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2284                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2285                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2286                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2287                 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2288                         texture->basematerialflags |= MATERIALFLAG_CAMERA;
2289                 texture->customblendfunc[0] = GL_ONE;
2290                 texture->customblendfunc[1] = GL_ZERO;
2291                 if (shader->numlayers > 0)
2292                 {
2293                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2294                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2295 /*
2296 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2297 * additive               GL_ONE GL_ONE
2298 additive weird         GL_ONE GL_SRC_ALPHA
2299 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2300 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2301 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2302 brighten               GL_DST_COLOR GL_ONE
2303 brighten               GL_ONE GL_SRC_COLOR
2304 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2305 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2306 * modulate               GL_DST_COLOR GL_ZERO
2307 * modulate               GL_ZERO GL_SRC_COLOR
2308 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2309 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2310 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2311 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2312 * no blend               GL_ONE GL_ZERO
2313 nothing                GL_ZERO GL_ONE
2314 */
2315                         // if not opaque, figure out what blendfunc to use
2316                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2317                         {
2318                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2319                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2320                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2321                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2322                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2323                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2324                                 else
2325                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2326                         }
2327                 }
2328                 if (!shader->lighting)
2329                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2330                 if (shader->primarylayer >= 0)
2331                 {
2332                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2333                         // copy over many primarylayer parameters
2334                         texture->rgbgen = primarylayer->rgbgen;
2335                         texture->alphagen = primarylayer->alphagen;
2336                         texture->tcgen = primarylayer->tcgen;
2337                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2338                         // load the textures
2339                         texture->numskinframes = primarylayer->numframes;
2340                         texture->skinframerate = primarylayer->framerate;
2341                         for (j = 0;j < primarylayer->numframes;j++)
2342                         {
2343                                 if(cls.state == ca_dedicated)
2344                                 {
2345                                         texture->skinframes[j] = NULL;
2346                                 }
2347                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2348                                 {
2349                                         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);
2350                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2351                                 }
2352                         }
2353                 }
2354                 if (shader->backgroundlayer >= 0)
2355                 {
2356                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2357                         // copy over one secondarylayer parameter
2358                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2359                         // load the textures
2360                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2361                         texture->backgroundskinframerate = backgroundlayer->framerate;
2362                         for (j = 0;j < backgroundlayer->numframes;j++)
2363                         {
2364                                 if(cls.state == ca_dedicated)
2365                                 {
2366                                         texture->skinframes[j] = NULL;
2367                                 }
2368                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2369                                 {
2370                                         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);
2371                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2372                                 }
2373                         }
2374                 }
2375                 if (shader->dpshadow)
2376                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2377                 if (shader->dpnoshadow)
2378                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2379                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2380                 texture->reflectmin = shader->reflectmin;
2381                 texture->reflectmax = shader->reflectmax;
2382                 texture->refractfactor = shader->refractfactor;
2383                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2384                 texture->reflectfactor = shader->reflectfactor;
2385                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2386                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2387                 texture->offsetmapping = shader->offsetmapping;
2388                 texture->offsetscale = shader->offsetscale;
2389                 texture->specularscalemod = shader->specularscalemod;
2390                 texture->specularpowermod = shader->specularpowermod;
2391                 if (shader->dpreflectcube[0])
2392                         texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2393
2394                 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2395                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2396                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents  = SUPERCONTENTS_LAVA         ;
2397                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents  = SUPERCONTENTS_SLIME        ;
2398                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents  = SUPERCONTENTS_WATER        ;
2399                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents  = 0                          ;
2400                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents  = SUPERCONTENTS_PLAYERCLIP   ;
2401                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents  = SUPERCONTENTS_MONSTERCLIP  ;
2402                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents  = SUPERCONTENTS_SKY          ;
2403
2404         //      if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW  ;
2405         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL   ;
2406         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2407         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->supercontents |= SUPERCONTENTS_DETAIL       ;
2408                 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->supercontents |= SUPERCONTENTS_DONOTENTER   ;
2409         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->supercontents |= SUPERCONTENTS_FOG          ;
2410                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents |= SUPERCONTENTS_LAVA         ;
2411         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER  ;
2412         //      if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->supercontents |= SUPERCONTENTS_METALSTEPS   ;
2413         //      if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->supercontents |= SUPERCONTENTS_NODAMAGE     ;
2414         //      if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->supercontents |= SUPERCONTENTS_NODLIGHT     ;
2415         //      if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->supercontents |= SUPERCONTENTS_NODRAW       ;
2416                 if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->supercontents |= SUPERCONTENTS_NODROP       ;
2417         //      if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->supercontents |= SUPERCONTENTS_NOIMPACT     ;
2418         //      if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP   ;
2419         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->supercontents |= SUPERCONTENTS_NOMARKS      ;
2420         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS    ;
2421                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents &=~SUPERCONTENTS_SOLID        ;
2422         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->supercontents |= SUPERCONTENTS_ORIGIN       ;
2423                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP   ;
2424                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents |= SUPERCONTENTS_SKY          ;
2425         //      if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->supercontents |= SUPERCONTENTS_SLICK        ;
2426                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents |= SUPERCONTENTS_SLIME        ;
2427         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL   ;
2428         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->supercontents |= SUPERCONTENTS_TRANS        ;
2429                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents |= SUPERCONTENTS_WATER        ;
2430         //      if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT   ;
2431         //      if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->supercontents |= SUPERCONTENTS_HINT         ;
2432         //      if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->supercontents |= SUPERCONTENTS_DUST         ;
2433                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents |= SUPERCONTENTS_BOTCLIP      | SUPERCONTENTS_MONSTERCLIP;
2434         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID    ;
2435         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL   ;
2436
2437                 if (shader->dpmeshcollisions)
2438                         texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2439         }
2440         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2441         {
2442                 if (developer_extra.integer)
2443                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2444                 texture->surfaceparms = 0;
2445                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2446         }
2447         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2448         {
2449                 if (developer_extra.integer)
2450                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2451                 texture->surfaceparms = 0;
2452                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2453                 texture->supercontents = SUPERCONTENTS_SOLID;
2454         }
2455         else
2456         {
2457                 if (developer_extra.integer)
2458                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2459                 texture->surfaceparms = 0;
2460                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2461                 {
2462                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2463                         texture->supercontents = SUPERCONTENTS_SOLID;
2464                 }
2465                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2466                 {
2467                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2468                         texture->supercontents = SUPERCONTENTS_SKY;
2469                 }
2470                 else
2471                 {
2472                         texture->basematerialflags |= MATERIALFLAG_WALL;
2473                         texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2474                 }
2475                 texture->numskinframes = 1;
2476                 if(cls.state == ca_dedicated)
2477                 {
2478                         texture->skinframes[0] = NULL;
2479                 }
2480                 else
2481                 {
2482                         if (fallback)
2483                         {
2484                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2485                                 {
2486                                         if(texture->skinframes[0]->hasalpha)
2487                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2488                                 }
2489                                 else
2490                                         success = false;
2491                         }
2492                         else
2493                                 success = false;
2494                         if (!success && warnmissing)
2495                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2496                 }
2497         }
2498         // init the animation variables
2499         texture->currentframe = texture;
2500         if (texture->numskinframes < 1)
2501                 texture->numskinframes = 1;
2502         if (!texture->skinframes[0])
2503                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2504         texture->currentskinframe = texture->skinframes[0];
2505         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2506         return success;
2507 }
2508
2509 skinfile_t *Mod_LoadSkinFiles(void)
2510 {
2511         int i, words, line, wordsoverflow;
2512         char *text;
2513         const char *data;
2514         skinfile_t *skinfile = NULL, *first = NULL;
2515         skinfileitem_t *skinfileitem;
2516         char word[10][MAX_QPATH];
2517
2518 /*
2519 sample file:
2520 U_bodyBox,models/players/Legoman/BikerA2.tga
2521 U_RArm,models/players/Legoman/BikerA1.tga
2522 U_LArm,models/players/Legoman/BikerA1.tga
2523 U_armor,common/nodraw
2524 U_sword,common/nodraw
2525 U_shield,common/nodraw
2526 U_homb,common/nodraw
2527 U_backpack,common/nodraw
2528 U_colcha,common/nodraw
2529 tag_head,
2530 tag_weapon,
2531 tag_torso,
2532 */
2533         memset(word, 0, sizeof(word));
2534         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2535         {
2536                 // If it's the first file we parse
2537                 if (skinfile == NULL)
2538                 {
2539                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2540                         first = skinfile;
2541                 }
2542                 else
2543                 {
2544                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2545                         skinfile = skinfile->next;
2546                 }
2547                 skinfile->next = NULL;
2548
2549                 for(line = 0;;line++)
2550                 {
2551                         // parse line
2552                         if (!COM_ParseToken_QuakeC(&data, true))
2553                                 break;
2554                         if (!strcmp(com_token, "\n"))
2555                                 continue;
2556                         words = 0;
2557                         wordsoverflow = false;
2558                         do
2559                         {
2560                                 if (words < 10)
2561                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2562                                 else
2563                                         wordsoverflow = true;
2564                         }
2565                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2566                         if (wordsoverflow)
2567                         {
2568                                 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);
2569                                 continue;
2570                         }
2571                         // words is always >= 1
2572                         if (!strcmp(word[0], "replace"))
2573                         {
2574                                 if (words == 3)
2575                                 {
2576                                         if (developer_loading.integer)
2577                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2578                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2579                                         skinfileitem->next = skinfile->items;
2580                                         skinfile->items = skinfileitem;
2581                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2582                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2583                                 }
2584                                 else
2585                                         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]);
2586                         }
2587                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2588                         {
2589                                 // tag name, like "tag_weapon,"
2590                                 // not used for anything (not even in Quake3)
2591                         }
2592                         else if (words >= 2 && !strcmp(word[1], ","))
2593                         {
2594                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2595                                 if (developer_loading.integer)
2596                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2597                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2598                                 skinfileitem->next = skinfile->items;
2599                                 skinfile->items = skinfileitem;
2600                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2601                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2602                         }
2603                         else
2604                                 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);
2605                 }
2606                 Mem_Free(text);
2607         }
2608         if (i)
2609                 loadmodel->numskins = i;
2610         return first;
2611 }
2612
2613 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2614 {
2615         skinfile_t *next;
2616         skinfileitem_t *skinfileitem, *nextitem;
2617         for (;skinfile;skinfile = next)
2618         {
2619                 next = skinfile->next;
2620                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2621                 {
2622                         nextitem = skinfileitem->next;
2623                         Mem_Free(skinfileitem);
2624                 }
2625                 Mem_Free(skinfile);
2626         }
2627 }
2628
2629 int Mod_CountSkinFiles(skinfile_t *skinfile)
2630 {
2631         int i;
2632         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2633         return i;
2634 }
2635
2636 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2637 {
2638         int i;
2639         double isnap = 1.0 / snap;
2640         for (i = 0;i < numvertices*numcomponents;i++)
2641                 vertices[i] = floor(vertices[i]*isnap)*snap;
2642 }
2643
2644 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2645 {
2646         int i, outtriangles;
2647         float edgedir1[3], edgedir2[3], temp[3];
2648         // a degenerate triangle is one with no width (thickness, surface area)
2649         // these are characterized by having all 3 points colinear (along a line)
2650         // or having two points identical
2651         // the simplest check is to calculate the triangle's area
2652         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2653         {
2654                 // calculate first edge
2655                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2656                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2657                 CrossProduct(edgedir1, edgedir2, temp);
2658                 if (VectorLength2(temp) < 0.001f)
2659                         continue; // degenerate triangle (no area)
2660                 // valid triangle (has area)
2661                 VectorCopy(inelement3i, outelement3i);
2662                 outelement3i += 3;
2663                 outtriangles++;
2664         }
2665         return outtriangles;
2666 }
2667
2668 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2669 {
2670         int i, e;
2671         int firstvertex, lastvertex;
2672         if (numelements > 0 && elements)
2673         {
2674                 firstvertex = lastvertex = elements[0];
2675                 for (i = 1;i < numelements;i++)
2676                 {
2677                         e = elements[i];
2678                         firstvertex = min(firstvertex, e);
2679                         lastvertex = max(lastvertex, e);
2680                 }
2681         }
2682         else
2683                 firstvertex = lastvertex = 0;
2684         if (firstvertexpointer)
2685                 *firstvertexpointer = firstvertex;
2686         if (lastvertexpointer)
2687                 *lastvertexpointer = lastvertex;
2688 }
2689
2690 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2691 {
2692         // make an optimal set of texture-sorted batches to draw...
2693         int j, t;
2694         int *firstsurfacefortexture;
2695         int *numsurfacesfortexture;
2696         if (!mod->sortedmodelsurfaces)
2697                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2698         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2699         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2700         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2701         for (j = 0;j < mod->nummodelsurfaces;j++)
2702         {
2703                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2704                 int t = (int)(surface->texture - mod->data_textures);
2705                 numsurfacesfortexture[t]++;
2706         }
2707         j = 0;
2708         for (t = 0;t < mod->num_textures;t++)
2709         {
2710                 firstsurfacefortexture[t] = j;
2711                 j += numsurfacesfortexture[t];
2712         }
2713         for (j = 0;j < mod->nummodelsurfaces;j++)
2714         {
2715                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2716                 int t = (int)(surface->texture - mod->data_textures);
2717                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2718         }
2719         Mem_Free(firstsurfacefortexture);
2720         Mem_Free(numsurfacesfortexture);
2721 }
2722
2723 void Mod_BuildVBOs(void)
2724 {
2725         if (!loadmodel->surfmesh.num_vertices)
2726                 return;
2727
2728         if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2729         {
2730                 int i;
2731                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2732                 {
2733                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2734                         {
2735                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2736                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2737                         }
2738                 }
2739         }
2740
2741         // build r_vertexmesh_t array
2742         // (compressed interleaved array for faster rendering)
2743         if (!loadmodel->surfmesh.vertexmesh)
2744         {
2745                 int vertexindex;
2746                 int numvertices = loadmodel->surfmesh.num_vertices;
2747                 r_vertexmesh_t *vertexmesh;
2748                 loadmodel->surfmesh.vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexmesh));
2749                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
2750                 {
2751                         VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexmesh->vertex3f);
2752                         VectorScale(loadmodel->surfmesh.data_svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
2753                         VectorScale(loadmodel->surfmesh.data_tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
2754                         VectorScale(loadmodel->surfmesh.data_normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
2755                         if (loadmodel->surfmesh.data_lightmapcolor4f)
2756                                 Vector4Scale(loadmodel->surfmesh.data_lightmapcolor4f + 4*vertexindex, 255.0f, vertexmesh->color4ub);
2757                         Vector2Copy(loadmodel->surfmesh.data_texcoordtexture2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
2758                         if (loadmodel->surfmesh.data_texcoordlightmap2f)
2759                                 Vector2Scale(loadmodel->surfmesh.data_texcoordlightmap2f + 2*vertexindex, 1.0f, vertexmesh->texcoordlightmap2f);
2760                 }
2761         }
2762
2763         // build r_vertexposition_t array
2764         if (!loadmodel->surfmesh.vertexposition)
2765         {
2766                 int vertexindex;
2767                 int numvertices = loadmodel->surfmesh.num_vertices;
2768                 r_vertexposition_t *vertexposition;
2769                 loadmodel->surfmesh.vertexposition = vertexposition = (r_vertexposition_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexposition));
2770                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexposition++)
2771                         VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexposition->vertex3f);
2772         }
2773
2774         // upload r_vertexmesh_t array as a buffer
2775         if (loadmodel->surfmesh.vertexmesh && !loadmodel->surfmesh.vertexmeshbuffer)
2776                 loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false);
2777
2778         // upload r_vertexposition_t array as a buffer
2779         if (loadmodel->surfmesh.vertexposition && !loadmodel->surfmesh.vertexpositionbuffer)
2780                 loadmodel->surfmesh.vertexpositionbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexposition, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexposition), loadmodel->name, false, false);
2781
2782         // upload short indices as a buffer
2783         if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
2784                 loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false);
2785
2786         // upload int indices as a buffer
2787         if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
2788                 loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false);
2789
2790         // only build a vbo if one has not already been created (this is important for brush models which load specially)
2791         // vertex buffer is several arrays and we put them in the same buffer
2792         //
2793         // is this wise?  the texcoordtexture2f array is used with dynamic
2794         // vertex/svector/tvector/normal when rendering animated models, on the
2795         // other hand animated models don't use a lot of vertices anyway...
2796         if (!loadmodel->surfmesh.vbo_vertexbuffer)
2797         {
2798                 size_t size;
2799                 unsigned char *mem;
2800                 size = 0;
2801                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2802                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2803                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2804                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2805                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2806                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2807                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2808                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2809                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2810                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2811                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2812                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2813                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2814                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2815                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2816                 loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false);
2817                 Mem_Free(mem);
2818         }
2819 }
2820
2821 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2822 {
2823         int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2824         int a, b, c;
2825         const char *texname;
2826         const int *e;
2827         const float *v, *vn, *vt;
2828         size_t l;
2829         size_t outbufferpos = 0;
2830         size_t outbuffermax = 0x100000;
2831         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2832         const msurface_t *surface;
2833         const int maxtextures = 256;
2834         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2835
2836         // construct the mtllib file
2837         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2838         if (l > 0)
2839                 outbufferpos += l;
2840         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2841         {
2842                 countsurfaces++;
2843                 countvertices += surface->num_vertices;
2844                 countfaces += surface->num_triangles;
2845                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2846                 for (textureindex = 0;textureindex < counttextures;textureindex++)
2847                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2848                                 break;
2849                 if (textureindex < counttextures)
2850                         continue; // already wrote this material entry
2851                 if (textureindex >= maxtextures)
2852                         continue; // just a precaution
2853                 textureindex = counttextures++;
2854                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2855                 if (outbufferpos >= outbuffermax >> 1)
2856                 {
2857                         outbuffermax *= 2;
2858                         oldbuffer = outbuffer;
2859                         outbuffer = (char *) Z_Malloc(outbuffermax);
2860                         memcpy(outbuffer, oldbuffer, outbufferpos);
2861                         Z_Free(oldbuffer);
2862                 }
2863                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "newmtl %s\nNs 96.078431\nKa 0 0 0\nKd 0.64 0.64 0.64\nKs 0.5 0.5 0.5\nNi 1\nd 1\nillum 2\nmap_Kd %s%s\n\n", texname, texname, strstr(texname, ".tga") ? "" : ".tga");
2864                 if (l > 0)
2865                         outbufferpos += l;
2866         }
2867
2868         // write the mtllib file
2869         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2870         outbufferpos = 0;
2871
2872         // construct the obj file
2873         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# model exported from %s by darkplaces engine\n# %i vertices, %i faces, %i surfaces\nmtllib %s\n", originalfilename, countvertices, countfaces, countsurfaces, mtlfilename);
2874         if (l > 0)
2875                 outbufferpos += l;
2876         for (vertexindex = 0, v = model->surfmesh.data_vertex3f, vn = model->surfmesh.data_normal3f, vt = model->surfmesh.data_texcoordtexture2f;vertexindex < model->surfmesh.num_vertices;vertexindex++, v += 3, vn += 3, vt += 2)
2877         {
2878                 if (outbufferpos >= outbuffermax >> 1)
2879                 {
2880                         outbuffermax *= 2;
2881                         oldbuffer = outbuffer;
2882                         outbuffer = (char *) Z_Malloc(outbuffermax);
2883                         memcpy(outbuffer, oldbuffer, outbufferpos);
2884                         Z_Free(oldbuffer);
2885                 }
2886                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[2], -v[1], vn[0], vn[2], -vn[1], vt[0], 1-vt[1]);
2887                 if (l > 0)
2888                         outbufferpos += l;
2889         }
2890         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2891         {
2892                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2893                 if (l > 0)
2894                         outbufferpos += l;
2895                 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2896                 {
2897                         if (outbufferpos >= outbuffermax >> 1)
2898                         {
2899                                 outbuffermax *= 2;
2900                                 oldbuffer = outbuffer;
2901                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2902                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2903                                 Z_Free(oldbuffer);
2904                         }
2905                         a = e[0]+1;
2906                         b = e[2]+1;
2907                         c = e[1]+1;
2908                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,b,b,b,c,c,c);
2909                         if (l > 0)
2910                                 outbufferpos += l;
2911                 }
2912         }
2913
2914         // write the obj file
2915         FS_WriteFile(filename, outbuffer, outbufferpos);
2916
2917         // clean up
2918         Z_Free(outbuffer);
2919         Z_Free(texturenames);
2920
2921         // print some stats
2922         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2923 }
2924
2925 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2926 {
2927         int countnodes = 0, counttriangles = 0, countframes = 0;
2928         int surfaceindex;
2929         int triangleindex;
2930         int transformindex;
2931         int poseindex;
2932         int cornerindex;
2933         const int *e;
2934         size_t l;
2935         size_t outbufferpos = 0;
2936         size_t outbuffermax = 0x100000;
2937         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2938         const msurface_t *surface;
2939         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
2940         if (l > 0)
2941                 outbufferpos += l;
2942         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2943         {
2944                 if (outbufferpos >= outbuffermax >> 1)
2945                 {
2946                         outbuffermax *= 2;
2947                         oldbuffer = outbuffer;
2948                         outbuffer = (char *) Z_Malloc(outbuffermax);
2949                         memcpy(outbuffer, oldbuffer, outbufferpos);
2950                         Z_Free(oldbuffer);
2951                 }
2952                 countnodes++;
2953                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2954                 if (l > 0)
2955                         outbufferpos += l;
2956         }
2957         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2958         if (l > 0)
2959                 outbufferpos += l;
2960         for (poseindex = 0;poseindex < numposes;poseindex++)
2961         {
2962                 countframes++;
2963                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2964                 if (l > 0)
2965                         outbufferpos += l;
2966                 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2967                 {
2968                         float angles[3];
2969                         float mtest[4][3];
2970                         matrix4x4_t posematrix;
2971                         if (outbufferpos >= outbuffermax >> 1)
2972                         {
2973                                 outbuffermax *= 2;
2974                                 oldbuffer = outbuffer;
2975                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2976                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2977                                 Z_Free(oldbuffer);
2978                         }
2979
2980                         // strangely the smd angles are for a transposed matrix, so we
2981                         // have to generate a transposed matrix, then convert that...
2982                         Matrix4x4_FromBonePose6s(&posematrix, model->num_posescale, model->data_poses6s + 6*(model->num_bones * poseindex + transformindex));
2983                         Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
2984                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
2985                         if (angles[0] >= 180) angles[0] -= 360;
2986                         if (angles[1] >= 180) angles[1] -= 360;
2987                         if (angles[2] >= 180) angles[2] -= 360;
2988
2989 #if 0
2990 {
2991                         float a = DEG2RAD(angles[ROLL]);
2992                         float b = DEG2RAD(angles[PITCH]);
2993                         float c = DEG2RAD(angles[YAW]);
2994                         float cy, sy, cp, sp, cr, sr;
2995                         float test[4][3];
2996                         // smd matrix construction, for comparing
2997                         sy = sin(c);
2998                         cy = cos(c);
2999                         sp = sin(b);
3000                         cp = cos(b);
3001                         sr = sin(a);
3002                         cr = cos(a);
3003
3004                         test[0][0] = cp*cy;
3005                         test[0][1] = cp*sy;
3006                         test[0][2] = -sp;
3007                         test[1][0] = sr*sp*cy+cr*-sy;
3008                         test[1][1] = sr*sp*sy+cr*cy;
3009                         test[1][2] = sr*cp;
3010                         test[2][0] = (cr*sp*cy+-sr*-sy);
3011                         test[2][1] = (cr*sp*sy+-sr*cy);
3012                         test[2][2] = cr*cp;
3013                         test[3][0] = pose[9];
3014                         test[3][1] = pose[10];
3015                         test[3][2] = pose[11];
3016 }
3017 #endif
3018                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, mtest[3][0], mtest[3][1], mtest[3][2], DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
3019                         if (l > 0)
3020                                 outbufferpos += l;
3021                 }
3022         }
3023         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3024         if (l > 0)
3025                 outbufferpos += l;
3026         if (writetriangles)
3027         {
3028                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
3029                 if (l > 0)
3030                         outbufferpos += l;
3031                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3032                 {
3033                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3034                         {
3035                                 counttriangles++;
3036                                 if (outbufferpos >= outbuffermax >> 1)
3037                                 {
3038                                         outbuffermax *= 2;
3039                                         oldbuffer = outbuffer;
3040                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3041                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3042                                         Z_Free(oldbuffer);
3043                                 }
3044                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
3045                                 if (l > 0)
3046                                         outbufferpos += l;
3047                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
3048                                 {
3049                                         const int index = e[2-cornerindex];
3050                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
3051                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
3052                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
3053                                         const int b = model->surfmesh.blends[index];
3054                                         if (b < model->num_bones)
3055                                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , b, v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
3056                                         else
3057                                      &nb