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