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