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