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