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