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