]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_shared.c
mod_obj_orientation: affect modeldecompile too
[xonotic/darkplaces.git] / model_shared.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // models.c -- model loading and caching
21
22 // models are the only shared resource between a client and server running
23 // on the same machine.
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "r_shadow.h"
28 #include "polygon.h"
29
30 cvar_t r_enableshadowvolumes = {CVAR_SAVE, "r_enableshadowvolumes", "1", "Enables use of Stencil Shadow Volume shadowing methods, saves some memory if turned off"};
31 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"};
32 cvar_t r_mipnormalmaps = {CVAR_SAVE, "r_mipnormalmaps", "1", "mipmaps normalmaps (turning it off looks sharper but may have aliasing)"};
33 cvar_t mod_generatelightmaps_unitspersample = {CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
34 cvar_t mod_generatelightmaps_borderpixels = {CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
35 cvar_t mod_generatelightmaps_texturesize = {CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
36 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
37 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
38 cvar_t mod_generatelightmaps_gridsamples = {CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
39 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
40 cvar_t mod_generatelightmaps_vertexradius = {CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
41 cvar_t mod_generatelightmaps_gridradius = {CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
42
43 dp_model_t *loadmodel;
44
45 static mempool_t *mod_mempool;
46 static memexpandablearray_t models;
47
48 static mempool_t* q3shaders_mem;
49 typedef struct q3shader_hash_entry_s
50 {
51   q3shaderinfo_t shader;
52   struct q3shader_hash_entry_s* chain;
53 } q3shader_hash_entry_t;
54 #define Q3SHADER_HASH_SIZE  1021
55 typedef struct q3shader_data_s
56 {
57   memexpandablearray_t hash_entries;
58   q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
59   memexpandablearray_t char_ptrs;
60 } q3shader_data_t;
61 static q3shader_data_t* q3shader_data;
62
63 static void mod_start(void)
64 {
65         int i, count;
66         int nummodels = Mem_ExpandableArray_IndexRange(&models);
67         dp_model_t *mod;
68
69         SCR_PushLoadingScreen(false, "Loading models", 1.0);
70         count = 0;
71         for (i = 0;i < nummodels;i++)
72                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
73                         if (mod->used)
74                                 ++count;
75         for (i = 0;i < nummodels;i++)
76                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
77                         if (mod->used)
78                         {
79                                 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
80                                 Mod_LoadModel(mod, true, false);
81                                 SCR_PopLoadingScreen(false);
82                         }
83         SCR_PopLoadingScreen(false);
84 }
85
86 static void mod_shutdown(void)
87 {
88         int i;
89         int nummodels = Mem_ExpandableArray_IndexRange(&models);
90         dp_model_t *mod;
91
92         for (i = 0;i < nummodels;i++)
93                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
94                         Mod_UnloadModel(mod);
95
96         Mod_FreeQ3Shaders();
97         Mod_Skeletal_FreeBuffers();
98 }
99
100 static void mod_newmap(void)
101 {
102         msurface_t *surface;
103         int i, j, k, surfacenum, ssize, tsize;
104         int nummodels = Mem_ExpandableArray_IndexRange(&models);
105         dp_model_t *mod;
106
107         for (i = 0;i < nummodels;i++)
108         {
109                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
110                 {
111                         for (j = 0;j < mod->num_textures && mod->data_textures;j++)
112                         {
113                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
114                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
115                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
116                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
117                         }
118                         if (mod->brush.solidskyskinframe)
119                                 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
120                         if (mod->brush.alphaskyskinframe)
121                                 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
122                 }
123         }
124
125         if (!cl_stainmaps_clearonload.integer)
126                 return;
127
128         for (i = 0;i < nummodels;i++)
129         {
130                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
131                 {
132                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
133                         {
134                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
135                                 {
136                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
137                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
138                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
139                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
140                                 }
141                         }
142                 }
143         }
144 }
145
146 /*
147 ===============
148 Mod_Init
149 ===============
150 */
151 static void Mod_Print(void);
152 static void Mod_Precache (void);
153 static void Mod_Decompile_f(void);
154 static void Mod_GenerateLightmaps_f(void);
155 void Mod_Init (void)
156 {
157         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
158         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
159
160         Mod_BrushInit();
161         Mod_AliasInit();
162         Mod_SpriteInit();
163
164         Cvar_RegisterVariable(&r_enableshadowvolumes);
165         Cvar_RegisterVariable(&r_mipskins);
166         Cvar_RegisterVariable(&r_mipnormalmaps);
167         Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
168         Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
169         Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
170
171         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
172         Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
173         Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
174         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
175         Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
176         Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
177
178         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
179         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
180         Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
181         Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
182 }
183
184 void Mod_RenderInit(void)
185 {
186         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap, NULL, NULL);
187 }
188
189 void Mod_UnloadModel (dp_model_t *mod)
190 {
191         char name[MAX_QPATH];
192         qboolean used;
193         dp_model_t *parentmodel;
194
195         if (developer_loading.integer)
196                 Con_Printf("unloading model %s\n", mod->name);
197
198         strlcpy(name, mod->name, sizeof(name));
199         parentmodel = mod->brush.parentmodel;
200         used = mod->used;
201         if (mod->mempool)
202         {
203                 if (mod->surfmesh.vertex3fbuffer)
204                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertex3fbuffer);
205                 mod->surfmesh.vertex3fbuffer = NULL;
206                 if (mod->surfmesh.vertexmeshbuffer)
207                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexmeshbuffer);
208                 mod->surfmesh.vertexmeshbuffer = NULL;
209                 if (mod->surfmesh.data_element3i_indexbuffer)
210                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
211                 mod->surfmesh.data_element3i_indexbuffer = NULL;
212                 if (mod->surfmesh.data_element3s_indexbuffer)
213                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
214                 mod->surfmesh.data_element3s_indexbuffer = NULL;
215                 if (mod->surfmesh.vbo_vertexbuffer)
216                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vbo_vertexbuffer);
217                 mod->surfmesh.vbo_vertexbuffer = NULL;
218         }
219         // free textures/memory attached to the model
220         R_FreeTexturePool(&mod->texturepool);
221         Mem_FreePool(&mod->mempool);
222         // clear the struct to make it available
223         memset(mod, 0, sizeof(dp_model_t));
224         // restore the fields we want to preserve
225         strlcpy(mod->name, name, sizeof(mod->name));
226         mod->brush.parentmodel = parentmodel;
227         mod->used = used;
228         mod->loaded = false;
229 }
230
231 static void R_Model_Null_Draw(entity_render_t *ent)
232 {
233         return;
234 }
235
236
237 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, const char *name, void *pass);
238
239 static int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
240 {
241         const char *bufptr;
242         int start, len;
243         float fps;
244         unsigned int i;
245         qboolean loop;
246         char name[64];
247
248         bufptr = buf;
249         i = 0;
250         while(bufptr)
251         {
252                 // an anim scene!
253
254                 // REQUIRED: fetch start
255                 COM_ParseToken_Simple(&bufptr, true, false, true);
256                 if (!bufptr)
257                         break; // end of file
258                 if (!strcmp(com_token, "\n"))
259                         continue; // empty line
260                 start = atoi(com_token);
261
262                 // REQUIRED: fetch length
263                 COM_ParseToken_Simple(&bufptr, true, false, true);
264                 if (!bufptr || !strcmp(com_token, "\n"))
265                 {
266                         Con_Printf("framegroups file: missing number of frames\n");
267                         continue;
268                 }
269                 len = atoi(com_token);
270
271                 // OPTIONAL args start
272                 COM_ParseToken_Simple(&bufptr, true, false, true);
273
274                 // OPTIONAL: fetch fps
275                 fps = 20;
276                 if (bufptr && strcmp(com_token, "\n"))
277                 {
278                         fps = atof(com_token);
279                         COM_ParseToken_Simple(&bufptr, true, false, true);
280                 }
281
282                 // OPTIONAL: fetch loopflag
283                 loop = true;
284                 if (bufptr && strcmp(com_token, "\n"))
285                 {
286                         loop = (atoi(com_token) != 0);
287                         COM_ParseToken_Simple(&bufptr, true, false, true);
288                 }
289
290                 // OPTIONAL: fetch name
291                 name[0] = 0;
292                 if (bufptr && strcmp(com_token, "\n"))
293                 {
294                         strlcpy(name, com_token, sizeof(name));
295                         COM_ParseToken_Simple(&bufptr, true, false, true);
296                 }
297
298                 // OPTIONAL: remaining unsupported tokens (eat them)
299                 while (bufptr && strcmp(com_token, "\n"))
300                         COM_ParseToken_Simple(&bufptr, true, false, true);
301
302                 //Con_Printf("data: %d %d %d %f %d (%s)\n", i, start, len, fps, loop, name);
303
304                 if(cb)
305                         cb(i, start, len, fps, loop, (name[0] ? name : NULL), pass);
306                 ++i;
307         }
308
309         return i;
310 }
311
312 static void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, const char *name, void *pass)
313 {
314         dp_model_t *mod = (dp_model_t *) pass;
315         animscene_t *anim = &mod->animscenes[i];
316         if(name)
317                 strlcpy(anim->name, name, sizeof(anim[i].name));
318         else
319                 dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
320         anim->firstframe = bound(0, start, mod->num_poses - 1);
321         anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
322         anim->framerate = max(1, fps);
323         anim->loop = !!loop;
324         //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
325 }
326
327 static void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
328 {
329         unsigned int cnt;
330
331         // 0. count
332         cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
333         if(!cnt)
334         {
335                 Con_Printf("no scene found in framegroups file, aborting\n");
336                 return;
337         }
338         mod->numframes = cnt;
339
340         // 1. reallocate
341         // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
342         mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
343
344         // 2. parse
345         Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
346 }
347
348 static void Mod_FindPotentialDeforms(dp_model_t *mod)
349 {
350         int i, j;
351         texture_t *texture;
352         mod->wantnormals = false;
353         mod->wanttangents = false;
354         for (i = 0;i < mod->num_textures;i++)
355         {
356                 texture = mod->data_textures + i;
357                 if (texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
358                         mod->wantnormals = true;
359                 for (j = 0;j < Q3MAXDEFORMS;j++)
360                 {
361                         if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
362                         {
363                                 mod->wanttangents = true;
364                                 mod->wantnormals = true;
365                                 break;
366                         }
367                         if (texture->deforms[j].deform != Q3DEFORM_NONE)
368                                 mod->wantnormals = true;
369                 }
370         }
371 }
372
373 /*
374 ==================
375 Mod_LoadModel
376
377 Loads a model
378 ==================
379 */
380 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
381 {
382         int num;
383         unsigned int crc;
384         void *buf;
385         fs_offset_t filesize = 0;
386         char vabuf[1024];
387
388         mod->used = true;
389
390         if (mod->name[0] == '*') // submodel
391                 return mod;
392         
393         if (!strcmp(mod->name, "null"))
394         {
395                 if(mod->loaded)
396                         return mod;
397
398                 if (mod->loaded || mod->mempool)
399                         Mod_UnloadModel(mod);
400
401                 if (developer_loading.integer)
402                         Con_Printf("loading model %s\n", mod->name);
403
404                 mod->used = true;
405                 mod->crc = (unsigned int)-1;
406                 mod->loaded = false;
407
408                 VectorClear(mod->normalmins);
409                 VectorClear(mod->normalmaxs);
410                 VectorClear(mod->yawmins);
411                 VectorClear(mod->yawmaxs);
412                 VectorClear(mod->rotatedmins);
413                 VectorClear(mod->rotatedmaxs);
414
415                 mod->modeldatatypestring = "null";
416                 mod->type = mod_null;
417                 mod->Draw = R_Model_Null_Draw;
418                 mod->numframes = 2;
419                 mod->numskins = 1;
420
421                 // no fatal errors occurred, so this model is ready to use.
422                 mod->loaded = true;
423
424                 return mod;
425         }
426
427         crc = 0;
428         buf = NULL;
429
430         // even if the model is loaded it still may need reloading...
431
432         // if it is not loaded or checkdisk is true we need to calculate the crc
433         if (!mod->loaded || checkdisk)
434         {
435                 if (checkdisk && mod->loaded)
436                         Con_DPrintf("checking model %s\n", mod->name);
437                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
438                 if (buf)
439                 {
440                         crc = CRC_Block((unsigned char *)buf, filesize);
441                         // we need to reload the model if the crc does not match
442                         if (mod->crc != crc)
443                                 mod->loaded = false;
444                 }
445         }
446
447         // if the model is already loaded and checks passed, just return
448         if (mod->loaded)
449         {
450                 if (buf)
451                         Mem_Free(buf);
452                 return mod;
453         }
454
455         if (developer_loading.integer)
456                 Con_Printf("loading model %s\n", mod->name);
457         
458         SCR_PushLoadingScreen(true, mod->name, 1);
459
460         // LordHavoc: unload the existing model in this slot (if there is one)
461         if (mod->loaded || mod->mempool)
462                 Mod_UnloadModel(mod);
463
464         // load the model
465         mod->used = true;
466         mod->crc = crc;
467         // errors can prevent the corresponding mod->loaded = true;
468         mod->loaded = false;
469
470         // default lightmap scale
471         mod->lightmapscale = 1;
472
473         // default model radius and bounding box (mainly for missing models)
474         mod->radius = 16;
475         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
476         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
477         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
478         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
479         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
480         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
481
482         if (!q3shaders_mem)
483         {
484                 // load q3 shaders for the first time, or after a level change
485                 Mod_LoadQ3Shaders();
486         }
487
488         if (buf)
489         {
490                 char *bufend = (char *)buf + filesize;
491
492                 // all models use memory, so allocate a memory pool
493                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
494
495                 num = LittleLong(*((int *)buf));
496                 // call the apropriate loader
497                 loadmodel = mod;
498                 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
499                 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
500                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
501                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
502                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
503                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
504                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
505                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
506                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
507                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
508                 else if (!memcmp(buf, "INTERQUAKEMODEL", 16)) Mod_INTERQUAKEMODEL_Load(mod, buf, bufend);
509                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
510                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
511                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
512                 Mem_Free(buf);
513
514                 Mod_FindPotentialDeforms(mod);
515
516                 buf = FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.framegroups", mod->name), tempmempool, false, &filesize);
517                 if(buf)
518                 {
519                         Mod_FrameGroupify(mod, (const char *)buf);
520                         Mem_Free(buf);
521                 }
522
523                 Mod_BuildVBOs();
524         }
525         else if (crash)
526         {
527                 // LordHavoc: Sys_Error was *ANNOYING*
528                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
529         }
530
531         // no fatal errors occurred, so this model is ready to use.
532         mod->loaded = true;
533
534         SCR_PopLoadingScreen(false);
535
536         return mod;
537 }
538
539 void Mod_ClearUsed(void)
540 {
541         int i;
542         int nummodels = Mem_ExpandableArray_IndexRange(&models);
543         dp_model_t *mod;
544         for (i = 0;i < nummodels;i++)
545                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
546                         mod->used = false;
547 }
548
549 void Mod_PurgeUnused(void)
550 {
551         int i;
552         int nummodels = Mem_ExpandableArray_IndexRange(&models);
553         dp_model_t *mod;
554         for (i = 0;i < nummodels;i++)
555         {
556                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
557                 {
558                         Mod_UnloadModel(mod);
559                         Mem_ExpandableArray_FreeRecord(&models, mod);
560                 }
561         }
562 }
563
564 /*
565 ==================
566 Mod_FindName
567
568 ==================
569 */
570 dp_model_t *Mod_FindName(const char *name, const char *parentname)
571 {
572         int i;
573         int nummodels;
574         dp_model_t *mod;
575
576         if (!parentname)
577                 parentname = "";
578
579         // if we're not dedicatd, the renderer calls will crash without video
580         Host_StartVideo();
581
582         nummodels = Mem_ExpandableArray_IndexRange(&models);
583
584         if (!name[0])
585                 Host_Error ("Mod_ForName: NULL name");
586
587         // search the currently loaded models
588         for (i = 0;i < nummodels;i++)
589         {
590                 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))))
591                 {
592                         mod->used = true;
593                         return mod;
594                 }
595         }
596
597         // no match found, create a new one
598         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
599         strlcpy(mod->name, name, sizeof(mod->name));
600         if (parentname[0])
601                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
602         else
603                 mod->brush.parentmodel = NULL;
604         mod->loaded = false;
605         mod->used = true;
606         return mod;
607 }
608
609 /*
610 ==================
611 Mod_ForName
612
613 Loads in a model for the given name
614 ==================
615 */
616 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
617 {
618         dp_model_t *model;
619         model = Mod_FindName(name, parentname);
620         if (!model->loaded || checkdisk)
621                 Mod_LoadModel(model, crash, checkdisk);
622         return model;
623 }
624
625 /*
626 ==================
627 Mod_Reload
628
629 Reloads all models if they have changed
630 ==================
631 */
632 void Mod_Reload(void)
633 {
634         int i, count;
635         int nummodels = Mem_ExpandableArray_IndexRange(&models);
636         dp_model_t *mod;
637
638         SCR_PushLoadingScreen(false, "Reloading models", 1.0);
639         count = 0;
640         for (i = 0;i < nummodels;i++)
641                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
642                         ++count;
643         for (i = 0;i < nummodels;i++)
644                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
645                 {
646                         SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
647                         Mod_LoadModel(mod, true, true);
648                         SCR_PopLoadingScreen(false);
649                 }
650         SCR_PopLoadingScreen(false);
651 }
652
653 unsigned char *mod_base;
654
655
656 //=============================================================================
657
658 /*
659 ================
660 Mod_Print
661 ================
662 */
663 static void Mod_Print(void)
664 {
665         int i;
666         int nummodels = Mem_ExpandableArray_IndexRange(&models);
667         dp_model_t *mod;
668
669         Con_Print("Loaded models:\n");
670         for (i = 0;i < nummodels;i++)
671         {
672                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
673                 {
674                         if (mod->brush.numsubmodels)
675                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
676                         else
677                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
678                 }
679         }
680 }
681
682 /*
683 ================
684 Mod_Precache
685 ================
686 */
687 static void Mod_Precache(void)
688 {
689         if (Cmd_Argc() == 2)
690                 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
691         else
692                 Con_Print("usage: modelprecache <filename>\n");
693 }
694
695 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
696 {
697         int i, count;
698         unsigned char *used;
699         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
700         memset(used, 0, numvertices);
701         for (i = 0;i < numelements;i++)
702                 used[elements[i]] = 1;
703         for (i = 0, count = 0;i < numvertices;i++)
704                 remapvertices[i] = used[i] ? count++ : -1;
705         Mem_Free(used);
706         return count;
707 }
708
709 #if 1
710 // fast way, using an edge hash
711 #define TRIANGLEEDGEHASH 8192
712 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
713 {
714         int i, j, p, e1, e2, *n, hashindex, count, match;
715         const int *e;
716         typedef struct edgehashentry_s
717         {
718                 struct edgehashentry_s *next;
719                 int triangle;
720                 int element[2];
721         }
722         edgehashentry_t;
723         static edgehashentry_t **edgehash;
724         edgehashentry_t *edgehashentries, *hash;
725         if (!numtriangles)
726                 return;
727         edgehash = (edgehashentry_t **)Mem_Alloc(tempmempool, TRIANGLEEDGEHASH * sizeof(*edgehash));
728         // if there are too many triangles for the stack array, allocate larger buffer
729         edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
730         // find neighboring triangles
731         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
732         {
733                 for (j = 0, p = 2;j < 3;p = j, j++)
734                 {
735                         e1 = e[p];
736                         e2 = e[j];
737                         // this hash index works for both forward and backward edges
738                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
739                         hash = edgehashentries + i * 3 + j;
740                         hash->next = edgehash[hashindex];
741                         edgehash[hashindex] = hash;
742                         hash->triangle = i;
743                         hash->element[0] = e1;
744                         hash->element[1] = e2;
745                 }
746         }
747         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
748         {
749                 for (j = 0, p = 2;j < 3;p = j, j++)
750                 {
751                         e1 = e[p];
752                         e2 = e[j];
753                         // this hash index works for both forward and backward edges
754                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
755                         count = 0;
756                         match = -1;
757                         for (hash = edgehash[hashindex];hash;hash = hash->next)
758                         {
759                                 if (hash->element[0] == e2 && hash->element[1] == e1)
760                                 {
761                                         if (hash->triangle != i)
762                                                 match = hash->triangle;
763                                         count++;
764                                 }
765                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
766                                         count++;
767                         }
768                         // detect edges shared by three triangles and make them seams
769                         if (count > 2)
770                                 match = -1;
771                         n[p] = match;
772                 }
773
774                 // also send a keepalive here (this can take a while too!)
775                 CL_KeepaliveMessage(false);
776         }
777         // free the allocated buffer
778         Mem_Free(edgehashentries);
779         Mem_Free(edgehash);
780 }
781 #else
782 // very slow but simple way
783 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
784 {
785         int i, match, count;
786         count = 0;
787         match = -1;
788         for (i = 0;i < numtriangles;i++, elements += 3)
789         {
790                      if ((elements[0] == start && elements[1] == end)
791                       || (elements[1] == start && elements[2] == end)
792                       || (elements[2] == start && elements[0] == end))
793                 {
794                         if (i != ignore)
795                                 match = i;
796                         count++;
797                 }
798                 else if ((elements[1] == start && elements[0] == end)
799                       || (elements[2] == start && elements[1] == end)
800                       || (elements[0] == start && elements[2] == end))
801                         count++;
802         }
803         // detect edges shared by three triangles and make them seams
804         if (count > 2)
805                 match = -1;
806         return match;
807 }
808
809 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
810 {
811         int i, *n;
812         const int *e;
813         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
814         {
815                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
816                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
817                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
818         }
819 }
820 #endif
821
822 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
823 {
824         int i, warned = false, endvertex = firstvertex + numverts;
825         for (i = 0;i < numtriangles * 3;i++)
826         {
827                 if (elements[i] < firstvertex || elements[i] >= endvertex)
828                 {
829                         if (!warned)
830                         {
831                                 warned = true;
832                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
833                         }
834                         elements[i] = firstvertex;
835                 }
836         }
837 }
838
839 // warning: this is an expensive function!
840 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
841 {
842         int i, j;
843         const int *element;
844         float *vectorNormal;
845         float areaNormal[3];
846         // clear the vectors
847         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
848         // process each vertex of each triangle and accumulate the results
849         // use area-averaging, to make triangles with a big area have a bigger
850         // weighting on the vertex normal than triangles with a small area
851         // to do so, just add the 'normals' together (the bigger the area
852         // the greater the length of the normal is
853         element = elements;
854         for (i = 0; i < numtriangles; i++, element += 3)
855         {
856                 TriangleNormal(
857                         vertex3f + element[0] * 3,
858                         vertex3f + element[1] * 3,
859                         vertex3f + element[2] * 3,
860                         areaNormal
861                         );
862
863                 if (!areaweighting)
864                         VectorNormalize(areaNormal);
865
866                 for (j = 0;j < 3;j++)
867                 {
868                         vectorNormal = normal3f + element[j] * 3;
869                         vectorNormal[0] += areaNormal[0];
870                         vectorNormal[1] += areaNormal[1];
871                         vectorNormal[2] += areaNormal[2];
872                 }
873         }
874         // and just normalize the accumulated vertex normal in the end
875         vectorNormal = normal3f + 3 * firstvertex;
876         for (i = 0; i < numvertices; i++, vectorNormal += 3)
877                 VectorNormalize(vectorNormal);
878 }
879
880 #if 0
881 static void Mod_BuildBumpVectors(const float *v0, const float *v1, const float *v2, const float *tc0, const float *tc1, const float *tc2, float *svector3f, float *tvector3f, float *normal3f)
882 {
883         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
884         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
885         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
886
887         // 6 multiply, 9 subtract
888         VectorSubtract(v1, v0, v10);
889         VectorSubtract(v2, v0, v20);
890         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
891         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
892         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
893         // 12 multiply, 10 subtract
894         tc10[1] = tc1[1] - tc0[1];
895         tc20[1] = tc2[1] - tc0[1];
896         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
897         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
898         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
899         tc10[0] = tc1[0] - tc0[0];
900         tc20[0] = tc2[0] - tc0[0];
901         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
902         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
903         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
904         // 12 multiply, 4 add, 6 subtract
905         f = DotProduct(svector3f, normal3f);
906         svector3f[0] -= f * normal3f[0];
907         svector3f[1] -= f * normal3f[1];
908         svector3f[2] -= f * normal3f[2];
909         f = DotProduct(tvector3f, normal3f);
910         tvector3f[0] -= f * normal3f[0];
911         tvector3f[1] -= f * normal3f[1];
912         tvector3f[2] -= f * normal3f[2];
913         // if texture is mapped the wrong way (counterclockwise), the tangents
914         // have to be flipped, this is detected by calculating a normal from the
915         // two tangents, and seeing if it is opposite the surface normal
916         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
917         CrossProduct(tvector3f, svector3f, tangentcross);
918         if (DotProduct(tangentcross, normal3f) < 0)
919         {
920                 VectorNegate(svector3f, svector3f);
921                 VectorNegate(tvector3f, tvector3f);
922         }
923 }
924 #endif
925
926 // warning: this is a very expensive function!
927 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)
928 {
929         int i, tnum;
930         float sdir[3], tdir[3], normal[3], *sv, *tv;
931         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
932         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
933         const int *e;
934         // clear the vectors
935         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
936         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
937         // process each vertex of each triangle and accumulate the results
938         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
939         {
940                 v0 = vertex3f + e[0] * 3;
941                 v1 = vertex3f + e[1] * 3;
942                 v2 = vertex3f + e[2] * 3;
943                 tc0 = texcoord2f + e[0] * 2;
944                 tc1 = texcoord2f + e[1] * 2;
945                 tc2 = texcoord2f + e[2] * 2;
946
947                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
948                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
949
950                 // calculate the edge directions and surface normal
951                 // 6 multiply, 9 subtract
952                 VectorSubtract(v1, v0, v10);
953                 VectorSubtract(v2, v0, v20);
954                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
955                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
956                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
957
958                 // calculate the tangents
959                 // 12 multiply, 10 subtract
960                 tc10[1] = tc1[1] - tc0[1];
961                 tc20[1] = tc2[1] - tc0[1];
962                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
963                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
964                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
965                 tc10[0] = tc1[0] - tc0[0];
966                 tc20[0] = tc2[0] - tc0[0];
967                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
968                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
969                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
970
971                 // if texture is mapped the wrong way (counterclockwise), the tangents
972                 // have to be flipped, this is detected by calculating a normal from the
973                 // two tangents, and seeing if it is opposite the surface normal
974                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
975                 CrossProduct(tdir, sdir, tangentcross);
976                 if (DotProduct(tangentcross, normal) < 0)
977                 {
978                         VectorNegate(sdir, sdir);
979                         VectorNegate(tdir, tdir);
980                 }
981
982                 if (!areaweighting)
983                 {
984                         VectorNormalize(sdir);
985                         VectorNormalize(tdir);
986                 }
987                 for (i = 0;i < 3;i++)
988                 {
989                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
990                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
991                 }
992         }
993         // make the tangents completely perpendicular to the surface normal, and
994         // then normalize them
995         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
996         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
997         {
998                 f = -DotProduct(sv, n);
999                 VectorMA(sv, f, n, sv);
1000                 VectorNormalize(sv);
1001                 f = -DotProduct(tv, n);
1002                 VectorMA(tv, f, n, tv);
1003                 VectorNormalize(tv);
1004         }
1005 }
1006
1007 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
1008 {
1009         unsigned char *data;
1010         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));
1011         loadmodel->surfmesh.num_vertices = numvertices;
1012         loadmodel->surfmesh.num_triangles = numtriangles;
1013         if (loadmodel->surfmesh.num_vertices)
1014         {
1015                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
1016                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
1017                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
1018                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
1019                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
1020                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
1021                 if (vertexcolors)
1022                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
1023                 if (lightmapoffsets)
1024                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
1025         }
1026         if (loadmodel->surfmesh.num_triangles)
1027         {
1028                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1029                 if (neighbors)
1030                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1031                 if (loadmodel->surfmesh.num_vertices <= 65536)
1032                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
1033         }
1034 }
1035
1036 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)
1037 {
1038         shadowmesh_t *newmesh;
1039         unsigned char *data;
1040         int size;
1041         size = sizeof(shadowmesh_t);
1042         size += maxverts * sizeof(float[3]);
1043         if (light)
1044                 size += maxverts * sizeof(float[11]);
1045         size += maxtriangles * sizeof(int[3]);
1046         if (maxverts <= 65536)
1047                 size += maxtriangles * sizeof(unsigned short[3]);
1048         if (neighbors)
1049                 size += maxtriangles * sizeof(int[3]);
1050         if (expandable)
1051                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
1052         data = (unsigned char *)Mem_Alloc(mempool, size);
1053         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
1054         newmesh->map_diffuse = map_diffuse;
1055         newmesh->map_specular = map_specular;
1056         newmesh->map_normal = map_normal;
1057         newmesh->maxverts = maxverts;
1058         newmesh->maxtriangles = maxtriangles;
1059         newmesh->numverts = 0;
1060         newmesh->numtriangles = 0;
1061         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
1062         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
1063
1064         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
1065         if (light)
1066         {
1067                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1068                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1069                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1070                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1071         }
1072         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1073         if (neighbors)
1074         {
1075                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1076         }
1077         if (expandable)
1078         {
1079                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1080                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1081         }
1082         if (maxverts <= 65536)
1083                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1084         return newmesh;
1085 }
1086
1087 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1088 {
1089         shadowmesh_t *newmesh;
1090         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1091         newmesh->numverts = oldmesh->numverts;
1092         newmesh->numtriangles = oldmesh->numtriangles;
1093         memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1094         memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1095
1096         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1097         if (newmesh->svector3f && oldmesh->svector3f)
1098         {
1099                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1100                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1101                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1102                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1103         }
1104         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1105         if (newmesh->neighbor3i && oldmesh->neighbor3i)
1106                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1107         return newmesh;
1108 }
1109
1110 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1111 {
1112         int hashindex, vnum;
1113         shadowmeshvertexhash_t *hash;
1114         // this uses prime numbers intentionally
1115         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1116         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1117         {
1118                 vnum = (hash - mesh->vertexhashentries);
1119                 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]))
1120                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1121                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1122                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1123                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1124                         return hash - mesh->vertexhashentries;
1125         }
1126         vnum = mesh->numverts++;
1127         hash = mesh->vertexhashentries + vnum;
1128         hash->next = mesh->vertexhashtable[hashindex];
1129         mesh->vertexhashtable[hashindex] = hash;
1130         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1131         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1132         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1133         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1134         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1135         return vnum;
1136 }
1137
1138 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1139 {
1140         if (mesh->numtriangles == 0)
1141         {
1142                 // set the properties on this empty mesh to be more favorable...
1143                 // (note: this case only occurs for the first triangle added to a new mesh chain)
1144                 mesh->map_diffuse = map_diffuse;
1145                 mesh->map_specular = map_specular;
1146                 mesh->map_normal = map_normal;
1147         }
1148         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)
1149         {
1150                 if (mesh->next == NULL)
1151                         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);
1152                 mesh = mesh->next;
1153         }
1154         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1155         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1156         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1157         mesh->numtriangles++;
1158 }
1159
1160 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)
1161 {
1162         int i, j, e;
1163         float vbuf[3*14], *v;
1164         memset(vbuf, 0, sizeof(vbuf));
1165         for (i = 0;i < numtris;i++)
1166         {
1167                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1168                 {
1169                         e = *element3i++;
1170                         if (vertex3f)
1171                         {
1172                                 v[0] = vertex3f[e * 3 + 0];
1173                                 v[1] = vertex3f[e * 3 + 1];
1174                                 v[2] = vertex3f[e * 3 + 2];
1175                         }
1176                         if (svector3f)
1177                         {
1178                                 v[3] = svector3f[e * 3 + 0];
1179                                 v[4] = svector3f[e * 3 + 1];
1180                                 v[5] = svector3f[e * 3 + 2];
1181                         }
1182                         if (tvector3f)
1183                         {
1184                                 v[6] = tvector3f[e * 3 + 0];
1185                                 v[7] = tvector3f[e * 3 + 1];
1186                                 v[8] = tvector3f[e * 3 + 2];
1187                         }
1188                         if (normal3f)
1189                         {
1190                                 v[9] = normal3f[e * 3 + 0];
1191                                 v[10] = normal3f[e * 3 + 1];
1192                                 v[11] = normal3f[e * 3 + 2];
1193                         }
1194                         if (texcoord2f)
1195                         {
1196                                 v[12] = texcoord2f[e * 2 + 0];
1197                                 v[13] = texcoord2f[e * 2 + 1];
1198                         }
1199                 }
1200                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1201         }
1202
1203         // the triangle calculation can take a while, so let's do a keepalive here
1204         CL_KeepaliveMessage(false);
1205 }
1206
1207 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)
1208 {
1209         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1210         CL_KeepaliveMessage(false);
1211
1212         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1213 }
1214
1215 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh, mempool_t *mempool)
1216 {
1217         if (!mesh->numverts)
1218                 return;
1219
1220         // build r_vertexmesh_t array
1221         // (compressed interleaved array for D3D)
1222         if (!mesh->vertexmesh && mesh->texcoord2f && vid.useinterleavedarrays)
1223         {
1224                 int vertexindex;
1225                 int numvertices = mesh->numverts;
1226                 r_vertexmesh_t *vertexmesh;
1227                 mesh->vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(mempool, numvertices * sizeof(*mesh->vertexmesh));
1228                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
1229                 {
1230                         VectorCopy(mesh->vertex3f + 3*vertexindex, vertexmesh->vertex3f);
1231                         VectorScale(mesh->svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
1232                         VectorScale(mesh->tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
1233                         VectorScale(mesh->normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
1234                         Vector2Copy(mesh->texcoord2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
1235                 }
1236         }
1237
1238         // upload r_vertexmesh_t array as a buffer
1239         if (mesh->vertexmesh && !mesh->vertexmeshbuffer)
1240                 mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false, false);
1241
1242         // upload vertex3f array as a buffer
1243         if (mesh->vertex3f && !mesh->vertex3fbuffer)
1244                 mesh->vertex3fbuffer = R_Mesh_CreateMeshBuffer(mesh->vertex3f, mesh->numverts * sizeof(float[3]), loadmodel->name, false, false, false);
1245
1246         // upload short indices as a buffer
1247         if (mesh->element3s && !mesh->element3s_indexbuffer)
1248                 mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false, true);
1249
1250         // upload int indices as a buffer
1251         if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
1252                 mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false, false);
1253
1254         // vertex buffer is several arrays and we put them in the same buffer
1255         //
1256         // is this wise?  the texcoordtexture2f array is used with dynamic
1257         // vertex/svector/tvector/normal when rendering animated models, on the
1258         // other hand animated models don't use a lot of vertices anyway...
1259         if (!mesh->vbo_vertexbuffer && !vid.useinterleavedarrays)
1260         {
1261                 size_t size;
1262                 unsigned char *mem;
1263                 size = 0;
1264                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1265                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1266                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1267                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1268                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1269                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1270                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1271                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1272                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1273                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1274                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1275                 mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false, false);
1276                 Mem_Free(mem);
1277         }
1278 }
1279
1280 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1281 {
1282         shadowmesh_t *mesh, *newmesh, *nextmesh;
1283         // reallocate meshs to conserve space
1284         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1285         {
1286                 nextmesh = mesh->next;
1287                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1288                 {
1289                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1290                         newmesh->next = firstmesh;
1291                         firstmesh = newmesh;
1292                         if (newmesh->element3s)
1293                         {
1294                                 int i;
1295                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1296                                         newmesh->element3s[i] = newmesh->element3i[i];
1297                         }
1298                         if (createvbo)
1299                                 Mod_ShadowMesh_CreateVBOs(newmesh, mempool);
1300                 }
1301                 Mem_Free(mesh);
1302         }
1303
1304         // this can take a while, so let's do a keepalive here
1305         CL_KeepaliveMessage(false);
1306
1307         return firstmesh;
1308 }
1309
1310 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1311 {
1312         int i;
1313         shadowmesh_t *mesh;
1314         vec3_t nmins, nmaxs, ncenter, temp;
1315         float nradius2, dist2, *v;
1316         VectorClear(nmins);
1317         VectorClear(nmaxs);
1318         // calculate bbox
1319         for (mesh = firstmesh;mesh;mesh = mesh->next)
1320         {
1321                 if (mesh == firstmesh)
1322                 {
1323                         VectorCopy(mesh->vertex3f, nmins);
1324                         VectorCopy(mesh->vertex3f, nmaxs);
1325                 }
1326                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1327                 {
1328                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1329                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1330                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1331                 }
1332         }
1333         // calculate center and radius
1334         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1335         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1336         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1337         nradius2 = 0;
1338         for (mesh = firstmesh;mesh;mesh = mesh->next)
1339         {
1340                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1341                 {
1342                         VectorSubtract(v, ncenter, temp);
1343                         dist2 = DotProduct(temp, temp);
1344                         if (nradius2 < dist2)
1345                                 nradius2 = dist2;
1346                 }
1347         }
1348         // return data
1349         if (mins)
1350                 VectorCopy(nmins, mins);
1351         if (maxs)
1352                 VectorCopy(nmaxs, maxs);
1353         if (center)
1354                 VectorCopy(ncenter, center);
1355         if (radius)
1356                 *radius = sqrt(nradius2);
1357 }
1358
1359 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1360 {
1361         shadowmesh_t *nextmesh;
1362         for (;mesh;mesh = nextmesh)
1363         {
1364                 if (mesh->vertex3fbuffer)
1365                         R_Mesh_DestroyMeshBuffer(mesh->vertex3fbuffer);
1366                 if (mesh->vertexmeshbuffer)
1367                         R_Mesh_DestroyMeshBuffer(mesh->vertexmeshbuffer);
1368                 if (mesh->element3i_indexbuffer)
1369                         R_Mesh_DestroyMeshBuffer(mesh->element3i_indexbuffer);
1370                 if (mesh->element3s_indexbuffer)
1371                         R_Mesh_DestroyMeshBuffer(mesh->element3s_indexbuffer);
1372                 if (mesh->vbo_vertexbuffer)
1373                         R_Mesh_DestroyMeshBuffer(mesh->vbo_vertexbuffer);
1374                 nextmesh = mesh->next;
1375                 Mem_Free(mesh);
1376         }
1377 }
1378
1379 void Mod_CreateCollisionMesh(dp_model_t *mod)
1380 {
1381         int k, numcollisionmeshtriangles;
1382         qboolean usesinglecollisionmesh = false;
1383         const msurface_t *surface = NULL;
1384
1385         mempool_t *mempool = mod->mempool;
1386         if (!mempool && mod->brush.parentmodel)
1387                 mempool = mod->brush.parentmodel->mempool;
1388         // make a single combined collision mesh for physics engine use
1389         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1390         numcollisionmeshtriangles = 0;
1391         for (k = 0;k < mod->nummodelsurfaces;k++)
1392         {
1393                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1394                 if (!strcmp(surface->texture->name, "collision")) // found collision mesh
1395                 {
1396                         usesinglecollisionmesh = true;
1397                         numcollisionmeshtriangles = surface->num_triangles;
1398                         break;
1399                 }
1400                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1401                         continue;
1402                 numcollisionmeshtriangles += surface->num_triangles;
1403         }
1404         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1405         if (usesinglecollisionmesh)
1406                 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));
1407         else
1408         {
1409                 for (k = 0;k < mod->nummodelsurfaces;k++)
1410                 {
1411                         surface = mod->data_surfaces + mod->firstmodelsurface + k;
1412                         if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1413                                 continue;
1414                         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));
1415                 }
1416         }
1417         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, false, false);
1418 }
1419
1420 #if 0
1421 static void Mod_GetTerrainVertex3fTexCoord2fFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1422 {
1423         float v[3], tc[3];
1424         v[0] = ix;
1425         v[1] = iy;
1426         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1427                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1428         else
1429                 v[2] = 0;
1430         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1431         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1432         texcoord2f[0] = tc[0];
1433         texcoord2f[1] = tc[1];
1434 }
1435
1436 static void Mod_GetTerrainVertexFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1437 {
1438         float vup[3], vdown[3], vleft[3], vright[3];
1439         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1440         float sv[3], tv[3], nl[3];
1441         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1442         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1443         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1444         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1445         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1446         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1447         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1448         VectorAdd(svector3f, sv, svector3f);
1449         VectorAdd(tvector3f, tv, tvector3f);
1450         VectorAdd(normal3f, nl, normal3f);
1451         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1452         VectorAdd(svector3f, sv, svector3f);
1453         VectorAdd(tvector3f, tv, tvector3f);
1454         VectorAdd(normal3f, nl, normal3f);
1455         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1456         VectorAdd(svector3f, sv, svector3f);
1457         VectorAdd(tvector3f, tv, tvector3f);
1458         VectorAdd(normal3f, nl, normal3f);
1459 }
1460
1461 static 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)
1462 {
1463         int x, y, ix, iy, *e;
1464         e = element3i;
1465         for (y = 0;y < height;y++)
1466         {
1467                 for (x = 0;x < width;x++)
1468                 {
1469                         e[0] = (y + 1) * (width + 1) + (x + 0);
1470                         e[1] = (y + 0) * (width + 1) + (x + 0);
1471                         e[2] = (y + 1) * (width + 1) + (x + 1);
1472                         e[3] = (y + 0) * (width + 1) + (x + 0);
1473                         e[4] = (y + 0) * (width + 1) + (x + 1);
1474                         e[5] = (y + 1) * (width + 1) + (x + 1);
1475                         e += 6;
1476                 }
1477         }
1478         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1479         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1480                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1481                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1482 }
1483 #endif
1484
1485 #if 0
1486 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1487 {
1488         float mins[3];
1489         float maxs[3];
1490         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1491         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1492         float viewvector[3];
1493         unsigned int firstvertex;
1494         unsigned int *e;
1495         float *v;
1496         if (chunkwidth < 2 || chunkheight < 2)
1497                 return;
1498         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]);
1499         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]);
1500         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1501         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1502         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1503         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1504         {
1505                 // too close for this stepsize, emit as 4 chunks instead
1506                 stepsize /= 2;
1507                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1508                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1509                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1510                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1511                 return;
1512         }
1513         // emit the geometry at stepsize into our vertex buffer / index buffer
1514         // we add two columns and two rows for skirt
1515         outwidth = chunkwidth+2;
1516         outheight = chunkheight+2;
1517         outwidth2 = outwidth-1;
1518         outheight2 = outheight-1;
1519         outwidth3 = outwidth+1;
1520         outheight3 = outheight+1;
1521         firstvertex = numvertices;
1522         e = model->terrain.element3i + numtriangles;
1523         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1524         v = model->terrain.vertex3f + numvertices;
1525         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1526         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1527         for (ty = 0;ty < outheight;ty++)
1528         {
1529                 for (tx = 0;tx < outwidth;tx++)
1530                 {
1531                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1532                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1533                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1534                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1535                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1536                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1537                 }
1538         }
1539         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1540         for (ty = 0;ty <= outheight;ty++)
1541         {
1542                 skirtrow = ty == 0 || ty == outheight;
1543                 ry = y+bound(1, ty, outheight)*stepsize;
1544                 for (tx = 0;tx <= outwidth;tx++)
1545                 {
1546                         skirt = skirtrow || tx == 0 || tx == outwidth;
1547                         rx = x+bound(1, tx, outwidth)*stepsize;
1548                         v[0] = rx*scale[0];
1549                         v[1] = ry*scale[1];
1550                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1551                         v += 3;
1552                 }
1553         }
1554         // TODO: emit skirt vertices
1555 }
1556
1557 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1558 {
1559         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1560         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1561         Mod_Terrain_BuildChunk(model, 
1562 }
1563 #endif
1564
1565 static int Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1566 {
1567         int offset = 0;
1568         if (!strncasecmp(s, "user", 4)) // parse stuff like "user1sin", always user<n>func
1569         {
1570                 offset = bound(0, s[4] - '0', 9);
1571                 offset = (offset + 1) << Q3WAVEFUNC_USER_SHIFT;
1572                 s += 4;
1573                 if(*s)
1574                         ++s;
1575         }
1576         if (!strcasecmp(s, "sin"))             return offset | Q3WAVEFUNC_SIN;
1577         if (!strcasecmp(s, "square"))          return offset | Q3WAVEFUNC_SQUARE;
1578         if (!strcasecmp(s, "triangle"))        return offset | Q3WAVEFUNC_TRIANGLE;
1579         if (!strcasecmp(s, "sawtooth"))        return offset | Q3WAVEFUNC_SAWTOOTH;
1580         if (!strcasecmp(s, "inversesawtooth")) return offset | Q3WAVEFUNC_INVERSESAWTOOTH;
1581         if (!strcasecmp(s, "noise"))           return offset | Q3WAVEFUNC_NOISE;
1582         if (!strcasecmp(s, "none"))            return offset | Q3WAVEFUNC_NONE;
1583         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1584         return offset | Q3WAVEFUNC_NONE;
1585 }
1586
1587 void Mod_FreeQ3Shaders(void)
1588 {
1589         Mem_FreePool(&q3shaders_mem);
1590 }
1591
1592 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1593 {
1594         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1595         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1596         q3shader_hash_entry_t* lastEntry = NULL;
1597         while (entry != NULL)
1598         {
1599                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1600                 {
1601                         // redeclaration
1602                         if(shader->dpshaderkill)
1603                         {
1604                                 // killed shader is a redeclarion? we can safely ignore it
1605                                 return;
1606                         }
1607                         else if(entry->shader.dpshaderkill)
1608                         {
1609                                 // replace the old shader!
1610                                 // this will skip the entry allocating part
1611                                 // below and just replace the shader
1612                                 break;
1613                         }
1614                         else
1615                         {
1616                                 unsigned char *start, *end, *start2;
1617                                 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1618                                 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1619                                 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1620                                 if(memcmp(start, start2, end - start))
1621                                         Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1622                                 else
1623                                         Con_DPrintf("Shader '%s' already defined\n", shader->name);
1624                                 return;
1625                         }
1626                 }
1627                 lastEntry = entry;
1628                 entry = entry->chain;
1629         }
1630         if (entry == NULL)
1631         {
1632                 if (lastEntry->shader.name[0] != 0)
1633                 {
1634                         /* Add to chain */
1635                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1636                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1637
1638                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1639                         lastEntry->chain = newEntry;
1640                         newEntry->chain = NULL;
1641                         lastEntry = newEntry;
1642                 }
1643                 /* else: head of chain, in hash entry array */
1644                 entry = lastEntry;
1645         }
1646         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1647 }
1648
1649 extern cvar_t mod_noshader_default_offsetmapping;
1650 extern cvar_t mod_q3shader_default_offsetmapping;
1651 extern cvar_t mod_q3shader_default_offsetmapping_scale;
1652 extern cvar_t mod_q3shader_default_offsetmapping_bias;
1653 extern cvar_t mod_q3shader_default_polygonoffset;
1654 extern cvar_t mod_q3shader_default_polygonfactor;
1655 extern cvar_t mod_q3shader_force_addalpha;
1656 void Mod_LoadQ3Shaders(void)
1657 {
1658         int j;
1659         int fileindex;
1660         fssearch_t *search;
1661         char *f;
1662         const char *text;
1663         q3shaderinfo_t shader;
1664         q3shaderinfo_layer_t *layer;
1665         int numparameters;
1666         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1667         char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1668         unsigned long custsurfaceflags[256]; 
1669         int numcustsurfaceflags;
1670         qboolean dpshaderkill;
1671
1672         Mod_FreeQ3Shaders();
1673
1674         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1675         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1676                 sizeof (q3shader_data_t));
1677         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1678                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1679         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1680                 q3shaders_mem, sizeof (char**), 256);
1681
1682         // parse custinfoparms.txt
1683         numcustsurfaceflags = 0;
1684         if ((text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL)) != NULL)
1685         {
1686                 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1687                         Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1688                 else
1689                 {
1690                         while (COM_ParseToken_QuakeC(&text, false))
1691                                 if (!strcasecmp(com_token, "}"))
1692                                         break;
1693                         // custom surfaceflags section
1694                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1695                                 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1696                         else
1697                         {
1698                                 while(COM_ParseToken_QuakeC(&text, false))
1699                                 {
1700                                         if (!strcasecmp(com_token, "}"))
1701                                                 break;  
1702                                         // register surfaceflag
1703                                         if (numcustsurfaceflags >= 256)
1704                                         {
1705                                                 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1706                                                 break;
1707                                         }
1708                                         // name
1709                                         j = strlen(com_token)+1;
1710                                         custsurfaceparmnames[numcustsurfaceflags] = (char *)Mem_Alloc(tempmempool, j);
1711                                         strlcpy(custsurfaceparmnames[numcustsurfaceflags], com_token, j+1);
1712                                         // value
1713                                         if (COM_ParseToken_QuakeC(&text, false))
1714                                                 custsurfaceflags[numcustsurfaceflags] = strtol(com_token, NULL, 0);
1715                                         else
1716                                                 custsurfaceflags[numcustsurfaceflags] = 0;
1717                                         numcustsurfaceflags++;
1718                                 }
1719                         }
1720                 }
1721                 Mem_Free(f);
1722         }
1723
1724         // parse shaders
1725         search = FS_Search("scripts/*.shader", true, false);
1726         if (!search)
1727                 return;
1728         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1729         {
1730                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1731                 if (!f)
1732                         continue;
1733                 while (COM_ParseToken_QuakeC(&text, false))
1734                 {
1735                         memset (&shader, 0, sizeof(shader));
1736                         shader.reflectmin = 0;
1737                         shader.reflectmax = 1;
1738                         shader.refractfactor = 1;
1739                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1740                         shader.reflectfactor = 1;
1741                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1742                         shader.r_water_wateralpha = 1;
1743                         shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1744                         shader.offsetscale = mod_q3shader_default_offsetmapping_scale.value;
1745                         shader.offsetbias = mod_q3shader_default_offsetmapping_bias.value;
1746                         shader.specularscalemod = 1;
1747                         shader.specularpowermod = 1;
1748                         shader.biaspolygonoffset = mod_q3shader_default_polygonoffset.value;
1749                         shader.biaspolygonfactor = mod_q3shader_default_polygonfactor.value;
1750
1751                         strlcpy(shader.name, com_token, sizeof(shader.name));
1752                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1753                         {
1754                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1755                                 break;
1756                         }
1757                         while (COM_ParseToken_QuakeC(&text, false))
1758                         {
1759                                 if (!strcasecmp(com_token, "}"))
1760                                         break;
1761                                 if (!strcasecmp(com_token, "{"))
1762                                 {
1763                                         static q3shaderinfo_layer_t dummy;
1764                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1765                                         {
1766                                                 layer = shader.layers + shader.numlayers++;
1767                                         }
1768                                         else
1769                                         {
1770                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1771                                                 memset(&dummy, 0, sizeof(dummy));
1772                                                 layer = &dummy;
1773                                         }
1774                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1775                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1776                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1777                                         layer->blendfunc[0] = GL_ONE;
1778                                         layer->blendfunc[1] = GL_ZERO;
1779                                         while (COM_ParseToken_QuakeC(&text, false))
1780                                         {
1781                                                 if (!strcasecmp(com_token, "}"))
1782                                                         break;
1783                                                 if (!strcasecmp(com_token, "\n"))
1784                                                         continue;
1785                                                 numparameters = 0;
1786                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1787                                                 {
1788                                                         if (j < TEXTURE_MAXFRAMES + 4)
1789                                                         {
1790                                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1791                                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1792                                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1793                                                                 else
1794                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1795                                                                 numparameters = j + 1;
1796                                                         }
1797                                                         if (!COM_ParseToken_QuakeC(&text, true))
1798                                                                 break;
1799                                                 }
1800                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1801                                                 //      parameter[j][0] = 0;
1802                                                 if (developer_insane.integer)
1803                                                 {
1804                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1805                                                         for (j = 0;j < numparameters;j++)
1806                                                                 Con_DPrintf(" %s", parameter[j]);
1807                                                         Con_DPrint("\n");
1808                                                 }
1809                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1810                                                 {
1811                                                         if (numparameters == 2)
1812                                                         {
1813                                                                 if (!strcasecmp(parameter[1], "add"))
1814                                                                 {
1815                                                                         layer->blendfunc[0] = GL_ONE;
1816                                                                         layer->blendfunc[1] = GL_ONE;
1817                                                                 }
1818                                                                 else if (!strcasecmp(parameter[1], "addalpha"))
1819                                                                 {
1820                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1821                                                                         layer->blendfunc[1] = GL_ONE;
1822                                                                 }
1823                                                                 else if (!strcasecmp(parameter[1], "filter"))
1824                                                                 {
1825                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1826                                                                         layer->blendfunc[1] = GL_ZERO;
1827                                                                 }
1828                                                                 else if (!strcasecmp(parameter[1], "blend"))
1829                                                                 {
1830                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1831                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1832                                                                 }
1833                                                         }
1834                                                         else if (numparameters == 3)
1835                                                         {
1836                                                                 int k;
1837                                                                 for (k = 0;k < 2;k++)
1838                                                                 {
1839                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1840                                                                                 layer->blendfunc[k] = GL_ONE;
1841                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1842                                                                                 layer->blendfunc[k] = GL_ZERO;
1843                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1844                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1845                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1846                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1847                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1848                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1849                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1850                                                                                 layer->blendfunc[k] = GL_DST_ALPHA;
1851                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1852                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1853                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1854                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1855                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1856                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1857                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1858                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1859                                                                         else
1860                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1861                                                                 }
1862                                                         }
1863                                                 }
1864                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1865                                                         layer->alphatest = true;
1866                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1867                                                 {
1868                                                         if (!strcasecmp(parameter[0], "clampmap"))
1869                                                                 layer->clampmap = true;
1870                                                         layer->numframes = 1;
1871                                                         layer->framerate = 1;
1872                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1873                                                                 &q3shader_data->char_ptrs);
1874                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1875                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1876                                                                 shader.lighting = true;
1877                                                 }
1878                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1879                                                 {
1880                                                         int i;
1881                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1882                                                         layer->framerate = atof(parameter[1]);
1883                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1884                                                         for (i = 0;i < layer->numframes;i++)
1885                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1886                                                 }
1887                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1888                                                 {
1889                                                         int i;
1890                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1891                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1892                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1893                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1894                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1895                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1896                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1897                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1898                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1899                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1900                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1901                                                         else if (!strcasecmp(parameter[1], "wave"))
1902                                                         {
1903                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1904                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1905                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1906                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1907                                                         }
1908                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1909                                                 }
1910                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1911                                                 {
1912                                                         int i;
1913                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1914                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1915                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1916                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1917                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1918                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1919                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1920                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1921                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1922                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1923                                                         else if (!strcasecmp(parameter[1], "wave"))
1924                                                         {
1925                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1926                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1927                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1928                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1929                                                         }
1930                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1931                                                 }
1932                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1933                                                 {
1934                                                         int i;
1935                                                         // observed values: tcgen environment
1936                                                         // no other values have been observed in real shaders
1937                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1938                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1939                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1940                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1941                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1942                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1943                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1944                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1945                                                 }
1946                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1947                                                 {
1948                                                         int i, tcmodindex;
1949                                                         // observed values:
1950                                                         // tcmod rotate #
1951                                                         // tcmod scale # #
1952                                                         // tcmod scroll # #
1953                                                         // tcmod stretch sin # # # #
1954                                                         // tcmod stretch triangle # # # #
1955                                                         // tcmod transform # # # # # #
1956                                                         // tcmod turb # # # #
1957                                                         // tcmod turb sin # # # #  (this is bogus)
1958                                                         // no other values have been observed in real shaders
1959                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1960                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1961                                                                         break;
1962                                                         if (tcmodindex < Q3MAXTCMODS)
1963                                                         {
1964                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1965                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1966                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1967                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1968                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1969                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1970                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1971                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1972                                                                 {
1973                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1974                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1975                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1976                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1977                                                                 }
1978                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1979                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1980                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1981                                                         }
1982                                                         else
1983                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1984                                                 }
1985                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1986                                                 if (!strcasecmp(com_token, "}"))
1987                                                         break;
1988                                         }
1989                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1990                                                 shader.lighting = true;
1991                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1992                                         {
1993                                                 if (layer == shader.layers + 0)
1994                                                 {
1995                                                         // vertex controlled transparency
1996                                                         shader.vertexalpha = true;
1997                                                 }
1998                                                 else
1999                                                 {
2000                                                         // multilayer terrain shader or similar
2001                                                         shader.textureblendalpha = true;
2002                                                 }
2003                                         }
2004
2005                                         if(mod_q3shader_force_addalpha.integer)
2006                                         {
2007                                                 // for a long while, DP treated GL_ONE GL_ONE as GL_SRC_ALPHA GL_ONE
2008                                                 // this cvar brings back this behaviour
2009                                                 if(layer->blendfunc[0] == GL_ONE && layer->blendfunc[1] == GL_ONE)
2010                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
2011                                         }
2012
2013                                         layer->texflags = 0;
2014                                         if (layer->alphatest)
2015                                                 layer->texflags |= TEXF_ALPHA;
2016                                         switch(layer->blendfunc[0])
2017                                         {
2018                                                 case GL_SRC_ALPHA:
2019                                                 case GL_ONE_MINUS_SRC_ALPHA:
2020                                                         layer->texflags |= TEXF_ALPHA;
2021                                                         break;
2022                                         }
2023                                         switch(layer->blendfunc[1])
2024                                         {
2025                                                 case GL_SRC_ALPHA:
2026                                                 case GL_ONE_MINUS_SRC_ALPHA:
2027                                                         layer->texflags |= TEXF_ALPHA;
2028                                                         break;
2029                                         }
2030                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
2031                                                 layer->texflags |= TEXF_MIPMAP;
2032                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
2033                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
2034                                         if (layer->clampmap)
2035                                                 layer->texflags |= TEXF_CLAMP;
2036                                         continue;
2037                                 }
2038                                 numparameters = 0;
2039                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
2040                                 {
2041                                         if (j < TEXTURE_MAXFRAMES + 4)
2042                                         {
2043                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
2044                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
2045                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
2046                                                 else
2047                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
2048                                                 numparameters = j + 1;
2049                                         }
2050                                         if (!COM_ParseToken_QuakeC(&text, true))
2051                                                 break;
2052                                 }
2053                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
2054                                 //      parameter[j][0] = 0;
2055                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
2056                                         break;
2057                                 if (developer_insane.integer)
2058                                 {
2059                                         Con_DPrintf("%s: ", shader.name);
2060                                         for (j = 0;j < numparameters;j++)
2061                                                 Con_DPrintf(" %s", parameter[j]);
2062                                         Con_DPrint("\n");
2063                                 }
2064                                 if (numparameters < 1)
2065                                         continue;
2066                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
2067                                 {
2068                                         if (!strcasecmp(parameter[1], "alphashadow"))
2069                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
2070                                         else if (!strcasecmp(parameter[1], "areaportal"))
2071                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
2072                                         else if (!strcasecmp(parameter[1], "botclip"))
2073                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
2074                                         else if (!strcasecmp(parameter[1], "clusterportal"))
2075                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
2076                                         else if (!strcasecmp(parameter[1], "detail"))
2077                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
2078                                         else if (!strcasecmp(parameter[1], "donotenter"))
2079                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
2080                                         else if (!strcasecmp(parameter[1], "dust"))
2081                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
2082                                         else if (!strcasecmp(parameter[1], "hint"))
2083                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
2084                                         else if (!strcasecmp(parameter[1], "fog"))
2085                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
2086                                         else if (!strcasecmp(parameter[1], "lava"))
2087                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
2088                                         else if (!strcasecmp(parameter[1], "lightfilter"))
2089                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
2090                                         else if (!strcasecmp(parameter[1], "lightgrid"))
2091                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
2092                                         else if (!strcasecmp(parameter[1], "metalsteps"))
2093                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
2094                                         else if (!strcasecmp(parameter[1], "nodamage"))
2095                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
2096                                         else if (!strcasecmp(parameter[1], "nodlight"))
2097                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
2098                                         else if (!strcasecmp(parameter[1], "nodraw"))
2099                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
2100                                         else if (!strcasecmp(parameter[1], "nodrop"))
2101                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
2102                                         else if (!strcasecmp(parameter[1], "noimpact"))
2103                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
2104                                         else if (!strcasecmp(parameter[1], "nolightmap"))
2105                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
2106                                         else if (!strcasecmp(parameter[1], "nomarks"))
2107                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
2108                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
2109                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2110                                         else if (!strcasecmp(parameter[1], "nonsolid"))
2111                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
2112                                         else if (!strcasecmp(parameter[1], "origin"))
2113                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
2114                                         else if (!strcasecmp(parameter[1], "playerclip"))
2115                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
2116                                         else if (!strcasecmp(parameter[1], "sky"))
2117                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2118                                         else if (!strcasecmp(parameter[1], "slick"))
2119                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
2120                                         else if (!strcasecmp(parameter[1], "slime"))
2121                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
2122                                         else if (!strcasecmp(parameter[1], "structural"))
2123                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
2124                                         else if (!strcasecmp(parameter[1], "trans"))
2125                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
2126                                         else if (!strcasecmp(parameter[1], "water"))
2127                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
2128                                         else if (!strcasecmp(parameter[1], "pointlight"))
2129                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
2130                                         else if (!strcasecmp(parameter[1], "antiportal"))
2131                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
2132                                         else if (!strcasecmp(parameter[1], "skip"))
2133                                                 ; // shader.surfaceparms |= Q3SURFACEPARM_SKIP; FIXME we don't have enough #defines for this any more, and the engine doesn't need this one anyway
2134                                         else
2135                                         {
2136                                                 // try custom surfaceparms
2137                                                 for (j = 0; j < numcustsurfaceflags; j++)
2138                                                 {
2139                                                         if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
2140                                                         {
2141                                                                 shader.surfaceflags |= custsurfaceflags[j];
2142                                                                 break;
2143                                                         }
2144                                                 }
2145                                                 // failed all
2146                                                 if (j == numcustsurfaceflags)
2147                                                         Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
2148                                         }
2149                                 }
2150                                 else if (!strcasecmp(parameter[0], "dpshadow"))
2151                                         shader.dpshadow = true;
2152                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
2153                                         shader.dpnoshadow = true;
2154                                 else if (!strcasecmp(parameter[0], "dpnortlight"))
2155                                         shader.dpnortlight = true;
2156                                 else if (!strcasecmp(parameter[0], "dpreflectcube"))
2157                                         strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
2158                                 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
2159                                         shader.dpmeshcollisions = true;
2160                                 // this sets dpshaderkill to true if dpshaderkillifcvarzero was used, and to false if dpnoshaderkillifcvarzero was used
2161                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvarzero")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvarzero")) && numparameters >= 2)
2162                                 {
2163                                         if (Cvar_VariableValue(parameter[1]) == 0.0f)
2164                                                 shader.dpshaderkill = dpshaderkill;
2165                                 }
2166                                 // this sets dpshaderkill to true if dpshaderkillifcvar was used, and to false if dpnoshaderkillifcvar was used
2167                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvar")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvar")) && numparameters >= 2)
2168                                 {
2169                                         const char *op = NULL;
2170                                         if (numparameters >= 3)
2171                                                 op = parameter[2];
2172                                         if(!op)
2173                                         {
2174                                                 if (Cvar_VariableValue(parameter[1]) != 0.0f)
2175                                                         shader.dpshaderkill = dpshaderkill;
2176                                         }
2177                                         else if (numparameters >= 4 && !strcmp(op, "=="))
2178                                         {
2179                                                 if (Cvar_VariableValue(parameter[1]) == atof(parameter[3]))
2180                                                         shader.dpshaderkill = dpshaderkill;
2181                                         }
2182                                         else if (numparameters >= 4 && !strcmp(op, "!="))
2183                                         {
2184                                                 if (Cvar_VariableValue(parameter[1]) != atof(parameter[3]))
2185                                                         shader.dpshaderkill = dpshaderkill;
2186                                         }
2187                                         else if (numparameters >= 4 && !strcmp(op, ">"))
2188                                         {
2189                                                 if (Cvar_VariableValue(parameter[1]) > atof(parameter[3]))
2190                                                         shader.dpshaderkill = dpshaderkill;
2191                                         }
2192                                         else if (numparameters >= 4 && !strcmp(op, "<"))
2193                                         {
2194                                                 if (Cvar_VariableValue(parameter[1]) < atof(parameter[3]))
2195                                                         shader.dpshaderkill = dpshaderkill;
2196                                         }
2197                                         else if (numparameters >= 4 && !strcmp(op, ">="))
2198                                         {
2199                                                 if (Cvar_VariableValue(parameter[1]) >= atof(parameter[3]))
2200                                                         shader.dpshaderkill = dpshaderkill;
2201                                         }
2202                                         else if (numparameters >= 4 && !strcmp(op, "<="))
2203                                         {
2204                                                 if (Cvar_VariableValue(parameter[1]) <= atof(parameter[3]))
2205                                                         shader.dpshaderkill = dpshaderkill;
2206                                         }
2207                                         else
2208                                         {
2209                                                 Con_DPrintf("%s parsing warning: unknown dpshaderkillifcvar op \"%s\", or not enough arguments\n", search->filenames[fileindex], op);
2210                                         }
2211                                 }
2212                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2213                                 {
2214                                         // some q3 skies don't have the sky parm set
2215                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2216                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2217                                 }
2218                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2219                                 {
2220                                         // some q3 skies don't have the sky parm set
2221                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2222                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2223                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2224                                 }
2225                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2226                                 {
2227                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2228                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2229                                 }
2230                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
2231                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2232                                 else if (!strcasecmp(parameter[0], "nopicmip"))
2233                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2234                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
2235                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2236                                 else if (!strcasecmp(parameter[0], "dppolygonoffset"))
2237                                 {
2238                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2239                                         if(numparameters >= 2)
2240                                         {
2241                                                 shader.biaspolygonfactor = atof(parameter[1]);
2242                                                 if(numparameters >= 3)
2243                                                         shader.biaspolygonoffset = atof(parameter[2]);
2244                                                 else
2245                                                         shader.biaspolygonoffset = 0;
2246                                         }
2247                                 }
2248                                 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2249                                 {
2250                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2251                                         shader.refractfactor = atof(parameter[1]);
2252                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2253                                 }
2254                                 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2255                                 {
2256                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2257                                         shader.reflectfactor = atof(parameter[1]);
2258                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2259                                 }
2260                                 else if (!strcasecmp(parameter[0], "dpcamera"))
2261                                 {
2262                                         shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2263                                 }
2264                                 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2265                                 {
2266                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2267                                         shader.reflectmin = atof(parameter[1]);
2268                                         shader.reflectmax = atof(parameter[2]);
2269                                         shader.refractfactor = atof(parameter[3]);
2270                                         shader.reflectfactor = atof(parameter[4]);
2271                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2272                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2273                                         shader.r_water_wateralpha = atof(parameter[11]);
2274                                 }
2275                                 else if (!strcasecmp(parameter[0], "dpwaterscroll") && numparameters >= 3)
2276                                 {
2277                                         shader.r_water_waterscroll[0] = 1/atof(parameter[1]);
2278                                         shader.r_water_waterscroll[1] = 1/atof(parameter[2]);
2279                                 }
2280                                 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2281                                 {
2282                                         shader.specularscalemod = atof(parameter[1]);
2283                                 }
2284                                 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2285                                 {
2286                                         shader.specularpowermod = atof(parameter[1]);
2287                                 }
2288                                 else if (!strcasecmp(parameter[0], "dprtlightambient") && numparameters >= 2)
2289                                 {
2290                                         shader.rtlightambient = atof(parameter[1]);
2291                                 }
2292                                 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 2)
2293                                 {
2294                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2295                                                 shader.offsetmapping = OFFSETMAPPING_OFF;
2296                                         else if (!strcasecmp(parameter[1], "default") || !strcasecmp(parameter[1], "normal"))
2297                                                 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2298                                         else if (!strcasecmp(parameter[1], "linear"))
2299                                                 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2300                                         else if (!strcasecmp(parameter[1], "relief"))
2301                                                 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2302                                         if (numparameters >= 3)
2303                                                 shader.offsetscale = atof(parameter[2]);
2304                                         if (numparameters >= 5)
2305                                         {
2306                                                 if(!strcasecmp(parameter[3], "bias"))
2307                                                         shader.offsetbias = atof(parameter[4]);
2308                                                 else if(!strcasecmp(parameter[3], "match"))
2309                                                         shader.offsetbias = 1.0f - atof(parameter[4]);
2310                                                 else if(!strcasecmp(parameter[3], "match8"))
2311                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 255.0f;
2312                                                 else if(!strcasecmp(parameter[3], "match16"))
2313                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 65535.0f;
2314                                         }
2315                                 }
2316                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2317                                 {
2318                                         int i, deformindex;
2319                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2320                                                 if (!shader.deforms[deformindex].deform)
2321                                                         break;
2322                                         if (deformindex < Q3MAXDEFORMS)
2323                                         {
2324                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2325                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2326                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2327                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2328                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2329                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2330                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2331                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2332                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2333                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2334                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2335                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2336                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2337                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2338                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2339                                                 else if (!strcasecmp(parameter[1], "wave"            ))
2340                                                 {
2341                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2342                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2343                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2344                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2345                                                 }
2346                                                 else if (!strcasecmp(parameter[1], "move"            ))
2347                                                 {
2348                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2349                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2350                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2351                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2352                                                 }
2353                                         }
2354                                 }
2355                         }
2356                         // hide this shader if a cvar said it should be killed
2357                         if (shader.dpshaderkill)
2358                                 shader.numlayers = 0;
2359                         // pick the primary layer to render with
2360                         if (shader.numlayers)
2361                         {
2362                                 shader.backgroundlayer = -1;
2363                                 shader.primarylayer = 0;
2364                                 // if lightmap comes first this is definitely an ordinary texture
2365                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2366                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
2367                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2368                                 {
2369                                         shader.backgroundlayer = -1;
2370                                         shader.primarylayer = 1;
2371                                 }
2372                                 else if (shader.numlayers >= 2
2373                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2374                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2375                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2376                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2377                                 {
2378                                         // terrain blending or other effects
2379                                         shader.backgroundlayer = 0;
2380                                         shader.primarylayer = 1;
2381                                 }
2382                         }
2383                         // fix up multiple reflection types
2384                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2385                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2386
2387                         Q3Shader_AddToHash (&shader);
2388                 }
2389                 Mem_Free(f);
2390         }
2391         FS_FreeSearch(search);
2392         // free custinfoparm values
2393         for (j = 0; j < numcustsurfaceflags; j++)
2394                 Mem_Free(custsurfaceparmnames[j]);
2395 }
2396
2397 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2398 {
2399         unsigned short hash;
2400         q3shader_hash_entry_t* entry;
2401         if (!q3shaders_mem)
2402                 Mod_LoadQ3Shaders();
2403         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2404         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2405         while (entry != NULL)
2406         {
2407                 if (strcasecmp (entry->shader.name, name) == 0)
2408                         return &entry->shader;
2409                 entry = entry->chain;
2410         }
2411         return NULL;
2412 }
2413
2414 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2415 {
2416         int j;
2417         int texflagsmask, texflagsor;
2418         qboolean success = true;
2419         q3shaderinfo_t *shader;
2420         if (!name)
2421                 name = "";
2422         strlcpy(texture->name, name, sizeof(texture->name));
2423         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2424
2425         texflagsmask = ~0;
2426         if(!(defaulttexflags & TEXF_PICMIP))
2427                 texflagsmask &= ~TEXF_PICMIP;
2428         if(!(defaulttexflags & TEXF_COMPRESS))
2429                 texflagsmask &= ~TEXF_COMPRESS;
2430         texflagsor = 0;
2431         if(defaulttexflags & TEXF_ISWORLD)
2432                 texflagsor |= TEXF_ISWORLD;
2433         if(defaulttexflags & TEXF_ISSPRITE)
2434                 texflagsor |= TEXF_ISSPRITE;
2435         // unless later loaded from the shader
2436         texture->offsetmapping = (mod_noshader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2437         texture->offsetscale = 1;
2438         texture->offsetbias = 0;
2439         texture->specularscalemod = 1;
2440         texture->specularpowermod = 1; 
2441         texture->rtlightambient = 0;
2442         // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2443         // HERE, AND Q1BSP LOADING
2444         // JUST GREP FOR "specularscalemod = 1".
2445
2446         if (shader)
2447         {
2448                 if (developer_loading.integer)
2449                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2450
2451                 // allow disabling of picmip or compression by defaulttexflags
2452                 texture->textureflags = (shader->textureflags & texflagsmask) | texflagsor;
2453
2454                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2455                 {
2456                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2457                         if (shader->skyboxname[0])
2458                         {
2459                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2460                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2461                         }
2462                 }
2463                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2464                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2465                 else
2466                         texture->basematerialflags = MATERIALFLAG_WALL;
2467
2468                 if (shader->layers[0].alphatest)
2469                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2470                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2471                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2472                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2473                 {
2474                         texture->biaspolygonoffset += shader->biaspolygonoffset;
2475                         texture->biaspolygonfactor += shader->biaspolygonfactor;
2476                 }
2477                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2478                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2479                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2480                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2481                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2482                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2483                 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2484                         texture->basematerialflags |= MATERIALFLAG_CAMERA;
2485                 texture->customblendfunc[0] = GL_ONE;
2486                 texture->customblendfunc[1] = GL_ZERO;
2487                 if (shader->numlayers > 0)
2488                 {
2489                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2490                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2491 /*
2492 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2493 * additive               GL_ONE GL_ONE
2494 additive weird         GL_ONE GL_SRC_ALPHA
2495 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2496 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2497 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2498 brighten               GL_DST_COLOR GL_ONE
2499 brighten               GL_ONE GL_SRC_COLOR
2500 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2501 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2502 * modulate               GL_DST_COLOR GL_ZERO
2503 * modulate               GL_ZERO GL_SRC_COLOR
2504 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2505 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2506 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2507 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2508 * no blend               GL_ONE GL_ZERO
2509 nothing                GL_ZERO GL_ONE
2510 */
2511                         // if not opaque, figure out what blendfunc to use
2512                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2513                         {
2514                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2515                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2516                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2517                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2518                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2519                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2520                                 else
2521                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2522                         }
2523                 }
2524                 if (!shader->lighting)
2525                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2526                 if (shader->primarylayer >= 0)
2527                 {
2528                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2529                         // copy over many primarylayer parameters
2530                         texture->rgbgen = primarylayer->rgbgen;
2531                         texture->alphagen = primarylayer->alphagen;
2532                         texture->tcgen = primarylayer->tcgen;
2533                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2534                         // load the textures
2535                         texture->numskinframes = primarylayer->numframes;
2536                         texture->skinframerate = primarylayer->framerate;
2537                         for (j = 0;j < primarylayer->numframes;j++)
2538                         {
2539                                 if(cls.state == ca_dedicated)
2540                                 {
2541                                         texture->skinframes[j] = NULL;
2542                                 }
2543                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], (primarylayer->texflags & texflagsmask) | texflagsor, false)))
2544                                 {
2545                                         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);
2546                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2547                                 }
2548                         }
2549                 }
2550                 if (shader->backgroundlayer >= 0)
2551                 {
2552                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2553                         // copy over one secondarylayer parameter
2554                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2555                         // load the textures
2556                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2557                         texture->backgroundskinframerate = backgroundlayer->framerate;
2558                         for (j = 0;j < backgroundlayer->numframes;j++)
2559                         {
2560                                 if(cls.state == ca_dedicated)
2561                                 {
2562                                         texture->skinframes[j] = NULL;
2563                                 }
2564                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], (backgroundlayer->texflags & texflagsmask) | texflagsor, false)))
2565                                 {
2566                                         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);
2567                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2568                                 }
2569                         }
2570                 }
2571                 if (shader->dpshadow)
2572                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2573                 if (shader->dpnoshadow)
2574                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2575                 if (shader->dpnortlight)
2576                         texture->basematerialflags |= MATERIALFLAG_NORTLIGHT;
2577                 if (shader->vertexalpha)
2578                         texture->basematerialflags |= MATERIALFLAG_ALPHAGEN_VERTEX;
2579                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2580                 texture->reflectmin = shader->reflectmin;
2581                 texture->reflectmax = shader->reflectmax;
2582                 texture->refractfactor = shader->refractfactor;
2583                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2584                 texture->reflectfactor = shader->reflectfactor;
2585                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2586                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2587                 Vector2Copy(shader->r_water_waterscroll, texture->r_water_waterscroll);
2588                 texture->offsetmapping = shader->offsetmapping;
2589                 texture->offsetscale = shader->offsetscale;
2590                 texture->offsetbias = shader->offsetbias;
2591                 texture->specularscalemod = shader->specularscalemod;
2592                 texture->specularpowermod = shader->specularpowermod;
2593                 texture->rtlightambient = shader->rtlightambient;
2594                 if (shader->dpreflectcube[0])
2595                         texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2596
2597                 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2598                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2599                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents  = SUPERCONTENTS_LAVA         ;
2600                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents  = SUPERCONTENTS_SLIME        ;
2601                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents  = SUPERCONTENTS_WATER        ;
2602                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents  = 0                          ;
2603                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents  = SUPERCONTENTS_PLAYERCLIP   ;
2604                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents  = SUPERCONTENTS_MONSTERCLIP  ;
2605                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents  = SUPERCONTENTS_SKY          ;
2606
2607         //      if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW  ;
2608         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL   ;
2609         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2610         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->supercontents |= SUPERCONTENTS_DETAIL       ;
2611                 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->supercontents |= SUPERCONTENTS_DONOTENTER   ;
2612         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->supercontents |= SUPERCONTENTS_FOG          ;
2613                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents |= SUPERCONTENTS_LAVA         ;
2614         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER  ;
2615         //      if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->supercontents |= SUPERCONTENTS_METALSTEPS   ;
2616         //      if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->supercontents |= SUPERCONTENTS_NODAMAGE     ;
2617         //      if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->supercontents |= SUPERCONTENTS_NODLIGHT     ;
2618         //      if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->supercontents |= SUPERCONTENTS_NODRAW       ;
2619                 if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->supercontents |= SUPERCONTENTS_NODROP       ;
2620         //      if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->supercontents |= SUPERCONTENTS_NOIMPACT     ;
2621         //      if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP   ;
2622         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->supercontents |= SUPERCONTENTS_NOMARKS      ;
2623         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS    ;
2624                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents &=~SUPERCONTENTS_SOLID        ;
2625         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->supercontents |= SUPERCONTENTS_ORIGIN       ;
2626                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP   ;
2627                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents |= SUPERCONTENTS_SKY          ;
2628         //      if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->supercontents |= SUPERCONTENTS_SLICK        ;
2629                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents |= SUPERCONTENTS_SLIME        ;
2630         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL   ;
2631         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->supercontents |= SUPERCONTENTS_TRANS        ;
2632                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents |= SUPERCONTENTS_WATER        ;
2633         //      if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT   ;
2634         //      if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->supercontents |= SUPERCONTENTS_HINT         ;
2635         //      if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->supercontents |= SUPERCONTENTS_DUST         ;
2636                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents |= SUPERCONTENTS_BOTCLIP      | SUPERCONTENTS_MONSTERCLIP;
2637         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID    ;
2638         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL   ;
2639
2640                 texture->surfaceflags = shader->surfaceflags;
2641                 if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->surfaceflags |= Q3SURFACEFLAG_ALPHASHADOW  ;
2642         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->surfaceflags |= Q3SURFACEFLAG_AREAPORTAL   ;
2643         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->surfaceflags |= Q3SURFACEFLAG_CLUSTERPORTAL;
2644         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->surfaceflags |= Q3SURFACEFLAG_DETAIL       ;
2645         //      if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->surfaceflags |= Q3SURFACEFLAG_DONOTENTER   ;
2646         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->surfaceflags |= Q3SURFACEFLAG_FOG          ;
2647         //      if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->surfaceflags |= Q3SURFACEFLAG_LAVA         ;
2648                 if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->surfaceflags |= Q3SURFACEFLAG_LIGHTFILTER  ;
2649                 if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->surfaceflags |= Q3SURFACEFLAG_METALSTEPS   ;
2650                 if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->surfaceflags |= Q3SURFACEFLAG_NODAMAGE     ;
2651                 if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->surfaceflags |= Q3SURFACEFLAG_NODLIGHT     ;
2652                 if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->surfaceflags |= Q3SURFACEFLAG_NODRAW       ;
2653         //      if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->surfaceflags |= Q3SURFACEFLAG_NODROP       ;
2654                 if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->surfaceflags |= Q3SURFACEFLAG_NOIMPACT     ;
2655                 if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->surfaceflags |= Q3SURFACEFLAG_NOLIGHTMAP   ;
2656                 if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->surfaceflags |= Q3SURFACEFLAG_NOMARKS      ;
2657         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->surfaceflags |= Q3SURFACEFLAG_NOMIPMAPS    ;
2658                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->surfaceflags |= Q3SURFACEFLAG_NONSOLID     ;
2659         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->surfaceflags |= Q3SURFACEFLAG_ORIGIN       ;
2660         //      if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->surfaceflags |= Q3SURFACEFLAG_PLAYERCLIP   ;
2661                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->surfaceflags |= Q3SURFACEFLAG_SKY          ;
2662                 if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->surfaceflags |= Q3SURFACEFLAG_SLICK        ;
2663         //      if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->surfaceflags |= Q3SURFACEFLAG_SLIME        ;
2664         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->surfaceflags |= Q3SURFACEFLAG_STRUCTURAL   ;
2665         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->surfaceflags |= Q3SURFACEFLAG_TRANS        ;
2666         //      if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->surfaceflags |= Q3SURFACEFLAG_WATER        ;
2667                 if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->surfaceflags |= Q3SURFACEFLAG_POINTLIGHT   ;
2668                 if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->surfaceflags |= Q3SURFACEFLAG_HINT         ;
2669                 if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->surfaceflags |= Q3SURFACEFLAG_DUST         ;
2670         //      if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->surfaceflags |= Q3SURFACEFLAG_BOTCLIP      ;
2671         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->surfaceflags |= Q3SURFACEFLAG_LIGHTGRID    ;
2672         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->surfaceflags |= Q3SURFACEFLAG_ANTIPORTAL   ;
2673
2674                 if (shader->dpmeshcollisions)
2675                         texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2676                 if (shader->dpshaderkill && developer_extra.integer)
2677                         Con_DPrintf("^1%s:^7 killing shader ^3\"%s\" because of cvar\n", loadmodel->name, name);
2678         }
2679         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2680         {
2681                 if (developer_extra.integer)
2682                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2683                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2684         }
2685         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2686         {
2687                 if (developer_extra.integer)
2688                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2689                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2690                 texture->supercontents = SUPERCONTENTS_SOLID;
2691         }
2692         else
2693         {
2694                 if (developer_extra.integer)
2695                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2696                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2697                 {
2698                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2699                         texture->supercontents = SUPERCONTENTS_SOLID;
2700                 }
2701                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2702                 {
2703                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2704                         texture->supercontents = SUPERCONTENTS_SKY;
2705                 }
2706                 else
2707                 {
2708                         texture->basematerialflags |= MATERIALFLAG_WALL;
2709                         texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2710                 }
2711                 texture->numskinframes = 1;
2712                 if(cls.state == ca_dedicated)
2713                 {
2714                         texture->skinframes[0] = NULL;
2715                         success = false;
2716                 }
2717                 else
2718                 {
2719                         if (fallback)
2720                         {
2721                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2722                                 {
2723                                         if(texture->skinframes[0]->hasalpha)
2724                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2725                                 }
2726                                 else
2727                                         success = false;
2728                         }
2729                         else
2730                                 success = false;
2731                         if (!success && warnmissing)
2732                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2733                 }
2734         }
2735         // init the animation variables
2736         texture->currentframe = texture;
2737         if (texture->numskinframes < 1)
2738                 texture->numskinframes = 1;
2739         if (!texture->skinframes[0])
2740                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2741         texture->currentskinframe = texture->skinframes[0];
2742         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2743         return success;
2744 }
2745
2746 skinfile_t *Mod_LoadSkinFiles(void)
2747 {
2748         int i, words, line, wordsoverflow;
2749         char *text;
2750         const char *data;
2751         skinfile_t *skinfile = NULL, *first = NULL;
2752         skinfileitem_t *skinfileitem;
2753         char word[10][MAX_QPATH];
2754         char vabuf[1024];
2755
2756 /*
2757 sample file:
2758 U_bodyBox,models/players/Legoman/BikerA2.tga
2759 U_RArm,models/players/Legoman/BikerA1.tga
2760 U_LArm,models/players/Legoman/BikerA1.tga
2761 U_armor,common/nodraw
2762 U_sword,common/nodraw
2763 U_shield,common/nodraw
2764 U_homb,common/nodraw
2765 U_backpack,common/nodraw
2766 U_colcha,common/nodraw
2767 tag_head,
2768 tag_weapon,
2769 tag_torso,
2770 */
2771         memset(word, 0, sizeof(word));
2772         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2773         {
2774                 // If it's the first file we parse
2775                 if (skinfile == NULL)
2776                 {
2777                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2778                         first = skinfile;
2779                 }
2780                 else
2781                 {
2782                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2783                         skinfile = skinfile->next;
2784                 }
2785                 skinfile->next = NULL;
2786
2787                 for(line = 0;;line++)
2788                 {
2789                         // parse line
2790                         if (!COM_ParseToken_QuakeC(&data, true))
2791                                 break;
2792                         if (!strcmp(com_token, "\n"))
2793                                 continue;
2794                         words = 0;
2795                         wordsoverflow = false;
2796                         do
2797                         {
2798                                 if (words < 10)
2799                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2800                                 else
2801                                         wordsoverflow = true;
2802                         }
2803                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2804                         if (wordsoverflow)
2805                         {
2806                                 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);
2807                                 continue;
2808                         }
2809                         // words is always >= 1
2810                         if (!strcmp(word[0], "replace"))
2811                         {
2812                                 if (words == 3)
2813                                 {
2814                                         if (developer_loading.integer)
2815                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2816                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2817                                         skinfileitem->next = skinfile->items;
2818                                         skinfile->items = skinfileitem;
2819                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2820                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2821                                 }
2822                                 else
2823                                         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]);
2824                         }
2825                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2826                         {
2827                                 // tag name, like "tag_weapon,"
2828                                 // not used for anything (not even in Quake3)
2829                         }
2830                         else if (words >= 2 && !strcmp(word[1], ","))
2831                         {
2832                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2833                                 if (developer_loading.integer)
2834                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2835                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2836                                 skinfileitem->next = skinfile->items;
2837                                 skinfile->items = skinfileitem;
2838                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2839                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2840                         }
2841                         else
2842                                 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);
2843                 }
2844                 Mem_Free(text);
2845         }
2846         if (i)
2847                 loadmodel->numskins = i;
2848         return first;
2849 }
2850
2851 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2852 {
2853         skinfile_t *next;
2854         skinfileitem_t *skinfileitem, *nextitem;
2855         for (;skinfile;skinfile = next)
2856         {
2857                 next = skinfile->next;
2858                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2859                 {
2860                         nextitem = skinfileitem->next;
2861                         Mem_Free(skinfileitem);
2862                 }
2863                 Mem_Free(skinfile);
2864         }
2865 }
2866
2867 int Mod_CountSkinFiles(skinfile_t *skinfile)
2868 {
2869         int i;
2870         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2871         return i;
2872 }
2873
2874 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2875 {
2876         int i;
2877         double isnap = 1.0 / snap;
2878         for (i = 0;i < numvertices*numcomponents;i++)
2879                 vertices[i] = floor(vertices[i]*isnap)*snap;
2880 }
2881
2882 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2883 {
2884         int i, outtriangles;
2885         float edgedir1[3], edgedir2[3], temp[3];
2886         // a degenerate triangle is one with no width (thickness, surface area)
2887         // these are characterized by having all 3 points colinear (along a line)
2888         // or having two points identical
2889         // the simplest check is to calculate the triangle's area
2890         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2891         {
2892                 // calculate first edge
2893                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2894                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2895                 CrossProduct(edgedir1, edgedir2, temp);
2896                 if (VectorLength2(temp) < 0.001f)
2897                         continue; // degenerate triangle (no area)
2898                 // valid triangle (has area)
2899                 VectorCopy(inelement3i, outelement3i);
2900                 outelement3i += 3;
2901                 outtriangles++;
2902         }
2903         return outtriangles;
2904 }
2905
2906 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2907 {
2908         int i, e;
2909         int firstvertex, lastvertex;
2910         if (numelements > 0 && elements)
2911         {
2912                 firstvertex = lastvertex = elements[0];
2913                 for (i = 1;i < numelements;i++)
2914                 {
2915                         e = elements[i];
2916                         firstvertex = min(firstvertex, e);
2917                         lastvertex = max(lastvertex, e);
2918                 }
2919         }
2920         else
2921                 firstvertex = lastvertex = 0;
2922         if (firstvertexpointer)
2923                 *firstvertexpointer = firstvertex;
2924         if (lastvertexpointer)
2925                 *lastvertexpointer = lastvertex;
2926 }
2927
2928 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2929 {
2930         // make an optimal set of texture-sorted batches to draw...
2931         int j, t;
2932         int *firstsurfacefortexture;
2933         int *numsurfacesfortexture;
2934         if (!mod->sortedmodelsurfaces)
2935                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2936         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2937         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2938         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2939         for (j = 0;j < mod->nummodelsurfaces;j++)
2940         {
2941                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2942                 int t = (int)(surface->texture - mod->data_textures);
2943                 numsurfacesfortexture[t]++;
2944         }
2945         j = 0;
2946         for (t = 0;t < mod->num_textures;t++)
2947         {
2948                 firstsurfacefortexture[t] = j;
2949                 j += numsurfacesfortexture[t];
2950         }
2951         for (j = 0;j < mod->nummodelsurfaces;j++)
2952         {
2953                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2954                 int t = (int)(surface->texture - mod->data_textures);
2955                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2956         }
2957         Mem_Free(firstsurfacefortexture);
2958         Mem_Free(numsurfacesfortexture);
2959 }
2960
2961 void Mod_BuildVBOs(void)
2962 {
2963         if (!loadmodel->surfmesh.num_vertices)
2964                 return;
2965
2966         if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2967         {
2968                 int i;
2969                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2970                 {
2971                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2972                         {
2973                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2974                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2975                         }
2976                 }
2977         }
2978
2979         // build r_vertexmesh_t array
2980         // (compressed interleaved array for D3D)
2981         if (!loadmodel->surfmesh.vertexmesh && vid.useinterleavedarrays)
2982         {
2983                 int vertexindex;
2984                 int numvertices = loadmodel->surfmesh.num_vertices;
2985                 r_vertexmesh_t *vertexmesh;
2986                 loadmodel->surfmesh.vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexmesh));
2987                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
2988                 {
2989                         VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexmesh->vertex3f);
2990                         VectorScale(loadmodel->surfmesh.data_svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
2991                         VectorScale(loadmodel->surfmesh.data_tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
2992                         VectorScale(loadmodel->surfmesh.data_normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
2993                         if (loadmodel->surfmesh.data_lightmapcolor4f)
2994                                 Vector4Copy(loadmodel->surfmesh.data_lightmapcolor4f + 4*vertexindex, vertexmesh->color4f);
2995                         Vector2Copy(loadmodel->surfmesh.data_texcoordtexture2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
2996                         if (loadmodel->surfmesh.data_texcoordlightmap2f)
2997                                 Vector2Scale(loadmodel->surfmesh.data_texcoordlightmap2f + 2*vertexindex, 1.0f, vertexmesh->texcoordlightmap2f);
2998                 }
2999         }
3000
3001         // upload r_vertexmesh_t array as a buffer
3002         if (loadmodel->surfmesh.vertexmesh && !loadmodel->surfmesh.vertexmeshbuffer)
3003                 loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false, false);
3004
3005         // upload vertex3f array as a buffer
3006         if (loadmodel->surfmesh.data_vertex3f && !loadmodel->surfmesh.vertex3fbuffer)
3007                 loadmodel->surfmesh.vertex3fbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.num_vertices * sizeof(float[3]), loadmodel->name, false, false, false);
3008
3009         // upload short indices as a buffer
3010         if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
3011                 loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false, true);
3012
3013         // upload int indices as a buffer
3014         if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
3015                 loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false, false);
3016
3017         // only build a vbo if one has not already been created (this is important for brush models which load specially)
3018         // vertex buffer is several arrays and we put them in the same buffer
3019         //
3020         // is this wise?  the texcoordtexture2f array is used with dynamic
3021         // vertex/svector/tvector/normal when rendering animated models, on the
3022         // other hand animated models don't use a lot of vertices anyway...
3023         if (!loadmodel->surfmesh.vbo_vertexbuffer && !vid.useinterleavedarrays)
3024         {
3025                 size_t size;
3026                 unsigned char *mem;
3027                 size = 0;
3028                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
3029                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
3030                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
3031                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
3032                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
3033                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
3034                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
3035                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
3036                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
3037                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
3038                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
3039                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
3040                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
3041                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
3042                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
3043                 loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false, false);
3044                 Mem_Free(mem);
3045         }
3046 }
3047
3048 extern cvar_t mod_obj_orientation;
3049 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
3050 {
3051         int submodelindex, vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
3052         int a, b, c;
3053         const char *texname;
3054         const int *e;
3055         const float *v, *vn, *vt;
3056         size_t l;
3057         size_t outbufferpos = 0;
3058         size_t outbuffermax = 0x100000;
3059         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
3060         const msurface_t *surface;
3061         const int maxtextures = 256;
3062         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
3063         dp_model_t *submodel;
3064
3065         // construct the mtllib file
3066         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
3067         if (l > 0)
3068                 outbufferpos += l;
3069         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3070         {
3071                 countsurfaces++;
3072                 countvertices += surface->num_vertices;
3073                 countfaces += surface->num_triangles;
3074                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
3075                 for (textureindex = 0;textureindex < counttextures;textureindex++)
3076                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
3077                                 break;
3078                 if (textureindex < counttextures)
3079                         continue; // already wrote this material entry
3080                 if (textureindex >= maxtextures)
3081                         continue; // just a precaution
3082                 textureindex = counttextures++;
3083                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
3084                 if (outbufferpos >= outbuffermax >> 1)
3085                 {
3086                         outbuffermax *= 2;
3087                         oldbuffer = outbuffer;
3088                         outbuffer = (char *) Z_Malloc(outbuffermax);
3089                         memcpy(outbuffer, oldbuffer, outbufferpos);
3090                         Z_Free(oldbuffer);
3091                 }
3092                 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");
3093                 if (l > 0)
3094                         outbufferpos += l;
3095         }
3096
3097         // write the mtllib file
3098         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
3099
3100         // construct the obj file
3101         outbufferpos = 0;
3102         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);
3103         if (l > 0)
3104                 outbufferpos += l;
3105
3106         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)
3107         {
3108                 if (outbufferpos >= outbuffermax >> 1)
3109                 {
3110                         outbuffermax *= 2;
3111                         oldbuffer = outbuffer;
3112                         outbuffer = (char *) Z_Malloc(outbuffermax);
3113                         memcpy(outbuffer, oldbuffer, outbufferpos);
3114                         Z_Free(oldbuffer);
3115                 }
3116                 if(mod_obj_orientation.integer)
3117                         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]);
3118                 else
3119                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1-vt[1]);
3120                 if (l > 0)
3121                         outbufferpos += l;
3122         }
3123
3124         for (submodelindex = 0;submodelindex < max(1, model->brush.numsubmodels);submodelindex++)
3125         {
3126                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "o %i\n", submodelindex);
3127                 if (l > 0)
3128                         outbufferpos += l;
3129                 submodel = model->brush.numsubmodels ? model->brush.submodels[submodelindex] : model;
3130                 for (surfaceindex = 0;surfaceindex < submodel->nummodelsurfaces;surfaceindex++)
3131                 {
3132                         surface = model->data_surfaces + submodel->sortedmodelsurfaces[surfaceindex];
3133                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
3134                         if (l > 0)
3135                                 outbufferpos += l;
3136                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3137                         {
3138                                 if (outbufferpos >= outbuffermax >> 1)
3139                                 {
3140                                         outbuffermax *= 2;
3141                                         oldbuffer = outbuffer;
3142                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3143                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3144                                         Z_Free(oldbuffer);
3145                                 }
3146                                 a = e[0]+1;
3147                                 b = e[1]+1;
3148                                 c = e[2]+1;
3149                                 if(mod_obj_orientation.integer)
3150                                         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);
3151                                 else
3152                                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,c,c,c,b,b,b);
3153                                 if (l > 0)
3154                                         outbufferpos += l;
3155                         }
3156                 }
3157         }
3158
3159         // write the obj file
3160         FS_WriteFile(filename, outbuffer, outbufferpos);
3161
3162         // clean up
3163         Z_Free(outbuffer);
3164         Z_Free(texturenames);
3165
3166         // print some stats
3167         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
3168 }
3169
3170 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
3171 {
3172         int countnodes = 0, counttriangles = 0, countframes = 0;
3173         int surfaceindex;
3174         int triangleindex;
3175         int transformindex;
3176         int poseindex;
3177         int cornerindex;
3178         const int *e;
3179         size_t l;
3180         size_t outbufferpos = 0;
3181         size_t outbuffermax = 0x100000;
3182         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
3183         const msurface_t *surface;
3184         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
3185         if (l > 0)
3186                 outbufferpos += l;
3187         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3188         {
3189                 if (outbufferpos >= outbuffermax >> 1)
3190                 {
3191                         outbuffermax *= 2;
3192                         oldbuffer = outbuffer;
3193                         outbuffer = (char *) Z_Malloc(outbuffermax);
3194                         memcpy(outbuffer, oldbuffer, outbufferpos);
3195                         Z_Free(oldbuffer);
3196                 }
3197                 countnodes++;
3198                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
3199                 if (l > 0)
3200                         outbufferpos += l;
3201         }
3202         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
3203         if (l > 0)
3204                 outbufferpos += l;
3205         for (poseindex = 0;poseindex < numposes;poseindex++)
3206         {
3207                 countframes++;
3208                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
3209                 if (l > 0)
3210                         outbufferpos += l;
3211                 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3212                 {
3213                         float angles[3];
3214                         float mtest[4][3];
3215                         matrix4x4_t posematrix;
3216                         if (outbufferpos >= outbuffermax >> 1)
3217                         {
3218                                 outbuffermax *= 2;
3219                                 oldbuffer = outbuffer;
3220                                 outbuffer = (char *) Z_Malloc(outbuffermax);
3221                                 memcpy(outbuffer, oldbuffer, outbufferpos);
3222                                 Z_Free(oldbuffer);
3223                         }
3224
3225                         // strangely the smd angles are for a transposed matrix, so we
3226                         // have to generate a transposed matrix, then convert that...
3227                         Matrix4x4_FromBonePose6s(&posematrix, model->num_posescale, model->data_poses6s + 6*(model->num_bones * poseindex + transformindex));
3228                         Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
3229                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
3230                         if (angles[0] >= 180) angles[0] -= 360;
3231                         if (angles[1] >= 180) angles[1] -= 360;
3232                         if (angles[2] >= 180) angles[2] -= 360;
3233
3234 #if 0
3235 {
3236                         float a = DEG2RAD(angles[ROLL]);
3237                         float b = DEG2RAD(angles[PITCH]);
3238                         float c = DEG2RAD(angles[YAW]);
3239                         float cy, sy, cp, sp, cr, sr;
3240                         float test[4][3];
3241                         // smd matrix construction, for comparing
3242                         sy = sin(c);
3243                         cy = cos(c);
3244                         sp = sin(b);
3245                         cp = cos(b);
3246                         sr = sin(a);
3247                         cr = cos(a);
3248
3249                         test[0][0] = cp*cy;
3250                         test[0][1] = cp*sy;
3251                         test[0][2] = -sp;
3252                         test[1][0] = sr*sp*cy+cr*-sy;
3253                         test[1][1] = sr*sp*sy+cr*cy;
3254                         test[1][2] = sr*cp;
3255                         test[2][0] = (cr*sp*cy+-sr*-sy);
3256                         test[2][1] = (cr*sp*sy+-sr*cy);
3257                         test[2][2] = cr*cp;
3258                         test[3][0] = pose[9];
3259                         test[3][1] = pose[10];
3260                         test[3][2] = pose[11];
3261 }
3262 #endif
3263                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, mtest[3][0], mtest[3][1], mtest[3][2], DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
3264                         if (l > 0)
3265                                 outbufferpos += l;
3266                 }
3267         }
3268         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3269         if (l > 0)
3270                 outbufferpos += l;
3271         if (writetriangles)
3272         {
3273                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
3274                 if (l > 0)
3275                         outbufferpos += l;
3276                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3277                 {
3278                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3279                         {
3280                                 counttriangles++;
3281                                 if (outbufferpos >= outbuffermax >> 1)
3282                                 {
3283                                         outbuffermax *= 2;
3284                                         oldbuffer = outbuffer;
3285                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3286                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3287                                         Z_Free(oldbuffer);
3288                                 }
3289                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
3290                                 if (l > 0)
3291                                         outbufferpos += l;
3292                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
3293                                 {
3294                                         const int index = e[2-cornerindex];
3295                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
3296                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
3297                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
3298                                         const int b = model->surfmesh.blends[index];
3299                                         if (b < model->num_bones)
3300                                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , b, v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
3301                                         else
3302                                         {
3303                                                 const blendweights_t *w = model->surfmesh.data_blendweights + b - model->num_bones;
3304                                                 const unsigned char *wi = w->index;
3305                                                 const unsigned char *wf = w->influence;
3306                                             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]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f, wi[3], wf[3]/255.0f);
3307                                                 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]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f);
3308                                                 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]/255.0f, wi[1], wf[1]/255.0f);
3309                                                 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]);
3310                                         }
3311                                         if (l > 0)
3312                                                 outbufferpos += l;
3313                                 }
3314                         }
3315                 }
3316                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3317                 if (l > 0)
3318                         outbufferpos += l;
3319         }
3320
3321         FS_WriteFile(filename, outbuffer, outbufferpos);
3322         Z_Free(outbuffer);
3323
3324         Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
3325 }
3326
3327 /*
3328 ================
3329 Mod_Decompile_f
3330
3331 decompiles a model to editable files
3332 ================
3333 */
3334 static void Mod_Decompile_f(void)
3335 {
3336         int i, j, k, l, first, count;
3337         dp_model_t *mod;
3338         char inname[MAX_QPATH];
3339         char outname[MAX_QPATH];
3340         char mtlname[MAX_QPATH];
3341         char basename[MAX_QPATH];
3342         char animname[MAX_QPATH];
3343         char animname2[MAX_QPATH];
3344         char zymtextbuffer[16384];
3345         char dpmtextbuffer[16384];
3346         char framegroupstextbuffer[16384];
3347         int zymtextsize = 0;
3348         int dpmtextsize = 0;
3349         int framegroupstextsize = 0;
3350         char vabuf[1024];
3351
3352         if (Cmd_Argc() != 2)
3353         {
3354                 Con_Print("usage: modeldecompile <filename>\n");
3355                 return;
3356         }
3357
3358         strlcpy(inname, Cmd_Argv(1), sizeof(inname));
3359         FS_StripExtension(inname, basename, sizeof(basename));
3360
3361         mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
3362         if (mod->brush.submodel)
3363         {
3364                 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
3365                 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
3366                 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
3367                 outname[0] = 0;
3368         }
3369         if (!mod)
3370         {
3371                 Con_Print("No such model\n");
3372                 return;
3373         }
3374         if (!mod->surfmesh.num_triangles)
3375         {
3376                 Con_Print("Empty model (or sprite)\n");
3377                 return;
3378         }
3379
3380         // export OBJ if possible (not on sprites)
3381         if (mod->surfmesh.num_triangles)
3382         {
3383                 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
3384                 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
3385                 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
3386         }
3387
3388         // export SMD if possible (only for skeletal models)
3389         if (mod->surfmesh.num_triangles && mod->num_bones)
3390         {
3391                 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
3392                 Mod_Decompile_SMD(mod, outname, 0, 1, true);
3393                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
3394                 if (l > 0) zymtextsize += l;
3395                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
3396                 if (l > 0) dpmtextsize += l;
3397                 for (i = 0;i < mod->numframes;i = j)
3398                 {
3399                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3400                         first = mod->animscenes[i].firstframe;
3401                         if (mod->animscenes[i].framecount > 1)
3402                         {
3403                                 // framegroup anim
3404                                 count = mod->animscenes[i].framecount;
3405                                 j = i + 1;
3406                         }
3407                         else
3408                         {
3409                                 // individual frame
3410                                 // check for additional frames with same name
3411                                 for (l = 0, k = strlen(animname);animname[l];l++)
3412                                         if(animname[l] < '0' || animname[l] > '9')
3413                                                 k = l + 1;
3414                                 if(k > 0 && animname[k-1] == '_')
3415                                         --k;
3416                                 animname[k] = 0;
3417                                 count = mod->num_poses - first;
3418                                 for (j = i + 1;j < mod->numframes;j++)
3419                                 {
3420                                         strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
3421                                         for (l = 0, k = strlen(animname2);animname2[l];l++)
3422                                                 if(animname2[l] < '0' || animname2[l] > '9')
3423                                                         k = l + 1;
3424                                         if(k > 0 && animname[k-1] == '_')
3425                                                 --k;
3426                                         animname2[k] = 0;
3427                                         if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
3428                                         {
3429                                                 count = mod->animscenes[j].firstframe - first;
3430                                                 break;
3431                                         }
3432                                 }
3433                                 // if it's only one frame, use the original frame name
3434                                 if (j == i + 1)
3435                                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3436                                 
3437                         }
3438                         dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
3439                         Mod_Decompile_SMD(mod, outname, first, count, false);
3440                         if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
3441                         {
3442                                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3443                                 if (l > 0) zymtextsize += l;
3444                         }
3445                         if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
3446                         {
3447                                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3448                                 if (l > 0) dpmtextsize += l;
3449                         }
3450                         if (framegroupstextsize < (int)sizeof(framegroupstextbuffer) - 100)
3451                         {
3452                                 l = dpsnprintf(framegroupstextbuffer + framegroupstextsize, sizeof(framegroupstextbuffer) - framegroupstextsize, "%d %d %f %d // %s\n", first, count, mod->animscenes[i].framerate, mod->animscenes[i].loop, animname);
3453                                 if (l > 0) framegroupstextsize += l;
3454                         }
3455                 }
3456                 if (zymtextsize)
3457                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
3458                 if (dpmtextsize)
3459                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
3460                 if (framegroupstextsize)
3461                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled.framegroups", basename), framegroupstextbuffer, (fs_offset_t)framegroupstextsize);
3462         }
3463 }
3464
3465 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
3466 {
3467         int y;
3468         memset(state, 0, sizeof(*state));
3469         state->width = width;
3470         state->height = height;
3471         state->currentY = 0;
3472         state->rows = (mod_alloclightmap_row_t *)Mem_Alloc(loadmodel->mempool, state->height * sizeof(*state->rows));
3473         for (y = 0;y < state->height;y++)
3474         {
3475                 state->rows[y].currentX = 0;
3476                 state->rows[y].rowY = -1;
3477         }
3478 }
3479
3480 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
3481 {
3482         int y;
3483         state->currentY = 0;
3484         for (y = 0;y < state->height;y++)
3485         {
3486                 state->rows[y].currentX = 0;
3487                 state->rows[y].rowY = -1;
3488         }
3489 }
3490
3491 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
3492 {
3493         if (state->rows)
3494                 Mem_Free(state->rows);
3495         memset(state, 0, sizeof(*state));
3496 }
3497
3498 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
3499 {
3500         mod_alloclightmap_row_t *row;
3501         int y;
3502
3503         row = state->rows + blockheight;
3504         if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
3505         {
3506                 if (state->currentY + blockheight <= state->height)
3507                 {
3508                         // use the current allocation position
3509                         row->rowY = state->currentY;
3510                         row->currentX = 0;
3511                         state->currentY += blockheight;
3512                 }
3513                 else
3514                 {
3515                         // find another position
3516                         for (y = blockheight;y < state->height;y++)
3517                         {
3518                                 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
3519                                 {
3520                                         row = state->rows + y;
3521                                         break;
3522                                 }
3523                         }
3524                         if (y == state->height)
3525                                 return false;
3526                 }
3527         }
3528         *outy = row->rowY;
3529         *outx = row->currentX;
3530         row->currentX += blockwidth;
3531
3532         return true;
3533 }
3534
3535 typedef struct lightmapsample_s
3536 {
3537         float pos[3];
3538         float sh1[4][3];
3539         float *vertex_color;
3540         unsigned char *lm_bgr;
3541         unsigned char *lm_dir;
3542 }
3543 lightmapsample_t;
3544
3545 typedef struct lightmapvertex_s
3546 {
3547         int index;
3548         float pos[3];
3549         float normal[3];
3550         float texcoordbase[2];
3551         float texcoordlightmap[2];
3552         float lightcolor[4];
3553 }
3554 lightmapvertex_t;
3555
3556 typedef struct lightmaptriangle_s
3557 {
3558         int triangleindex;
3559         int surfaceindex;
3560         int lightmapindex;
3561         int axis;
3562         int lmoffset[2];
3563         int lmsize[2];
3564         // 2D modelspace coordinates of min corner
3565         // snapped to lightmap grid but not in grid coordinates
3566         float lmbase[2];
3567         // 2D modelspace to lightmap coordinate scale
3568         float lmscale[2];
3569         float vertex[3][3];
3570         float mins[3];
3571         float maxs[3];
3572 }
3573 lightmaptriangle_t;
3574
3575 typedef struct lightmaplight_s
3576 {
3577         float origin[3];
3578         float radius;
3579         float iradius;
3580         float radius2;
3581         float color[3];
3582         svbsp_t svbsp;
3583 }
3584 lightmaplight_t;
3585
3586 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3587
3588 #define MAX_LIGHTMAPSAMPLES 64
3589 static int mod_generatelightmaps_numoffsets[3];
3590 static float mod_generatelightmaps_offsets[3][MAX_LIGHTMAPSAMPLES][3];
3591
3592 static int mod_generatelightmaps_numlights;
3593 static lightmaplight_t *mod_generatelightmaps_lightinfo;
3594
3595 extern cvar_t r_shadow_lightattenuationdividebias;
3596 extern cvar_t r_shadow_lightattenuationlinearscale;
3597
3598 static void Mod_GenerateLightmaps_LightPoint(dp_model_t *model, const vec3_t pos, vec3_t ambient, vec3_t diffuse, vec3_t lightdir)
3599 {
3600         int i;
3601         int index;
3602         int result;
3603         float relativepoint[3];
3604         float color[3];
3605         float dir[3];
3606         float dist;
3607         float dist2;
3608         float intensity;
3609         float sample[5*3];
3610         float lightorigin[3];
3611         float lightradius;
3612         float lightradius2;
3613         float lightiradius;
3614         float lightcolor[3];
3615         trace_t trace;
3616         for (i = 0;i < 5*3;i++)
3617                 sample[i] = 0.0f;
3618         for (index = 0;;index++)
3619         {
3620                 result = R_Shadow_GetRTLightInfo(index, lightorigin, &lightradius, lightcolor);
3621                 if (result < 0)
3622                         break;
3623                 if (result == 0)
3624                         continue;
3625                 lightradius2 = lightradius * lightradius;
3626                 VectorSubtract(lightorigin, pos, relativepoint);
3627                 dist2 = VectorLength2(relativepoint);
3628                 if (dist2 >= lightradius2)
3629                         continue;
3630                 lightiradius = 1.0f / lightradius;
3631                 dist = sqrt(dist2) * lightiradius;
3632                 intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3633                 if (intensity <= 0.0f)
3634                         continue;
3635                 if (model && model->TraceLine)
3636                 {
3637                         model->TraceLine(model, NULL, NULL, &trace, pos, lightorigin, SUPERCONTENTS_VISBLOCKERMASK);
3638                         if (trace.fraction < 1)
3639                                 continue;
3640                 }
3641                 // scale down intensity to add to both ambient and diffuse
3642                 //intensity *= 0.5f;
3643                 VectorNormalize(relativepoint);
3644                 VectorScale(lightcolor, intensity, color);
3645                 VectorMA(sample    , 0.5f            , color, sample    );
3646                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3647                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3648                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3649                 // calculate a weighted average light direction as well
3650                 intensity *= VectorLength(color);
3651                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3652         }
3653         // calculate the direction we'll use to reduce the sample to a directional light source
3654         VectorCopy(sample + 12, dir);
3655         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3656         VectorNormalize(dir);
3657         // extract the diffuse color along the chosen direction and scale it
3658         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
3659         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
3660         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
3661         // subtract some of diffuse from ambient
3662         VectorMA(sample, -0.333f, diffuse, ambient);
3663         // store the normalized lightdir
3664         VectorCopy(dir, lightdir);
3665 }
3666
3667 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(const dp_model_t *model, svbsp_t *svbsp, const float *mins, const float *maxs)
3668 {
3669         int surfaceindex;
3670         int triangleindex;
3671         const msurface_t *surface;
3672         const float *vertex3f = model->surfmesh.data_vertex3f;
3673         const int *element3i = model->surfmesh.data_element3i;
3674         const int *e;
3675         float v2[3][3];
3676         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->nummodelsurfaces;surfaceindex++, surface++)
3677         {
3678                 if (!BoxesOverlap(surface->mins, surface->maxs, mins, maxs))
3679                         continue;
3680                 if (surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW)
3681                         continue;
3682                 for (triangleindex = 0, e = element3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3683                 {
3684                         VectorCopy(vertex3f + 3*e[0], v2[0]);
3685                         VectorCopy(vertex3f + 3*e[1], v2[1]);
3686                         VectorCopy(vertex3f + 3*e[2], v2[2]);
3687                         SVBSP_AddPolygon(svbsp, 3, v2[0], true, NULL, NULL, 0);
3688                 }
3689         }
3690 }
3691
3692 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(dp_model_t *model, lightmaplight_t *lightinfo)
3693 {
3694         int maxnodes = 1<<14;
3695         svbsp_node_t *nodes;
3696         float origin[3];
3697         float mins[3];
3698         float maxs[3];
3699         svbsp_t svbsp;
3700         VectorSet(mins, lightinfo->origin[0] - lightinfo->radius, lightinfo->origin[1] - lightinfo->radius, lightinfo->origin[2] - lightinfo->radius);
3701         VectorSet(maxs, lightinfo->origin[0] + lightinfo->radius, lightinfo->origin[1] + lightinfo->radius, lightinfo->origin[2] + lightinfo->radius);
3702         VectorCopy(lightinfo->origin, origin);
3703         nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3704         for (;;)
3705         {
3706                 SVBSP_Init(&svbsp, origin, maxnodes, nodes);
3707                 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(model, &svbsp, mins, maxs);
3708                 if (svbsp.ranoutofnodes)
3709                 {
3710                         maxnodes *= 16;
3711                         if (maxnodes > 1<<22)
3712                         {
3713                                 Mem_Free(nodes);
3714                                 return;
3715                         }
3716                         Mem_Free(nodes);
3717                         nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3718                 }
3719                 else
3720                         break;
3721         }
3722         if (svbsp.numnodes > 0)
3723         {
3724                 svbsp.nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, svbsp.numnodes * sizeof(*nodes));
3725                 memcpy(svbsp.nodes, nodes, svbsp.numnodes * sizeof(*nodes));
3726                 lightinfo->svbsp = svbsp;
3727         }
3728         Mem_Free(nodes);
3729 }
3730
3731 static void Mod_GenerateLightmaps_CreateLights(dp_model_t *model)
3732 {
3733         int index;
3734         int result;
3735         lightmaplight_t *lightinfo;
3736         float origin[3];
3737         float radius;
3738         float color[3];
3739         mod_generatelightmaps_numlights = 0;
3740         for (index = 0;;index++)
3741         {
3742                 result = R_Shadow_GetRTLightInfo(index, origin, &radius, color);
3743                 if (result < 0)
3744                         break;
3745                 if (result > 0)
3746                         mod_generatelightmaps_numlights++;
3747         }
3748         if (mod_generatelightmaps_numlights > 0)
3749         {
3750                 mod_generatelightmaps_lightinfo = (lightmaplight_t *)Mem_Alloc(tempmempool, mod_generatelightmaps_numlights * sizeof(*mod_generatelightmaps_lightinfo));
3751                 lightinfo = mod_generatelightmaps_lightinfo;
3752                 for (index = 0;;index++)
3753                 {
3754                         result = R_Shadow_GetRTLightInfo(index, lightinfo->origin, &lightinfo->radius, lightinfo->color);
3755                         if (result < 0)
3756                                 break;
3757                         if (result > 0)
3758                                 lightinfo++;
3759                 }
3760         }
3761         for (index = 0, lightinfo = mod_generatelightmaps_lightinfo;index < mod_generatelightmaps_numlights;index++, lightinfo++)
3762         {
3763                 lightinfo->iradius = 1.0f / lightinfo->radius;
3764                 lightinfo->radius2 = lightinfo->radius * lightinfo->radius;
3765                 // TODO: compute svbsp
3766                 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(model, lightinfo);
3767         }
3768 }
3769
3770 static void Mod_GenerateLightmaps_DestroyLights(dp_model_t *model)
3771 {
3772         int i;
3773         if (mod_generatelightmaps_lightinfo)
3774         {
3775                 for (i = 0;i < mod_generatelightmaps_numlights;i++)
3776                         if (mod_generatelightmaps_lightinfo[i].svbsp.nodes)
3777                                 Mem_Free(mod_generatelightmaps_lightinfo[i].svbsp.nodes);
3778                 Mem_Free(mod_generatelightmaps_lightinfo);
3779         }
3780         mod_generatelightmaps_lightinfo = NULL;
3781         mod_generatelightmaps_numlights = 0;
3782 }
3783
3784 static qboolean Mod_GenerateLightmaps_SamplePoint_SVBSP(const svbsp_t *svbsp, const float *pos)
3785 {
3786         const svbsp_node_t *node;
3787         const svbsp_node_t *nodes = svbsp->nodes;
3788         int num = 0;
3789         while (num >= 0)
3790         {
3791                 node = nodes + num;
3792                 num = node->children[DotProduct(node->plane, pos) < node->plane[3]];
3793         }
3794         return num == -1; // true if empty, false if solid (shadowed)
3795 }
3796
3797 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, const float *normal, float *sample, int numoffsets, const float *offsets)
3798 {
3799         int i;
3800         float relativepoint[3];
3801         float color[3];
3802         float offsetpos[3];
3803         float dist;
3804         float dist2;
3805         float intensity;
3806         int offsetindex;
3807         int hits;
3808         int tests;
3809         const lightmaplight_t *lightinfo;
3810         trace_t trace;
3811         for (i = 0;i < 5*3;i++)
3812                 sample[i] = 0.0f;
3813         for (i = 0, lightinfo = mod_generatelightmaps_lightinfo;i < mod_generatelightmaps_numlights;i++, lightinfo++)
3814         {
3815                 //R_SampleRTLights(pos, sample, numoffsets, offsets);
3816                 VectorSubtract(lightinfo->origin, pos, relativepoint);
3817                 // don't accept light from behind a surface, it causes bad shading
3818                 if (normal && DotProduct(relativepoint, normal) <= 0)
3819                         continue;
3820                 dist2 = VectorLength2(relativepoint);
3821                 if (dist2 >= lightinfo->radius2)
3822                         continue;
3823                 dist = sqrt(dist2) * lightinfo->iradius;
3824                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
3825                 if (intensity <= 0)
3826                         continue;
3827                 if (cl.worldmodel && cl.worldmodel->TraceLine && numoffsets > 0)
3828                 {
3829                         hits = 0;
3830                         tests = 1;
3831                         if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, pos))
3832                                 hits++;
3833                         for (offsetindex = 1;offsetindex < numoffsets;offsetindex++)
3834                         {
3835                                 VectorAdd(pos, offsets + 3*offsetindex, offsetpos);
3836                                 if (!normal)
3837                                 {
3838                                         // for light grid we'd better check visibility of the offset point
3839                                         cl.worldmodel->TraceLine(cl.worldmodel, NULL, NULL, &trace, pos, offsetpos, SUPERCONTENTS_VISBLOCKERMASK);
3840                                         if (trace.fraction < 1)
3841                                                 VectorLerp(pos, trace.fraction, offsetpos, offsetpos);
3842                                 }
3843                                 tests++;
3844                                 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, offsetpos))
3845                                         hits++;
3846                         }
3847                         if (!hits)
3848                                 continue;
3849                         // scale intensity according to how many rays succeeded
3850                         // we know one test is valid, half of the rest will fail...
3851                         //if (normal && tests > 1)
3852                         //      intensity *= (tests - 1.0f) / tests;
3853                         intensity *= (float)hits / tests;
3854                 }
3855                 // scale down intensity to add to both ambient and diffuse
3856                 //intensity *= 0.5f;
3857                 VectorNormalize(relativepoint);
3858                 VectorScale(lightinfo->color, intensity, color);
3859                 VectorMA(sample    , 0.5f            , color, sample    );
3860                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3861                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3862                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3863                 // calculate a weighted average light direction as well
3864                 intensity *= VectorLength(color);
3865                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3866         }
3867 }
3868
3869 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3870 {
3871         float sample[5*3];
3872         float color[3];
3873         float dir[3];
3874         float f;
3875         Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[0], mod_generatelightmaps_offsets[0][0]);
3876         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3877         VectorCopy(sample + 12, dir);
3878         VectorNormalize(dir);
3879         //VectorAdd(dir, normal, dir);
3880         //VectorNormalize(dir);
3881         f = DotProduct(dir, normal);
3882         f = max(0, f) * 255.0f;
3883         VectorScale(sample, f, color);
3884         //VectorCopy(normal, dir);
3885         VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3886         lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3887         lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3888         lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3889         lm_bgr[3] = 255;
3890         lm_dir[0] = (unsigned char)dir[2];
3891         lm_dir[1] = (unsigned char)dir[1];
3892         lm_dir[2] = (unsigned char)dir[0];
3893         lm_dir[3] = 255;
3894 }
3895
3896 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3897 {
3898         float sample[5*3];
3899         Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[1], mod_generatelightmaps_offsets[1][0]);
3900         VectorCopy(sample, vertex_color);
3901 }
3902
3903 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3904 {
3905         float sample[5*3];
3906         float ambient[3];
3907         float diffuse[3];
3908         float dir[3];
3909         Mod_GenerateLightmaps_SamplePoint(pos, NULL, sample, mod_generatelightmaps_numoffsets[2], mod_generatelightmaps_offsets[2][0]);
3910         // calculate the direction we'll use to reduce the sample to a directional light source
3911         VectorCopy(sample + 12, dir);
3912         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3913         VectorNormalize(dir);
3914         // extract the diffuse color along the chosen direction and scale it
3915         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]) * 127.5f;
3916         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]) * 127.5f;
3917         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]) * 127.5f;
3918         // scale the ambient from 0-2 to 0-255 and subtract some of diffuse
3919         VectorScale(sample, 127.5f, ambient);
3920         VectorMA(ambient, -0.333f, diffuse, ambient);
3921         // encode to the grid format
3922         s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3923         s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3924         s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3925         s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3926         s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3927         s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3928         if (dir[2] >= 0.99f) {s->diffusepitch = 0;s->diffuseyaw = 0;}
3929         else if (dir[2] <= -0.99f) {s->diffusepitch = 128;s->diffuseyaw = 0;}
3930         else {s->diffusepitch = (unsigned char)(acos(dir[2]) * (127.5f/M_PI));s->diffuseyaw = (unsigned char)(atan2(dir[1], dir[0]) * (127.5f/M_PI));}
3931 }
3932
3933 static void Mod_GenerateLightmaps_InitSampleOffsets(dp_model_t *model)
3934 {
3935         float radius[3];
3936         float temp[3];
3937         int i, j;
3938         memset(mod_generatelightmaps_offsets, 0, sizeof(mod_generatelightmaps_offsets));
3939         mod_generatelightmaps_numoffsets[0] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_lightmapsamples.integer);
3940         mod_generatelightmaps_numoffsets[1] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_vertexsamples.integer);
3941         mod_generatelightmaps_numoffsets[2] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_gridsamples.integer);
3942         radius[0] = mod_generatelightmaps_lightmapradius.value;
3943         radius[1] = mod_generatelightmaps_vertexradius.value;
3944         radius[2] = mod_generatelightmaps_gridradius.value;
3945         for (i = 0;i < 3;i++)
3946         {
3947                 for (j = 1;j < mod_generatelightmaps_numoffsets[i];j++)
3948                 {
3949                         VectorRandom(temp);
3950                         VectorScale(temp, radius[i], mod_generatelightmaps_offsets[i][j]);
3951                 }
3952         }
3953 }
3954
3955 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3956 {
3957         msurface_t *surface;
3958         int surfaceindex;
3959         int i;
3960         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3961         {
3962                 surface = model->data_surfaces + surfaceindex;
3963                 surface->lightmaptexture = NULL;
3964                 surface->deluxemaptexture = NULL;
3965         }
3966         if (model->brushq3.data_lightmaps)
3967         {
3968                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3969                         if (model->brushq3.data_lightmaps[i])
3970                                 R_FreeTexture(model->brushq3.data_lightmaps[i]);
3971                 Mem_Free(model->brushq3.data_lightmaps);
3972                 model->brushq3.data_lightmaps = NULL;
3973         }
3974         if (model->brushq3.data_deluxemaps)
3975         {
3976                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3977                         if (model->brushq3.data_deluxemaps[i])
3978                                 R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3979                 Mem_Free(model->brushq3.data_deluxemaps);
3980                 model->brushq3.data_deluxemaps = NULL;
3981         }
3982 }
3983
3984 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3985 {
3986         msurface_t *surface;
3987         int surfaceindex;
3988         int vertexindex;
3989         int outvertexindex;
3990         int i;
3991         const int *e;
3992         surfmesh_t oldsurfmesh;
3993         size_t size;
3994         unsigned char *data;
3995         oldsurfmesh = model->surfmesh;
3996         model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3997         model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3998         size = 0;
3999         size += model->surfmesh.num_vertices * sizeof(float[3]);
4000         size += model->surfmesh.num_vertices * sizeof(float[3]);
4001         size += model->surfmesh.num_vertices * sizeof(float[3]);
4002         size += model->surfmesh.num_vertices * sizeof(float[3]);
4003         size += model->surfmesh.num_vertices * sizeof(float[2]);
4004         size += model->surfmesh.num_vertices * sizeof(float[2]);
4005         size += model->surfmesh.num_vertices * sizeof(float[4]);
4006         data = (unsigned char *)Mem_Alloc(model->mempool, size);
4007         model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
4008         model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
4009         model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
4010         model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
4011         model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
4012         model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
4013         model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
4014         if (model->surfmesh.num_vertices > 65536)
4015                 model->surfmesh.data_element3s = NULL;
4016
4017         if (model->surfmesh.vertexmesh)
4018                 Mem_Free(model->surfmesh.vertexmesh);
4019         model->surfmesh.vertexmesh = NULL;
4020         if (model->surfmesh.vertex3fbuffer)
4021                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertex3fbuffer);
4022         model->surfmesh.vertex3fbuffer = NULL;
4023         if (model->surfmesh.vertexmeshbuffer)
4024                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertexmeshbuffer);
4025         model->surfmesh.vertexmeshbuffer = NULL;
4026         if (model->surfmesh.data_element3i_indexbuffer)
4027                 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3i_indexbuffer);
4028         model->surfmesh.data_element3i_indexbuffer = NULL;
4029         if (model->surfmesh.data_element3s_indexbuffer)
4030                 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3s_indexbuffer);
4031         model->surfmesh.data_element3s_indexbuffer = NULL;
4032         if (model->surfmesh.vbo_vertexbuffer)
4033                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vbo_vertexbuffer);
4034         model->surfmesh.vbo_vertexbuffer = 0;
4035
4036         // convert all triangles to unique vertex data
4037         outvertexindex = 0;
4038         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4039         {
4040                 surface = model->data_surfaces + surfaceindex;
4041                 surface->num_firstvertex = outvertexindex;
4042                 surface->num_vertices = surface->num_triangles*3;
4043                 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
4044                 for (i = 0;i < surface->num_triangles*3;i++)
4045                 {
4046                         vertexindex = e[i];
4047                         model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
4048                         model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
4049                         model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
4050                         model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
4051                         model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
4052                         model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
4053                         model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
4054                         model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
4055                         model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
4056                         model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
4057                         model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
4058                         model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
4059                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
4060                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
4061                         if (oldsurfmesh.data_texcoordlightmap2f)
4062                         {
4063                                 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
4064                                 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
4065                         }
4066                         if (oldsurfmesh.data_lightmapcolor4f)
4067                         {
4068                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
4069                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
4070                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
4071                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
4072                         }
4073                         else
4074                                 Vector4Set(model->surfmesh.data_lightmapcolor4f + 4*outvertexindex, 1, 1, 1, 1);
4075                         model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
4076                         outvertexindex++;
4077                 }
4078         }
4079         if (model->surfmesh.data_element3s)
4080                 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
4081                         model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
4082
4083         // find and update all submodels to use this new surfmesh data
4084         for (i = 0;i < model->brush.numsubmodels;i++)
4085                 model->brush.submodels[i]->surfmesh = model->surfmesh;
4086 }
4087
4088 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
4089 {
4090         msurface_t *surface;
4091         int surfaceindex;
4092         int i;
4093         int axis;
4094         float normal[3];
4095         const int *e;
4096         lightmaptriangle_t *triangle;
4097         // generate lightmap triangle structs
4098         mod_generatelightmaps_lightmaptriangles = (lightmaptriangle_t *)Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
4099         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4100         {
4101                 surface = model->data_surfaces + surfaceindex;
4102                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4103                 for (i = 0;i < surface->num_triangles;i++)
4104                 {
4105                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4106                         triangle->triangleindex = surface->num_firsttriangle+i;
4107                         triangle->surfaceindex = surfaceindex;
4108                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
4109                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
4110                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
4111                         // calculate bounds of triangle
4112                         triangle->mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
4113                         triangle->mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
4114                         triangle->mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
4115                         triangle->maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
4116                         triangle->maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
4117                         triangle->maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
4118                         // pick an axial projection based on the triangle normal
4119                         TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], normal);
4120                         axis = 0;
4121                         if (fabs(normal[1]) > fabs(normal[axis]))
4122                                 axis = 1;
4123                         if (fabs(normal[2]) > fabs(normal[axis]))
4124                                 axis = 2;
4125                         triangle->axis = axis;
4126                 }
4127         }
4128 }
4129
4130 static void Mod_GenerateLightmaps_DestroyTriangleInformation(dp_model_t *model)
4131 {
4132         if (mod_generatelightmaps_lightmaptriangles)
4133                 Mem_Free(mod_generatelightmaps_lightmaptriangles);
4134         mod_generatelightmaps_lightmaptriangles = NULL;
4135 }
4136
4137 float lmaxis[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
4138
4139 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
4140 {
4141         msurface_t *surface;
4142         int surfaceindex;
4143         int lightmapindex;
4144         int lightmapnumber;
4145         int i;
4146         int j;
4147         int k;
4148         int x;
4149         int y;
4150         int axis;
4151         int axis1;
4152         int axis2;
4153         int retry;
4154         int pixeloffset;
4155         float trianglenormal[3];
4156         float samplecenter[3];
4157         float samplenormal[3];
4158         float temp[3];
4159         float lmiscale[2];
4160         float slopex;
4161         float slopey;
4162         float slopebase;
4163         float lmscalepixels;
4164         float lmmins;
4165         float lmmaxs;
4166         float lm_basescalepixels;
4167         int lm_borderpixels;
4168         int lm_texturesize;
4169         //int lm_maxpixels;
4170         const int *e;
4171         lightmaptriangle_t *triangle;
4172         unsigned char *lightmappixels;
4173         unsigned char *deluxemappixels;
4174         mod_alloclightmap_state_t lmstate;
4175         char vabuf[1024];
4176
4177         // generate lightmap projection information for all triangles
4178         if (model->texturepool == NULL)
4179                 model->texturepool = R_AllocTexturePool();
4180         lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
4181         lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
4182         lm_texturesize = bound(lm_borderpixels*2+1, 64, (int)vid.maxtexturesize_2d);
4183         //lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
4184         Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4185         lightmapnumber = 0;
4186         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4187         {
4188                 surface = model->data_surfaces + surfaceindex;
4189                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4190                 lmscalepixels = lm_basescalepixels;
4191                 for (retry = 0;retry < 30;retry++)
4192                 {
4193                         // after a couple failed attempts, degrade quality to make it fit
4194                         if (retry > 1)
4195                                 lmscalepixels *= 0.5f;
4196                         for (i = 0;i < surface->num_triangles;i++)
4197                         {
4198                                 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4199                                 triangle->lightmapindex = lightmapnumber;
4200                                 // calculate lightmap bounds in 3D pixel coordinates, limit size,
4201                                 // pick two planar axes for projection
4202                                 // lightmap coordinates here are in pixels
4203                                 // lightmap projections are snapped to pixel grid explicitly, such
4204                                 // that two neighboring triangles sharing an edge and projection
4205                                 // axis will have identical sampl espacing along their shared edge
4206                                 k = 0;
4207                                 for (j = 0;j < 3;j++)
4208                                 {
4209                                         if (j == triangle->axis)
4210                                                 continue;
4211                                         lmmins = floor(triangle->mins[j]*lmscalepixels)-lm_borderpixels;
4212                                         lmmaxs = floor(triangle->maxs[j]*lmscalepixels)+lm_borderpixels;
4213                                         triangle->lmsize[k] = (int)(lmmaxs-lmmins);
4214                                         triangle->lmbase[k] = lmmins/lmscalepixels;
4215                                         triangle->lmscale[k] = lmscalepixels;
4216                                         k++;
4217                                 }
4218                                 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
4219                                         break;
4220                         }
4221                         // if all fit in this texture, we're done with this surface
4222                         if (i == surface->num_triangles)
4223                                 break;
4224                         // if we haven't maxed out the lightmap size yet, we retry the
4225                         // entire surface batch...
4226                         if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, (int)vid.maxtexturesize_2d))
4227                         {
4228                                 lm_texturesize *= 2;
4229                                 surfaceindex = -1;
4230                                 lightmapnumber = 0;
4231                                 Mod_AllocLightmap_Free(&lmstate);
4232                                 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4233                                 break;
4234                         }
4235                         // if we have maxed out the lightmap size, and this triangle does
4236                         // not fit in the same texture as the rest of the surface, we have
4237                         // to retry the entire surface in a new texture (can only use one)
4238                         // with multiple retries, the lightmap quality degrades until it
4239                         // fits (or gives up)
4240                         if (surfaceindex > 0)
4241                                 lightmapnumber++;
4242                         Mod_AllocLightmap_Reset(&lmstate);
4243                 }
4244         }
4245         lightmapnumber++;
4246         Mod_AllocLightmap_Free(&lmstate);
4247
4248         // now put triangles together into lightmap textures, and do not allow
4249         // triangles of a surface to go into different textures (as that would
4250         // require rewriting the surface list)
4251         model->brushq3.deluxemapping_modelspace = true;
4252         model->brushq3.deluxemapping = true;
4253         model->brushq3.num_mergedlightmaps = lightmapnumber;
4254         model->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4255         model->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4256         lightmappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4257         deluxemappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4258         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4259         {
4260                 surface = model->data_surfaces + surfaceindex;
4261                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4262                 for (i = 0;i < surface->num_triangles;i++)
4263                 {
4264                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4265                         TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
4266                         VectorNormalize(trianglenormal);
4267                         VectorCopy(trianglenormal, samplenormal); // FIXME: this is supposed to be interpolated per pixel from vertices
4268                         axis = triangle->axis;
4269                         axis1 = axis == 0 ? 1 : 0;
4270                         axis2 = axis == 2 ? 1 : 2;
4271                         lmiscale[0] = 1.0f / triangle->lmscale[0];
4272                         lmiscale[1] = 1.0f / triangle->lmscale[1];
4273                         if (trianglenormal[axis] < 0)
4274                                 VectorNegate(trianglenormal, trianglenormal);
4275                         CrossProduct(lmaxis[axis2], trianglenormal, temp);slopex = temp[axis] / temp[axis1];
4276                         CrossProduct(lmaxis[axis1], trianglenormal, temp);slopey = temp[axis] / temp[axis2];
4277                         slopebase = triangle->vertex[0][axis] - triangle->vertex[0][axis1]*slopex - triangle->vertex[0][axis2]*slopey;
4278                         for (j = 0;j < 3;j++)
4279                         {
4280                                 float *t2f = model->surfmesh.data_texcoordlightmap2f + e[i*3+j]*2;
4281                                 t2f[0] = ((triangle->vertex[j][axis1] - triangle->lmbase[0]) * triangle->lmscale[0] + triangle->lmoffset[0]) / lm_texturesize;
4282                                 t2f[1] = ((triangle->vertex[j][axis2] - triangle->lmbase[1]) * triangle->lmscale[1] + triangle->lmoffset[1]) / lm_texturesize;
4283 #if 0
4284                                 samplecenter[axis1] = (t2f[0]*lm_texturesize-triangle->lmoffset[0])*lmiscale[0] + triangle->lmbase[0];
4285                                 samplecenter[axis2] = (t2f[1]*lm_texturesize-triangle->lmoffset[1])*lmiscale[1] + triangle->lmbase[1];
4286                                 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4287                                 Con_Printf("%f:%f %f:%f %f:%f = %f %f\n", triangle->vertex[j][axis1], samplecenter[axis1], triangle->vertex[j][axis2], samplecenter[axis2], triangle->vertex[j][axis], samplecenter[axis], t2f[0], t2f[1]);
4288 #endif
4289                         }
4290
4291 #if 0
4292                         switch (axis)
4293                         {
4294                         default:
4295                         case 0:
4296                                 forward[0] = 0;
4297                                 forward[1] = 1.0f / triangle->lmscale[0];
4298                                 forward[2] = 0;
4299                                 left[0] = 0;
4300                                 left[1] = 0;
4301                                 left[2] = 1.0f / triangle->lmscale[1];
4302                                 up[0] = 1.0f;
4303                                 up[1] = 0;
4304                                 up[2] = 0;
4305                                 origin[0] = 0;
4306                                 origin[1] = triangle->lmbase[0];
4307                                 origin[2] = triangle->lmbase[1];
4308                                 break;
4309                         case 1:
4310                                 forward[0] = 1.0f / triangle->lmscale[0];
4311                                 forward[1] = 0;
4312                                 forward[2] = 0;
4313                                 left[0] = 0;
4314                                 left[1] = 0;
4315                                 left[2] = 1.0f / triangle->lmscale[1];
4316                                 up[0] = 0;
4317                                 up[1] = 1.0f;
4318                                 up[2] = 0;
4319                                 origin[0] = triangle->lmbase[0];
4320                                 origin[1] = 0;
4321                                 origin[2] = triangle->lmbase[1];
4322                                 break;
4323                         case 2:
4324                                 forward[0] = 1.0f / triangle->lmscale[0];
4325                                 forward[1] = 0;
4326                                 forward[2] = 0;
4327                                 left[0] = 0;
4328                                 left[1] = 1.0f / triangle->lmscale[1];
4329                                 left[2] = 0;
4330                                 up[0] = 0;
4331                                 up[1] = 0;
4332                                 up[2] = 1.0f;
4333                                 origin[0] = triangle->lmbase[0];
4334                                 origin[1] = triangle->lmbase[1];
4335                                 origin[2] = 0;
4336                                 break;
4337                         }
4338                         Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
4339 #endif
4340 #define LM_DIST_EPSILON (1.0f / 32.0f)
4341                         for (y = 0;y < triangle->lmsize[1];y++)
4342                         {
4343                                 pixeloffset = ((triangle->lightmapindex * lm_texturesize + y + triangle->lmoffset[1]) * lm_texturesize + triangle->lmoffset[0]) * 4;
4344                                 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
4345                                 {
4346                                         samplecenter[axis1] = (x+0.5f)*lmiscale[0] + triangle->lmbase[0];
4347                                         samplecenter[axis2] = (y+0.5f)*lmiscale[1] + triangle->lmbase[1];
4348                                         samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4349                                         VectorMA(samplecenter, 0.125f, samplenormal, samplecenter);
4350                                         Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
4351                                 }
4352                         }
4353                 }
4354         }
4355
4356         for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
4357         {
4358                 model->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapindex), lm_texturesize, lm_texturesize, lightmappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4359                 model->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapindex), lm_texturesize, lm_texturesize, deluxemappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4360         }
4361
4362         if (lightmappixels)
4363                 Mem_Free(lightmappixels);
4364         if (deluxemappixels)
4365                 Mem_Free(deluxemappixels);
4366
4367         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4368         {
4369                 surface = model->data_surfaces + surfaceindex;
4370                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4371                 if (!surface->num_triangles)
4372                         continue;
4373                 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
4374                 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
4375                 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
4376                 surface->lightmapinfo = NULL;
4377         }
4378
4379         model->brush.LightPoint = Mod_GenerateLightmaps_LightPoint;
4380         model->brushq1.lightdata = NULL;
4381         model->brushq1.lightmapupdateflags = NULL;
4382         model->brushq1.firstrender = false;
4383         model->brushq1.num_lightstyles = 0;
4384         model->brushq1.data_lightstyleinfo = NULL;
4385         for (i = 0;i < model->brush.numsubmodels;i++)
4386         {
4387                 model->brush.submodels[i]->brushq1.lightmapupdateflags = NULL;
4388                 model->brush.submodels[i]->brushq1.firstrender = false;
4389                 model->brush.submodels[i]->brushq1.num_lightstyles = 0;
4390                 model->brush.submodels[i]->brushq1.data_lightstyleinfo = NULL;
4391         }
4392 }
4393
4394 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
4395 {
4396         int i;
4397         for (i = 0;i < model->surfmesh.num_vertices;i++)
4398                 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
4399 }
4400
4401 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
4402 {
4403         int x;
4404         int y;
4405         int z;
4406         int index = 0;
4407         float pos[3];
4408         for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
4409         {
4410                 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
4411                 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
4412                 {
4413                         pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
4414                         for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
4415                         {
4416                                 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
4417                                 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
4418                         }
4419                 }
4420         }
4421 }
4422
4423 extern cvar_t mod_q3bsp_nolightmaps;
4424 static void Mod_GenerateLightmaps(dp_model_t *model)
4425 {
4426         //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
4427         dp_model_t *oldloadmodel = loadmodel;
4428         loadmodel = model;
4429
4430         Mod_GenerateLightmaps_InitSampleOffsets(model);
4431         Mod_GenerateLightmaps_DestroyLightmaps(model);
4432         Mod_GenerateLightmaps_UnweldTriangles(model);
4433         Mod_GenerateLightmaps_CreateTriangleInformation(model);
4434         Mod_GenerateLightmaps_CreateLights(model);
4435         if(!mod_q3bsp_nolightmaps.integer)
4436                 Mod_GenerateLightmaps_CreateLightmaps(model);
4437         Mod_GenerateLightmaps_UpdateVertexColors(model);
4438         Mod_GenerateLightmaps_UpdateLightGrid(model);
4439         Mod_GenerateLightmaps_DestroyLights(model);
4440         Mod_GenerateLightmaps_DestroyTriangleInformation(model);
4441
4442         loadmodel = oldloadmodel;
4443 }
4444
4445 static void Mod_GenerateLightmaps_f(void)
4446 {
4447         if (Cmd_Argc() != 1)
4448         {
4449                 Con_Printf("usage: mod_generatelightmaps\n");
4450                 return;
4451         }
4452         if (!cl.worldmodel)
4453         {
4454                 Con_Printf("no worldmodel loaded\n");
4455                 return;
4456         }
4457         Mod_GenerateLightmaps(cl.worldmodel);
4458 }